<?php
require_once __DIR__ . '/includes/functions.php';
requireRole(['admin']);
$pageTitle = 'Pengguna';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'save') {
        $id = $_POST['id'] ?? '';
        $username = trim($_POST['username']);
        $nama = trim($_POST['nama']);
        $role = $_POST['role'];
        $status = $_POST['status'];
        $password = $_POST['password'] ?? '';

        if ($id) {
            if ($password) {
                $hash = password_hash($password, PASSWORD_DEFAULT);
                $pdo->prepare("UPDATE users SET username=:u, nama=:n, role=:r, status=:s, password=:p WHERE id=:id")
                    ->execute(['u'=>$username,'n'=>$nama,'r'=>$role,'s'=>$status,'p'=>$hash,'id'=>$id]);
            } else {
                $pdo->prepare("UPDATE users SET username=:u, nama=:n, role=:r, status=:s WHERE id=:id")
                    ->execute(['u'=>$username,'n'=>$nama,'r'=>$role,'s'=>$status,'id'=>$id]);
            }
            flash('success', 'Pengguna berhasil diperbarui.');
        } else {
            $hash = password_hash($password ?: 'password123', PASSWORD_DEFAULT);
            $pdo->prepare("INSERT INTO users (username,password,nama,role,status) VALUES (:u,:p,:n,:r,:s)")
                ->execute(['u'=>$username,'p'=>$hash,'n'=>$nama,'r'=>$role,'s'=>$status]);
            flash('success', 'Pengguna berhasil ditambahkan.');
        }
    } elseif ($action === 'delete') {
        if ($_POST['id'] != currentUser()['id']) {
            $pdo->prepare("DELETE FROM users WHERE id=:id")->execute(['id'=>$_POST['id']]);
            flash('success', 'Pengguna berhasil dihapus.');
        } else {
            flash('error', 'Tidak dapat menghapus akun yang sedang digunakan.');
        }
    }
    header('Location: users.php');
    exit;
}

$data = $pdo->query("SELECT * FROM users ORDER BY nama")->fetchAll();
include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/sidebar.php';
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <h5 class="mb-0">Pengguna Sistem</h5>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalUser" onclick="resetForm()"><i class="bi bi-plus-lg"></i> Tambah Pengguna</button>
</div>

<div class="card">
    <div class="card-body">
        <table class="table table-hover datatable w-100">
            <thead><tr><th>Username</th><th>Nama</th><th>Role</th><th>Status</th><th>Aksi</th></tr></thead>
            <tbody>
            <?php foreach ($data as $row): ?>
                <tr>
                    <td><?= htmlspecialchars($row['username']) ?></td>
                    <td><?= htmlspecialchars($row['nama']) ?></td>
                    <td><span class="badge text-bg-info"><?= ucfirst($row['role']) ?></span></td>
                    <td><span class="badge text-bg-<?= $row['status']==='aktif'?'success':'secondary' ?>"><?= ucfirst($row['status']) ?></span></td>
                    <td>
                        <button class="btn btn-sm btn-outline-primary" onclick='editRow(<?= htmlspecialchars(json_encode($row), ENT_QUOTES) ?>)'><i class="bi bi-pencil"></i></button>
                        <form method="POST" class="d-inline" onsubmit="return confirmDelete()">
                            <input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?= $row['id'] ?>">
                            <button class="btn btn-sm btn-outline-danger"><i class="bi bi-trash"></i></button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<div class="modal fade" id="modalUser" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" class="modal-content">
            <div class="modal-header"><h5 class="modal-title" id="modalTitle">Tambah Pengguna</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <input type="hidden" name="action" value="save"><input type="hidden" name="id" id="f_id">
                <div class="mb-3"><label class="form-label">Username</label><input type="text" name="username" id="f_username" class="form-control" required></div>
                <div class="mb-3"><label class="form-label">Nama Lengkap</label><input type="text" name="nama" id="f_nama" class="form-control" required></div>
                <div class="mb-3">
                    <label class="form-label">Role</label>
                    <select name="role" id="f_role" class="form-select">
                        <option value="admin">Admin</option>
                        <option value="bendahara">Bendahara</option>
                        <option value="kepala_sekolah">Kepala Sekolah</option>
                    </select>
                </div>
                <div class="mb-3"><label class="form-label">Password <small class="text-muted">(kosongkan jika tidak diubah)</small></label><input type="password" name="password" class="form-control"></div>
                <div class="mb-3">
                    <label class="form-label">Status</label>
                    <select name="status" id="f_status" class="form-select"><option value="aktif">Aktif</option><option value="nonaktif">Nonaktif</option></select>
                </div>
            </div>
            <div class="modal-footer"><button type="button" class="btn btn-light" data-bs-dismiss="modal">Batal</button><button class="btn btn-primary">Simpan</button></div>
        </form>
    </div>
</div>

<script>
function resetForm() {
    document.getElementById('modalTitle').innerText = 'Tambah Pengguna';
    document.getElementById('f_id').value = '';
    document.getElementById('f_username').value = '';
    document.getElementById('f_nama').value = '';
    document.getElementById('f_role').value = 'bendahara';
    document.getElementById('f_status').value = 'aktif';
}
function editRow(row) {
    document.getElementById('modalTitle').innerText = 'Edit Pengguna';
    document.getElementById('f_id').value = row.id;
    document.getElementById('f_username').value = row.username;
    document.getElementById('f_nama').value = row.nama;
    document.getElementById('f_role').value = row.role;
    document.getElementById('f_status').value = row.status;
    new bootstrap.Modal(document.getElementById('modalUser')).show();
}
</script>

<?php include __DIR__ . '/includes/footer.php'; ?>