<?php
require_once '../includes/header.php';

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

$user_id = $_GET['id'] ?? null;
if (!$user_id) {
    header('Location: manage_users.php');
    exit;
}

$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    check_csrf(); // Verifikasi token keamanan
    
    $username = $_POST['username'];
    $role = $_POST['role'];
    $password = $_POST['password'];

    if (empty($username) || empty($role)) {
        $error = "Username dan Role tidak boleh kosong.";
    } else {
        $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? AND id != ?");
        $stmt->execute([$username, $user_id]);
        if ($stmt->fetch()) {
            $error = "Username tersebut sudah digunakan oleh pengguna lain.";
        } else {
            try {
                if (!empty($password)) {
                    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                    $stmt = $pdo->prepare("UPDATE users SET username = ?, role = ?, password = ? WHERE id = ?");
                    $stmt->execute([$username, $role, $hashed_password, $user_id]);
                } else {
                    $stmt = $pdo->prepare("UPDATE users SET username = ?, role = ? WHERE id = ?");
                    $stmt->execute([$username, $role, $user_id]);
                }
                $message = "Data pengguna berhasil diperbarui!";
            } catch (PDOException $e) {
                $error = "Gagal memperbarui data pengguna.";
                error_log($e->getMessage());
            }
        }
    }
}

$stmt = $pdo->prepare("SELECT id, username, role FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

if (!$user) {
    header('Location: manage_users.php');
    exit;
}
?>

<main class="container mx-auto p-4 md:p-8">
    <a href="manage_users.php" class="text-blue-500 font-semibold hover:underline mb-6 inline-block">&larr; Kembali ke Kelola Pengguna</a>
    <h1 class="text-3xl font-bold text-gray-800 mb-8">Edit Pengguna</h1>

    <?php if ($message): ?><div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded-lg mb-6"><?= e($message) ?></div><?php endif; ?>
    <?php if ($error): ?><div class="bg-red-100 border-red-400 text-red-700 px-4 py-3 rounded-lg mb-6"><?= e($error) ?></div><?php endif; ?>

    <div class="bg-white p-8 rounded-xl shadow-lg">
        <form action="edit_user.php?id=<?= $user['id'] ?>" method="POST" class="space-y-4">
            <input type="hidden" name="csrf_token" value="<?= e(generate_csrf_token()); ?>">
            <div>
                <label for="username" class="text-sm font-semibold text-gray-600 block">Username</label>
                <input type="text" name="username" id="username" value="<?= e($user['username']) ?>" class="w-full px-4 py-2 mt-2 border border-gray-300 rounded-lg" required>
            </div>
            <div>
                <label for="password" class="text-sm font-semibold text-gray-600 block">Password Baru</label>
                <input type="password" name="password" id="password" class="w-full px-4 py-2 mt-2 border border-gray-300 rounded-lg" placeholder="Kosongkan jika tidak ingin mengubah">
            </div>
            <div>
                <label for="role" class="text-sm font-semibold text-gray-600 block">Role</label>
                <select name="role" id="role" class="w-full px-4 py-2 mt-2 border border-gray-300 rounded-lg" required>
                    <option value="user" <?= $user['role'] == 'user' ? 'selected' : '' ?>>User (Siswa)</option>
                    <option value="admin" <?= $user['role'] == 'admin' ? 'selected' : '' ?>>Admin</option>
                </select>
            </div>
            <button type="submit" class="px-6 py-3 font-semibold text-white bg-blue-500 rounded-lg hover:bg-blue-600">Simpan Perubahan</button>
        </form>
    </div>
</main>
<?php require_once '../includes/footer.php'; ?>