<?php
require_once __DIR__ . '/includes/layout.php';
require_login();
require_roles(['Pengguna Biasa', 'Admin Audit', 'Pentadbir Sistem']);
require_department_access($conn, 'pengurusan_pendaftaran', 'read');

$currentPage = basename($_SERVER['PHP_SELF']);
$canUpdateRegistration = has_department_access($conn, 'pengurusan_pendaftaran', 'update');
$stmt = $conn->query("SELECT id, nama, ic, emel, role, jabatan, created_at FROM users WHERE role = 'Pengguna Biasa' AND approval_status = 'pending' ORDER BY created_at ASC");
$pendingUsers = $stmt ? $stmt->fetch_all(MYSQLI_ASSOC) : [];

$extraJs = <<<HTML
<script>
function getRowCheckboxes() {
    return Array.from(document.querySelectorAll('.row-checkbox'));
}
function updateSelectionState() {
    const checkboxes = getRowCheckboxes();
    const checked = checkboxes.filter((item) => item.checked).length;
    const selectedCount = document.getElementById('selected-count');
    if (selectedCount) {
        selectedCount.textContent = checked;
    }
    const selectAll = document.getElementById('select-all');
    if (selectAll) {
        selectAll.checked = checkboxes.length > 0 && checked === checkboxes.length;
    }
}
function toggleSelectAll(source) {
    getRowCheckboxes().forEach((item) => { item.checked = source.checked; });
    updateSelectionState();
}
function selectAllRows() {
    getRowCheckboxes().forEach((item) => { item.checked = true; });
    updateSelectionState();
}
function clearAllRows() {
    getRowCheckboxes().forEach((item) => { item.checked = false; });
    updateSelectionState();
}
function validateBulkSelection(actionLabel) {
    const total = getRowCheckboxes().filter((item) => item.checked).length;
    if (total === 0) {
        alert('Sila pilih sekurang-kurangnya satu pendaftar.');
        return false;
    }
    return confirm('Adakah anda pasti mahu ' + actionLabel + ' ' + total + ' pendaftaran?');
}
updateSelectionState();
</script>
HTML;

render_layout_start('Pengurusan Pendaftaran - Dashboard Audit MAINPP');
?>
<?php if (isset($_GET['success']) && $_GET['success'] === 'approved'): ?>
    <div class="status-message status-success"><?= (int) ($_GET['count'] ?? 1) ?> pendaftaran berjaya diluluskan.</div>
<?php elseif (isset($_GET['success']) && $_GET['success'] === 'rejected'): ?>
    <div class="status-message status-success"><?= (int) ($_GET['count'] ?? 1) ?> pendaftaran berjaya ditolak.</div>
<?php elseif (isset($_GET['error'])): ?>
    <div class="status-message status-danger">Tindakan tidak berjaya diproses.</div>
<?php endif; ?>

<div class="page-card">
    <h3><i class="fa-solid fa-user-clock"></i> Pengurusan Pendaftaran</h3>
</div>

<div class="table-container">
    <form action="proses_pendaftaran.php" method="POST">
        <div class="content-card" style="padding:16px;">
            <div class="button-row" style="margin-top:0; justify-content:space-between;">
                <div class="button-row" style="margin-top:0;">
                    <?php if ($canUpdateRegistration): ?>
                    <button type="button" class="secondary-btn" onclick="selectAllRows()">Pilih Semua</button>
                    <button type="button" class="secondary-btn" onclick="clearAllRows()">Kosongkan Pilihan</button>
                    <span class="field-note"><span id="selected-count">0</span> pendaftar dipilih</span>
                    <?php else: ?>
                    <span class="field-note">Mod lihat sahaja aktif untuk bahagian anda.</span>
                    <?php endif; ?>
                </div>
                <div class="button-row" style="margin-top:0;">
                    <?php if ($canUpdateRegistration): ?>
                    <button type="submit" name="action_type" value="approve" class="success-btn" onclick="return validateBulkSelection('meluluskan')">Diluluskan</button>
                    <button type="submit" name="action_type" value="reject" class="danger-btn" onclick="return validateBulkSelection('menolak')">Tidak Diluluskan</button>
                    <?php else: ?>
                    <span class="field-note">Anda hanya dibenarkan melihat senarai pendaftaran.</span>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <table>
            <thead>
                <tr>
                    <?php if ($canUpdateRegistration): ?>
                    <th style="width:58px; text-align:center;"><input type="checkbox" id="select-all" onclick="toggleSelectAll(this)"></th>
                    <?php endif; ?>
                    <th>Bil</th>
                    <th>Nama</th>
                    <th>No. IC</th>
                    <th>Emel</th>
                    <th>Role</th>
                    <th>Bahagian / Unit</th>
                    <th>Tarikh Daftar</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!empty($pendingUsers)): ?>
                    <?php $bil = 1; foreach ($pendingUsers as $row): ?>
                    <tr>
                        <?php if ($canUpdateRegistration): ?>
                        <td style="text-align:center;"><input type="checkbox" class="row-checkbox" name="user_ids[]" value="<?= (int) $row['id'] ?>" onchange="updateSelectionState()"></td>
                        <?php endif; ?>
                        <td><?= $bil++ ?></td>
                        <td><strong><?= htmlspecialchars($row['nama']) ?></strong></td>
                        <td><?= htmlspecialchars($row['ic']) ?></td>
                        <td><?= htmlspecialchars($row['emel']) ?></td>
                        <td><span class="role-badge"><i class="fa-solid fa-user-lock"></i><?= htmlspecialchars($row['role']) ?></span></td>
                        <td><span class="unit-badge"><i class="fa-solid fa-building"></i><?= htmlspecialchars($row['jabatan']) ?></span></td>
                        <td><?= date('d/m/Y h:i A', strtotime($row['created_at'])) ?></td>
                    </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr><td colspan="<?= $canUpdateRegistration ? 8 : 7 ?>" class="empty-state">Tiada pendaftaran baru yang sedang menunggu kelulusan.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </form>
</div>
<?php render_layout_end($extraJs); ?>
