<?php
session_start();
require_once '../config.php';

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../login.php"); exit;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $user = $_POST['username'];
    // Password di-hash agar aman
    $pass = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $nama = $_POST['nama_lengkap'];
    $role = $_POST['role'];
    $posyandu = ($role == 'kader') ? $_POST['id_posyandu'] : null;
    $nik = ($role == 'ibu') ? $_POST['nik_ibu'] : null;

    // Cek apakah username sudah ada
    $cek = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = ?");
    $cek->execute([$user]);
    
    if ($cek->fetchColumn() > 0) {
        echo "<script>alert('Error: Username sudah digunakan!'); window.history.back();</script>";
    } else {
        $stmt = $pdo->prepare("INSERT INTO users (username, password, nama_lengkap, role, id_posyandu, nik_ibu) VALUES (?,?,?,?,?,?)");
        if ($stmt->execute([$user, $pass, $nama, $role, $posyandu, $nik])) {
            echo "<script>alert('User Berhasil Ditambahkan'); window.location='manage_users.php';</script>";
        }
    }
}
$list_posyandu = $pdo->query("SELECT * FROM posyandu ORDER BY nama_posyandu ASC")->fetchAll();
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tambah User Baru</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body class="bg-light">
    <?php include 'sidebar.php'; ?>

    <div class="main-content">
        <div class="container-fluid">
            <div class="card border-0 shadow-sm rounded-4 mx-auto" style="max-width: 550px;">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center mb-4">
                        <a href="manage_users.php" class="btn btn-sm btn-light me-3"><i class="fa fa-arrow-left"></i></a>
                        <h5 class="fw-bold mb-0">Tambah User Baru</h5>
                    </div>

                    <form method="POST">
                        <div class="mb-3">
                            <label class="small fw-bold text-secondary">Akses Sebagai</label>
                            <select name="role" id="roleSelect" class="form-select form-select-lg" onchange="toggleForm()" required>
                                <option value="admin">Admin Utama</option>
                                <option value="kader">Kader Posyandu</option>
                                <option value="ibu">Ibu Bayi (Warga)</option>
                            </select>
                        </div>

                        <div class="mb-3">
                            <label class="small fw-bold text-secondary">Nama Lengkap</label>
                            <input type="text" name="nama_lengkap" class="form-control" placeholder="Nama asli user" required>
                        </div>

                        <div id="div_nik" class="mb-3 d-none">
                            <label class="small fw-bold text-danger">NIK Ibu (Username Otomatis)</label>
                            <input type="number" id="nik_input" name="nik_ibu" class="form-control" placeholder="16 Digit NIK" oninput="syncUsername()">
                            <small class="text-muted" style="font-size: 0.7rem;">*Gunakan NIK yang terdaftar di data Balita</small>
                        </div>

                        <div class="mb-3">
                            <label class="small fw-bold text-secondary">Username Login</label>
                            <input type="text" id="username_input" name="username" class="form-control" placeholder="Contoh: admin_desa" required>
                        </div>

                        <div class="mb-3">
                            <label class="small fw-bold text-secondary">Password</label>
                            <input type="password" name="password" class="form-control" placeholder="Minimal 6 karakter" required>
                        </div>

                        <div id="div_posyandu" class="mb-4 d-none">
                            <label class="small fw-bold text-secondary">Tugas di Posyandu</label>
                            <select name="id_posyandu" class="form-select">
                                <option value="">-- Pilih Lokasi Tugas --</option>
                                <?php foreach($list_posyandu as $p): ?>
                                    <option value="<?= $p['id_posyandu'] ?>"><?= $p['nama_posyandu'] ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <hr>
                        <button type="submit" class="btn btn-primary w-100 py-3 fw-bold rounded-3 shadow">
                            <i class="fa fa-save me-2"></i>Simpan User Baru
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script>
        function toggleForm() {
            const role = document.getElementById('roleSelect').value;
            const divPos = document.getElementById('div_posyandu');
            const divNik = document.getElementById('div_nik');
            const userInput = document.getElementById('username_input');

            // Reset tampilan
            divPos.classList.add('d-none');
            divNik.classList.add('d-none');
            userInput.readOnly = false;

            if (role === 'kader') {
                divPos.classList.remove('d-none');
            } else if (role === 'ibu') {
                divNik.classList.remove('d-none');
                userInput.readOnly = true; // Username mengunci ke NIK
            }
        }

        function syncUsername() {
            const role = document.getElementById('roleSelect').value;
            if (role === 'ibu') {
                document.getElementById('username_input').value = document.getElementById('nik_input').value;
            }
        }
    </script>
</body>
</html>