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

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

$id = $_GET['id'];
$stmt = $pdo->prepare("SELECT * FROM users WHERE id_user = ?");
$stmt->execute([$id]);
$u = $stmt->fetch();

if (!$u) { echo "User tidak ditemukan"; exit; }

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $nama = $_POST['nama_lengkap'];
    $username = $_POST['username'];
    $role = $_POST['role'];
    $posyandu = ($role == 'kader') ? $_POST['id_posyandu'] : null;
    $nik = ($role == 'ibu') ? $_POST['nik_ibu'] : null;

    // Logika update password: Hanya update jika diisi
    if (!empty($_POST['password'])) {
        $pass = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $sql = "UPDATE users SET username=?, password=?, nama_lengkap=?, role=?, id_posyandu=?, nik_ibu=? WHERE id_user=?";
        $params = [$username, $pass, $nama, $role, $posyandu, $nik, $id];
    } else {
        $sql = "UPDATE users SET username=?, nama_lengkap=?, role=?, id_posyandu=?, nik_ibu=? WHERE id_user=?";
        $params = [$username, $nama, $role, $posyandu, $nik, $id];
    }

    $update = $pdo->prepare($sql);
    if ($update->execute($params)) {
        echo "<script>alert('Data Berhasil Diperbarui'); window.location='manage_users.php';</script>";
    }
}

$list_posyandu = $pdo->query("SELECT * FROM posyandu")->fetchAll();
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit User</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</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: 500px;">
                <div class="card-body p-4">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h5 class="fw-bold mb-0">Edit User</h5>
                        <a href="manage_users.php" class="btn-close"></a>
                    </div>
                    
                    <form method="POST">
                        <div class="mb-3">
                            <label class="small fw-bold text-muted">Role Access</label>
                            <select name="role" id="roleSelect" class="form-select bg-light" onchange="toggleForm()" required>
                                <option value="admin" <?= $u['role']=='admin'?'selected':'' ?>>Admin</option>
                                <option value="kader" <?= $u['role']=='kader'?'selected':'' ?>>Kader</option>
                                <option value="ibu" <?= $u['role']=='ibu'?'selected':'' ?>>Ibu Bayi</option>
                            </select>
                        </div>

                        <div class="mb-3">
                            <label class="small fw-bold text-muted">Nama Lengkap</label>
                            <input type="text" name="nama_lengkap" class="form-control" value="<?= $u['nama_lengkap'] ?>" required>
                        </div>

                        <div class="mb-3">
                            <label class="small fw-bold text-muted">Username</label>
                            <input type="text" name="username" class="form-control" value="<?= $u['username'] ?>" required>
                        </div>

                        <div class="mb-3">
                            <label class="small fw-bold text-muted">Password Baru</label>
                            <input type="password" name="password" class="form-control" placeholder="Kosongkan jika tidak diganti">
                            <div class="form-text italic" style="font-size: 0.7rem;">*Isi hanya jika ingin merubah password</div>
                        </div>
                        
                        <div id="div_posyandu" class="mb-3 <?= $u['role']!='kader'?'d-none':'' ?>">
                            <label class="small fw-bold text-muted">Penempatan Posyandu</label>
                            <select name="id_posyandu" class="form-select">
                                <?php foreach($list_posyandu as $p): ?>
                                    <option value="<?= $p['id_posyandu'] ?>" <?= $u['id_posyandu']==$p['id_posyandu']?'selected':'' ?>><?= $p['nama_posyandu'] ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div id="div_nik" class="mb-3 <?= $u['role']!='ibu'?'d-none':'' ?>">
                            <label class="small fw-bold text-muted">NIK Ibu (Username)</label>
                            <input type="text" name="nik_ibu" class="form-control" value="<?= $u['nik_ibu'] ?>" maxlength="16">
                        </div>

                        <div class="mt-4">
                            <button type="submit" class="btn btn-success w-100 py-2 fw-bold rounded-3 shadow-sm">Simpan Perubahan</button>
                            <a href="manage_users.php" class="btn btn-link w-100 mt-2 text-decoration-none text-muted small">Batal / Kembali</a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script>
        function toggleForm() {
            const role = document.getElementById('roleSelect').value;
            document.getElementById('div_posyandu').classList.toggle('d-none', role !== 'kader');
            document.getElementById('div_nik').classList.toggle('d-none', role !== 'ibu');
        }
    </script>
</body>
</html>