<?php
require_once '../auth/cek_login.php';
require_role('admin');
require_once '../config/koneksi.php';

if (!function_exists('e')) {
    function e($value) {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

$current_user_id = (int)($_SESSION['user_id'] ?? 0);
$pesan = '';
$error = '';
$edit_user = null;

function redirect_pengguna($query = '') {
    header('Location: pengguna.php' . ($query ? '?' . $query : ''));
    exit;
}

if (isset($_GET['hapus'])) {
    $id = (int)$_GET['hapus'];

    if ($id <= 0) {
        redirect_pengguna('err=invalid');
    }

    if ($id === $current_user_id) {
        redirect_pengguna('err=self_delete');
    }

    $stmt = $conn->prepare("SELECT role FROM users WHERE id = ? LIMIT 1");
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $target = $stmt->get_result()->fetch_assoc();

    if (!$target) {
        redirect_pengguna('err=not_found');
    }

    if (($target['role'] ?? '') === 'admin') {
        $admin_count = (int)$conn->query("SELECT COUNT(*) AS total FROM users WHERE role = 'admin'")->fetch_assoc()['total'];
        if ($admin_count <= 1) {
            redirect_pengguna('err=last_admin');
        }
    }

    $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
    $stmt->bind_param('i', $id);
    $stmt->execute();
    redirect_pengguna('hapus_ok=1');
}

if (isset($_GET['edit'])) {
    $id = (int)$_GET['edit'];
    $stmt = $conn->prepare("SELECT id, username, nama_lengkap, role FROM users WHERE id = ? LIMIT 1");
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $edit_user = $stmt->get_result()->fetch_assoc();

    if (!$edit_user) {
        redirect_pengguna('err=not_found');
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = (int)($_POST['id'] ?? 0);
    $username = trim($_POST['username'] ?? '');
    $nama_lengkap = trim($_POST['nama_lengkap'] ?? '');
    $role = $_POST['role'] ?? 'guru';
    $password = $_POST['password'] ?? '';
    $password_confirm = $_POST['password_confirm'] ?? '';

    if ($username === '' || $nama_lengkap === '' || !in_array($role, ['admin', 'guru'], true)) {
        $error = 'Username, nama lengkap, dan role wajib diisi dengan benar.';
    } elseif ($password !== $password_confirm) {
        $error = 'Konfirmasi password tidak sama.';
    } elseif ($id <= 0 && strlen($password) < 6) {
        $error = 'Password pengguna baru minimal 6 karakter.';
    } elseif ($password !== '' && strlen($password) < 6) {
        $error = 'Password minimal 6 karakter.';
    } else {
        $stmt = $conn->prepare("SELECT id FROM users WHERE username = ? AND id <> ? LIMIT 1");
        $stmt->bind_param('si', $username, $id);
        $stmt->execute();
        $duplikat = $stmt->get_result()->fetch_assoc();

        if ($duplikat) {
            $error = 'Username sudah digunakan oleh pengguna lain.';
        } else {
            if ($id > 0) {
                if ($id === $current_user_id && $role !== 'admin') {
                    $error = 'Anda tidak dapat menurunkan role akun yang sedang digunakan.';
                } else {
                    $stmt = $conn->prepare("SELECT role FROM users WHERE id = ? LIMIT 1");
                    $stmt->bind_param('i', $id);
                    $stmt->execute();
                    $old = $stmt->get_result()->fetch_assoc();

                    if (!$old) {
                        $error = 'Data pengguna tidak ditemukan.';
                    } elseif (($old['role'] ?? '') === 'admin' && $role !== 'admin') {
                        $admin_count = (int)$conn->query("SELECT COUNT(*) AS total FROM users WHERE role = 'admin'")->fetch_assoc()['total'];
                        if ($admin_count <= 1) {
                            $error = 'Minimal harus ada satu akun administrator.';
                        }
                    }
                }

                if ($error === '') {
                    if ($password !== '') {
                        $hash = password_hash($password, PASSWORD_DEFAULT);
                        $stmt = $conn->prepare("UPDATE users SET username = ?, nama_lengkap = ?, role = ?, password = ? WHERE id = ?");
                        $stmt->bind_param('ssssi', $username, $nama_lengkap, $role, $hash, $id);
                    } else {
                        $stmt = $conn->prepare("UPDATE users SET username = ?, nama_lengkap = ?, role = ? WHERE id = ?");
                        $stmt->bind_param('sssi', $username, $nama_lengkap, $role, $id);
                    }
                    $stmt->execute();

                    if ($id === $current_user_id) {
                        $_SESSION['nama_admin'] = $nama_lengkap;
                        $_SESSION['role'] = $role;
                    }

                    redirect_pengguna('edit_ok=1');
                }
            } else {
                $hash = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $conn->prepare("INSERT INTO users(username, password, nama_lengkap, role) VALUES(?, ?, ?, ?)");
                $stmt->bind_param('ssss', $username, $hash, $nama_lengkap, $role);
                $stmt->execute();
                redirect_pengguna('ok=1');
            }
        }
    }

    if ($id > 0) {
        $edit_user = [
            'id' => $id,
            'username' => $username,
            'nama_lengkap' => $nama_lengkap,
            'role' => $role,
        ];
    }
}

include 'header.php';

$users = $conn->query("SELECT id, username, nama_lengkap, role FROM users ORDER BY role ASC, nama_lengkap ASC, username ASC");

if (isset($_GET['ok'])) $pesan = 'Pengguna baru berhasil ditambahkan.';
if (isset($_GET['edit_ok'])) $pesan = 'Data pengguna berhasil diperbarui.';
if (isset($_GET['hapus_ok'])) $pesan = 'Pengguna berhasil dihapus.';

$err_map = [
    'invalid' => 'ID pengguna tidak valid.',
    'self_delete' => 'Anda tidak dapat menghapus akun yang sedang digunakan.',
    'last_admin' => 'Minimal harus ada satu akun administrator.',
    'not_found' => 'Data pengguna tidak ditemukan.',
];
if (isset($_GET['err'], $err_map[$_GET['err']])) $error = $err_map[$_GET['err']];
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <div>
        <h3 class="fw-bold mb-1">Pengaturan Pengguna</h3>
        <div class="text-muted small">Kelola akun administrator dan guru yang dapat masuk ke aplikasi.</div>
    </div>
    <?php if ($edit_user): ?>
        <a href="pengguna.php" class="btn btn-outline-secondary"><i class="fa-solid fa-plus"></i> Tambah Baru</a>
    <?php endif; ?>
</div>

<?php if ($pesan): ?>
    <div class="alert alert-success"><?= e($pesan) ?></div>
<?php endif; ?>

<?php if ($error): ?>
    <div class="alert alert-danger"><?= e($error) ?></div>
<?php endif; ?>

<div class="row g-3">
    <div class="col-lg-4">
        <form method="post" class="card p-3">
            <h5 class="fw-bold mb-3"><?= $edit_user ? 'Edit Pengguna' : 'Tambah Pengguna' ?></h5>
            <input type="hidden" name="id" value="<?= e($edit_user['id'] ?? 0) ?>">

            <div class="mb-3">
                <label class="form-label">Nama Lengkap</label>
                <input name="nama_lengkap" class="form-control" required value="<?= e($edit_user['nama_lengkap'] ?? '') ?>" placeholder="Contoh: Guru Kelas 6">
            </div>

            <div class="mb-3">
                <label class="form-label">Username</label>
                <input name="username" class="form-control" required value="<?= e($edit_user['username'] ?? '') ?>" placeholder="Contoh: guru">
            </div>

            <div class="mb-3">
                <label class="form-label">Role</label>
                <select name="role" class="form-select" required>
                    <?php $selected_role = $edit_user['role'] ?? 'guru'; ?>
                    <option value="admin" <?= $selected_role === 'admin' ? 'selected' : '' ?>>Administrator</option>
                    <option value="guru" <?= $selected_role === 'guru' ? 'selected' : '' ?>>Guru</option>
                </select>
                <div class="form-text">Admin dapat mengelola semua data. Guru hanya dapat mengakses menu yang diizinkan.</div>
            </div>

            <div class="mb-3">
                <label class="form-label">Password <?= $edit_user ? 'Baru' : '' ?></label>
                <input type="password" name="password" class="form-control" <?= $edit_user ? '' : 'required' ?> minlength="6" placeholder="Minimal 6 karakter">
                <?php if ($edit_user): ?>
                    <div class="form-text">Kosongkan jika tidak ingin mengganti password.</div>
                <?php endif; ?>
            </div>

            <div class="mb-3">
                <label class="form-label">Konfirmasi Password</label>
                <input type="password" name="password_confirm" class="form-control" <?= $edit_user ? '' : 'required' ?> minlength="6" placeholder="Ulangi password">
            </div>

            <button class="btn btn-primary"><i class="fa-solid fa-save"></i> <?= $edit_user ? 'Update' : 'Simpan' ?></button>
            <?php if ($edit_user): ?>
                <a href="pengguna.php" class="btn btn-secondary mt-2">Batal</a>
            <?php endif; ?>
        </form>
    </div>

    <div class="col-lg-8">
        <div class="card p-3 table-responsive">
            <table class="table table-bordered table-striped align-middle">
                <thead>
                    <tr>
                        <th width="60">No</th>
                        <th>Nama Lengkap</th>
                        <th>Username</th>
                        <th width="130">Role</th>
                        <th width="170">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $no = 1; while ($row = $users->fetch_assoc()): ?>
                        <tr>
                            <td><?= $no++ ?></td>
                            <td><?= e($row['nama_lengkap']) ?></td>
                            <td><?= e($row['username']) ?></td>
                            <td>
                                <span class="badge <?= $row['role'] === 'admin' ? 'bg-primary' : 'bg-success' ?>">
                                    <?= $row['role'] === 'admin' ? 'Administrator' : 'Guru' ?>
                                </span>
                            </td>
                            <td>
                                <a href="pengguna.php?edit=<?= (int)$row['id'] ?>" class="btn btn-sm btn-warning"><i class="fa-solid fa-pen"></i> Edit</a>
                                <?php if ((int)$row['id'] !== $current_user_id): ?>
                                    <a href="pengguna.php?hapus=<?= (int)$row['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Hapus pengguna ini?')"><i class="fa-solid fa-trash"></i> Hapus</a>
                                <?php else: ?>
                                    <button class="btn btn-sm btn-secondary" disabled>Akun aktif</button>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endwhile; ?>

                    <?php if ($no === 1): ?>
                        <tr>
                            <td colspan="5" class="text-center text-muted">Belum ada data pengguna.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php include 'footer.php'; ?>
