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

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

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

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

    $action = $_POST['action'] ?? null;

    if ($action === 'delete_user') {
        $user_id_to_delete = $_POST['user_id'];
        if ($user_id_to_delete == $_SESSION['user_id']) {
            $error = "Anda tidak dapat menghapus akun Anda sendiri!";
        } else {
            try {
                $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
                $stmt->execute([$user_id_to_delete]);
                $message = "Pengguna berhasil dihapus.";
            } catch (PDOException $e) {
                $error = "Gagal menghapus pengguna.";
                error_log($e->getMessage());
            }
        }
    }

    if ($action === 'add_user') {
        $username = $_POST['username'];
        $password = $_POST['password'];
        $role = $_POST['role'];
        if (empty($username) || empty($password) || empty($role)) {
            $error = "Semua field wajib diisi!";
        } else {
            $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
            $stmt->execute([$username]);
            if ($stmt->fetch()) {
                $error = "Username sudah digunakan.";
            } else {
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("INSERT INTO users (username, password, role) VALUES (?, ?, ?)");
                if ($stmt->execute([$username, $hashed_password, $role])) {
                    $message = "Pengguna baru berhasil ditambahkan!";
                } else {
                    $error = "Gagal menambahkan pengguna.";
                }
            }
        }
    }
}

$users = $pdo->query("SELECT id, username, role, created_at FROM users ORDER BY created_at DESC")->fetchAll();
?>
<main class="container mx-auto p-4 md:p-8">
    <a href="index.php" class="text-blue-500 font-semibold hover:underline mb-6 inline-block">&larr; Kembali ke Admin Dashboard</a>
    <h1 class="text-3xl font-bold text-gray-800 mb-8">Kelola 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" role="alert"><?= e($message) ?></div><?php endif; ?>
    <?php if ($error): ?><div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-lg mb-6" role="alert"><?= e($error) ?></div><?php endif; ?>

    <div class="bg-white p-8 rounded-xl shadow-lg mb-10">
        <h2 class="text-2xl font-bold text-gray-800 mb-6">Tambah Pengguna Baru</h2>
        <form action="manage_users.php" method="POST" class="space-y-4">
            <input type="hidden" name="csrf_token" value="<?= e(generate_csrf_token()); ?>">
            <input type="hidden" name="action" value="add_user">
            <div>
                <label for="username" class="text-sm font-semibold text-gray-600 block">Username</label>
                <input type="text" name="username" id="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</label>
                <input type="password" name="password" id="password" class="w-full px-4 py-2 mt-2 border border-gray-300 rounded-lg" required>
            </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 (Siswa)</option>
                    <option value="admin">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">Tambah Pengguna</button>
        </form>
    </div>

    <div class="bg-white rounded-xl shadow-lg overflow-x-auto">
        <table class="w-full text-sm text-left text-gray-600">
            <thead class="text-xs text-gray-700 uppercase bg-gray-50">
                <tr>
                    <th scope="col" class="px-6 py-3">Username</th>
                    <th scope="col" class="px-6 py-3">Role</th>
                    <th scope="col" class="px-6 py-3">Tanggal Bergabung</th>
                    <th scope="col" class="px-6 py-3 text-right">Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($users as $user): ?>
                <tr class="bg-white border-b hover:bg-gray-50">
                    <td class="px-6 py-4 font-semibold text-gray-900"><?= e($user['username']) ?></td>
                    <td class="px-6 py-4"><?= e(ucfirst($user['role'])) ?></td>
                    <td class="px-6 py-4"><?= date('d M Y, H:i', strtotime($user['created_at'])) ?></td>
                    <td class="px-6 py-4 text-right">
                        <div class="flex justify-end gap-4 items-center">
                            <a href="edit_user.php?id=<?= $user['id'] ?>" class="font-medium text-blue-600 hover:underline">Edit</a>
                            <?php if ($user['id'] != $_SESSION['user_id']): ?>
                                <form action="manage_users.php" method="POST" onsubmit="return confirm('Yakin hapus pengguna ini?');">
                                    <input type="hidden" name="csrf_token" value="<?= e(generate_csrf_token()); ?>">
                                    <input type="hidden" name="action" value="delete_user">
                                    <input type="hidden" name="user_id" value="<?= $user['id'] ?>">
                                    <button type="submit" class="font-medium text-red-600 hover:underline">Hapus</button>
                                </form>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</main>
<?php require_once '../includes/footer.php'; ?>