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

// proteksi login admin
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    die("Akses ditolak!");
}

$error = '';
$sukses = '';

// ambil id user
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0) {
    die("ID user tidak valid");
}

// ambil data user
$stmt = $conn->prepare("SELECT * FROM users WHERE id_user = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();

if (!$user) {
    die("Data user tidak ditemukan");
}

// proses update
if (isset($_POST['update'])) {

    $nama_lengkap = $_POST['nama_lengkap'] ?? '';
    $username     = $_POST['username'] ?? '';
    $role         = $_POST['role'] ?? '';
    $status       = $_POST['status'] ?? '';
    $password     = $_POST['password'] ?? '';

    if ($nama_lengkap === '' || $username === '' || $role === '') {
        $error = "Nama, Username, dan Role wajib diisi!";
    } else {

        // cek username dipakai user lain
        $cek = $conn->prepare(
            "SELECT id_user FROM users WHERE username = ? AND id_user != ?"
        );
        $cek->bind_param("si", $username, $id);
        $cek->execute();
        $cek->store_result();

        if ($cek->num_rows > 0) {
            $error = "Username sudah digunakan user lain!";
        } else {

            // jika password diisi
            if ($password !== '') {

                $password_hash = password_hash($password, PASSWORD_DEFAULT);

                $update = $conn->prepare(
                    "UPDATE users 
                     SET nama_lengkap=?, username=?, password=?, role=?, status=? 
                     WHERE id_user=?"
                );
                $update->bind_param(
                    "sssssi",
                    $nama_lengkap,
                    $username,
                    $password_hash,
                    $role,
                    $status,
                    $id
                );

            } else {

                // tanpa ubah password
                $update = $conn->prepare(
                    "UPDATE users 
                     SET nama_lengkap=?, username=?, role=?, status=? 
                     WHERE id_user=?"
                );
                $update->bind_param(
                    "ssssi",
                    $nama_lengkap,
                    $username,
                    $role,
                    $status,
                    $id
                );
            }

            if ($update->execute()) {
                $sukses = "Data user berhasil diperbarui";
            } else {
                $error = "Gagal memperbarui data";
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>Edit User</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

<style>
body{
    background:#f4f6f9;
    padding:25px;
    font-family:"Segoe UI",sans-serif;
}
.card-custom{
    max-width:550px;
    margin:auto;
    background:#fff;
    padding:35px;
    border-radius:14px;
    box-shadow:0 8px 20px rgba(0,0,0,.08);
}
</style>
</head>

<body>

<div class="card-custom">
    <h4 class="mb-4">✏️ Edit User</h4>

    <?php if($error){ ?>
        <div class="alert alert-danger"><?= $error ?></div>
    <?php } ?>

    <?php if($sukses){ ?>
        <div class="alert alert-success">
            <?= $sukses ?>
            <div class="mt-2">
                <a href="users.php" class="btn btn-sm btn-success">Kembali ke Data Users</a>
            </div>
        </div>
    <?php } ?>

    <form method="post">
        <div class="mb-3">
            <label class="form-label">Nama Lengkap *</label>
            <input type="text" name="nama_lengkap" class="form-control"
                   value="<?= htmlspecialchars($user['nama_lengkap']) ?>" required>
        </div>

        <div class="mb-3">
            <label class="form-label">Username *</label>
            <input type="text" name="username" class="form-control"
                   value="<?= htmlspecialchars($user['username']) ?>" required>
        </div>

        <div class="mb-3">
            <label class="form-label">
                Password (kosongkan jika tidak diubah)
            </label>
            <input type="password" name="password" class="form-control">
        </div>

        <div class="mb-3">
            <label class="form-label">Role *</label>
            <select name="role" class="form-select" required>
                <option value="admin" <?= $user['role']=='admin'?'selected':'' ?>>Admin</option>
                <option value="sekolah" <?= $user['role']=='sekolah'?'selected':'' ?>>sekolah</option>
            </select>
        </div>

        <div class="mb-4">
            <label class="form-label">Status</label>
            <select name="status" class="form-select">
                <option value="aktif" <?= $user['status']=='aktif'?'selected':'' ?>>Aktif</option>
                <option value="nonaktif" <?= $user['status']=='nonaktif'?'selected':'' ?>>Nonaktif</option>
            </select>
        </div>

        <div class="d-flex justify-content-between">
            <a href="users.php" class="btn btn-outline-secondary">
                ⬅ Kembali
            </a>
            <button name="update" class="btn btn-primary">
                💾 Update User
            </button>
        </div>
    </form>
</div>

</body>
</html>
