<?php
require_once __DIR__ . '/includes/layout.php';
require_login();

if (current_user_role() !== 'Pentadbir Sistem') {
    render_layout_start('Capaian Bahagian - Dashboard Audit MAINPP');
    ?>
    <div class="content-card access-denied-card">
        <div class="access-denied-icon"><i class="fa-solid fa-lock"></i></div>
        <h3>Akses Tidak Dibenarkan</h3>
        <p>Hanya Pentadbir Sistem dibenarkan mengurus capaian pengguna mengikut bahagian.</p>
        <div class="button-row">
            <a href="dashboard.php" class="primary-btn">Kembali ke Dashboard</a>
        </div>
    </div>
    <?php
    render_layout_end();
    exit();
}

$bahagianList = audit_bahagian_list();
$modules = access_module_options();
$selectedBahagian = trim($_GET['bahagian'] ?? ($bahagianList[0] ?? ''));
$permissions = [];
$activePermissionCount = 0;
$moduleWithAccessCount = 0;
$latestRollback = null;
$userList = [];
$userPermissions = [];
$selectedUser = null;
$selectedUserId = (int) ($_GET['user_id'] ?? 0);

if ($selectedBahagian !== '' && in_array($selectedBahagian, $bahagianList, true)) {
    $userStmt = $conn->prepare("
        SELECT id, nama, emel, role, jabatan
        FROM users
        WHERE jabatan = ?
          AND approval_status = 'active'
          AND account_status = 'active'
        ORDER BY nama ASC, id ASC
    ");
    $userStmt->bind_param('s', $selectedBahagian);
    $userStmt->execute();
    $userList = $userStmt->get_result()->fetch_all(MYSQLI_ASSOC);
}
if ($selectedUserId <= 0 && !empty($userList)) {
    $selectedUserId = (int) ($userList[0]['id'] ?? 0);
}
foreach ($userList as $userRow) {
    if ((int) ($userRow['id'] ?? 0) === $selectedUserId) {
        $selectedUser = $userRow;
        break;
    }
}
if (!$selectedUser && !empty($userList)) {
    $selectedUser = $userList[0];
    $selectedUserId = (int) ($selectedUser['id'] ?? 0);
}

$actionMeta = [
    'create' => ['column' => 'can_create', 'label' => 'Create', 'short' => 'C', 'icon' => 'fa-plus', 'text' => 'Tambah rekod baharu'],
    'read' => ['column' => 'can_read', 'label' => 'Read', 'short' => 'R', 'icon' => 'fa-eye', 'text' => 'Lihat senarai dan detail'],
    'update' => ['column' => 'can_update', 'label' => 'Update', 'short' => 'U', 'icon' => 'fa-pen', 'text' => 'Kemaskini maklumat'],
    'delete' => ['column' => 'can_delete', 'label' => 'Delete', 'short' => 'D', 'icon' => 'fa-trash', 'text' => 'Padam rekod'],
    'rollback' => ['column' => 'can_rollback', 'label' => 'Rollback', 'short' => 'RB', 'icon' => 'fa-rotate-left', 'text' => 'Kembali ke versi sebelumnya'],
];

if ($selectedBahagian !== '' && in_array($selectedBahagian, $bahagianList, true)) {
    $stmt = $conn->prepare("
        SELECT module_key, can_create, can_read, can_update, can_delete, can_rollback
        FROM department_access_permissions
        WHERE jabatan = ?
    ");
    $stmt->bind_param('s', $selectedBahagian);
    $stmt->execute();
    foreach ($stmt->get_result()->fetch_all(MYSQLI_ASSOC) as $row) {
        $permissions[$row['module_key']] = $row;
    }

    $rollbackStmt = $conn->prepare("
        SELECT r.id, r.created_at, u.nama
        FROM department_access_permission_rollbacks r
        LEFT JOIN users u ON u.id = r.created_by
        WHERE r.jabatan = ? AND r.restored_at IS NULL
        ORDER BY r.id DESC
        LIMIT 1
    ");
    $rollbackStmt->bind_param('s', $selectedBahagian);
    $rollbackStmt->execute();
    $latestRollback = $rollbackStmt->get_result()->fetch_assoc();
}

if ($selectedUserId > 0) {
    $userPermissionStmt = $conn->prepare("
        SELECT module_key, can_create, can_read, can_update, can_delete, can_rollback
        FROM user_access_permissions
        WHERE user_id = ?
    ");
    $userPermissionStmt->bind_param('i', $selectedUserId);
    $userPermissionStmt->execute();
    foreach ($userPermissionStmt->get_result()->fetch_all(MYSQLI_ASSOC) as $row) {
        $userPermissions[$row['module_key']] = $row;
    }
}

foreach ($modules as $moduleKey => $moduleLabel) {
    $row = $permissions[$moduleKey] ?? [];
    $allowedActions = access_module_allowed_actions($moduleKey);
    $rowCount = 0;
    foreach ($actionMeta as $action => $meta) {
        if (in_array($action, $allowedActions, true) && !empty($row[$meta['column']])) {
            $rowCount++;
        }
    }
    $activePermissionCount += $rowCount;
    if ($rowCount > 0) {
        $moduleWithAccessCount++;
    }
}

$moduleMeta = [
    'senarai_maklum_balas_audit' => [
        'icon' => 'fa-comments',
        'tag' => 'Maklum Balas',
        'desc' => 'Kawalan capaian kepada senarai maklum balas, detail dan catatan audit.',
    ],
    'senarai_maklumat_audit' => [
        'icon' => 'fa-clipboard-list',
        'tag' => 'Maklumat Audit',
        'desc' => 'Tetapan untuk daftar, lihat, kemaskini dan padam maklumat audit.',
    ],
    'daftar_pengguna' => [
        'icon' => 'fa-user-plus',
        'tag' => 'Daftar',
        'desc' => 'Kawalan capaian untuk membuka borang dan mendaftarkan pengguna baharu.',
    ],
    'pengurusan_pendaftaran' => [
        'icon' => 'fa-user-check',
        'tag' => 'Pendaftaran',
        'desc' => 'Lihat permohonan pendaftaran dan kemaskini status lulus atau tolak.',
    ],
    'senarai_pengguna' => [
        'icon' => 'fa-users-gear',
        'tag' => 'Pengguna',
        'desc' => 'Urus senarai pengguna, peranan dan status akaun pengguna.',
    ],
    'transaksi_log_pengguna' => [
        'icon' => 'fa-clock-rotate-left',
        'tag' => 'Log',
        'desc' => 'Capaian kepada rekod transaksi dan jejak aktiviti pengguna.',
    ],
];

render_layout_start('Capaian Bahagian - Dashboard Audit MAINPP');
?>
<style>
.access-hero {
    position: relative;
    overflow: hidden;
    background:
        radial-gradient(circle at 8% 20%, rgba(0, 218, 67, 0.16) 0, transparent 26%),
        radial-gradient(circle at 92% 0%, rgba(255, 230, 0, 0.18) 0, transparent 28%),
        linear-gradient(135deg, #031512 0%, #06241f 45%, #0b5138 100%);
    color: #fff;
    border-radius: 16px;
    padding: 30px;
    margin-bottom: 22px;
    box-shadow: 0 18px 45px rgba(3, 21, 18, 0.18);
}
.access-hero::before {
    content: "";
    position: absolute;
    inset: 0;
    background:
        linear-gradient(90deg, rgba(255,255,255,0.045) 1px, transparent 1px),
        linear-gradient(0deg, rgba(255,255,255,0.035) 1px, transparent 1px);
    background-size: 44px 44px;
    opacity: 0.34;
}
.access-hero-content {
    position: relative;
    z-index: 1;
    display: grid;
    grid-template-columns: 1fr auto;
    gap: 24px;
    align-items: end;
}
.access-hero h3,
.access-hero p {
    margin: 0;
}
.access-eyebrow {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 7px 12px;
    border-radius: 8px;
    background: rgba(255, 255, 255, 0.12);
    color: #f7e94f;
    font-size: 12px;
    font-weight: 800;
    margin-bottom: 14px;
}
.access-hero h3 {
    color: #fff;
    font-size: 28px;
    margin-bottom: 10px;
}
.access-hero p {
    max-width: 680px;
    color: rgba(255, 255, 255, 0.82);
    line-height: 1.7;
}
.access-filter-card {
    min-width: 360px;
    padding: 16px;
    border-radius: 12px;
    background: rgba(255, 255, 255, 0.11);
    border: 1px solid rgba(255, 255, 255, 0.14);
    backdrop-filter: blur(8px);
}
.access-filter-card label {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;
    color: rgba(255, 255, 255, 0.82);
    font-size: 12px;
    font-weight: 900;
    text-transform: uppercase;
}
.access-filter-card select {
    background: rgba(255, 255, 255, 0.94);
    border: none;
    font-weight: 700;
    min-height: 44px;
}
.access-stats {
    display: grid;
    grid-template-columns: repeat(4, minmax(0, 1fr));
    gap: 16px;
    margin-bottom: 22px;
}
.access-stat {
    background: #fff;
    border: 1px solid #e8eef5;
    border-radius: 12px;
    padding: 18px;
    box-shadow: 0 10px 28px rgba(18, 52, 88, 0.07);
    display: flex;
    align-items: center;
    gap: 14px;
}
.access-stat-icon {
    width: 44px;
    height: 44px;
    border-radius: 10px;
    background: #eef9f1;
    color: #0b7f3a;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
}
.access-stat-number {
    color: #1f3556;
    font-size: 20px;
    font-weight: 900;
    line-height: 1.2;
}
.access-stat-label {
    color: #64748b;
    font-size: 12px;
    font-weight: 800;
    text-transform: uppercase;
    letter-spacing: 0.03em;
}
.rollback-ready {
    color: #b45309;
}
.access-stat-icon.rollback-icon {
    background: #fff7ed;
    color: #c2410c;
}
.access-matrix {
    padding: 0;
    overflow: hidden;
    border-radius: 14px;
}
.access-matrix-head {
    display: grid;
    grid-template-columns: minmax(0, 1fr) auto;
    align-items: center;
    gap: 16px;
    padding: 20px;
    background: #f8fbff;
    border-bottom: 1px solid #e8eef5;
}
.access-matrix-title {
    display: flex;
    align-items: center;
    gap: 10px;
    font-weight: 900;
    color: #1f3556;
    font-size: 18px;
}
.access-matrix-title i {
    width: 36px;
    height: 36px;
    border-radius: 10px;
    background: #e8fff0;
    color: #0b7f3a;
    display: inline-flex;
    align-items: center;
    justify-content: center;
}
.access-matrix-subtitle {
    margin-top: 4px;
    color: #64748b;
    font-size: 13px;
    line-height: 1.5;
}
.access-policy-strip {
    display: grid;
    grid-template-columns: repeat(5, minmax(130px, 1fr));
    gap: 10px;
    padding: 14px 20px;
    background: #fff;
    border-bottom: 1px solid #e8eef5;
}
.access-policy-pill {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 12px;
    border: 1px solid #e8eef5;
    border-radius: 10px;
    background: #fbfdff;
}
.access-policy-pill i {
    width: 30px;
    height: 30px;
    border-radius: 8px;
    background: #eef5ff;
    color: #0d6efd;
    display: inline-flex;
    align-items: center;
    justify-content: center;
}
.access-policy-pill strong {
    display: block;
    color: #1f3556;
    font-size: 13px;
}
.access-policy-pill span {
    display: block;
    margin-top: 2px;
    color: #64748b;
    font-size: 11px;
}
.permission-table th {
    background: #f8fbff;
    color: #1f3556;
    font-size: 12px;
    text-transform: uppercase;
    letter-spacing: 0.04em;
    padding-top: 16px;
    padding-bottom: 16px;
    white-space: nowrap;
}
.permission-table td {
    vertical-align: middle;
}
.permission-table tbody tr {
    transition: background 0.2s ease, box-shadow 0.2s ease;
}
.permission-table tbody tr:hover {
    background: #fbfdff;
}
.permission-table tbody tr.access-row-active {
    background: linear-gradient(90deg, rgba(11, 127, 58, 0.045), transparent 55%);
}
.permission-module {
    min-width: 360px;
}
.module-name {
    display: flex;
    align-items: center;
    gap: 10px;
    font-weight: 900;
    color: #223047;
}
.module-name i {
    flex: 0 0 38px;
    width: 38px;
    height: 38px;
    border-radius: 10px;
    background: #eef5ff;
    color: #0d6efd;
    display: inline-flex;
    align-items: center;
    justify-content: center;
}
.module-copy {
    min-width: 0;
}
.module-title-line {
    display: flex;
    align-items: center;
    gap: 9px;
    flex-wrap: wrap;
}
.module-desc {
    margin-top: 5px;
    color: #64748b;
    font-size: 12px;
    font-weight: 600;
    line-height: 1.45;
}
.module-tag,
.module-status {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    border-radius: 8px;
    padding: 4px 8px;
    font-size: 11px;
    font-weight: 900;
}
.module-tag {
    background: #fff7db;
    color: #9a6200;
}
.module-status {
    background: #edf2f7;
    color: #64748b;
}
.module-status.active {
    background: #dcfce7;
    color: #166534;
}
.permission-cell {
    text-align: center;
    min-width: 124px;
}
.permission-na {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 96px;
    min-height: 30px;
    border-radius: 8px;
    background: #f1f5f9;
    color: #94a3b8;
    font-size: 11px;
    font-weight: 900;
}
.permission-toggle {
    display: inline-flex;
    align-items: center;
    gap: 9px;
    cursor: pointer;
    user-select: none;
    font-size: 12px;
    font-weight: 800;
    color: #475569;
}
.permission-toggle input {
    position: absolute;
    opacity: 0;
    pointer-events: none;
}
.toggle-track {
    position: relative;
    width: 44px;
    height: 24px;
    border-radius: 999px;
    background: #cbd5e1;
    transition: background 0.2s ease;
    flex: 0 0 auto;
}
.toggle-track::after {
    content: "";
    position: absolute;
    top: 3px;
    left: 3px;
    width: 18px;
    height: 18px;
    border-radius: 50%;
    background: #fff;
    box-shadow: 0 2px 6px rgba(15, 23, 42, 0.18);
    transition: transform 0.2s ease;
}
.permission-toggle input:checked + .toggle-track {
    background: #0b7f3a;
}
.permission-toggle input:checked + .toggle-track::after {
    transform: translateX(20px);
}
.access-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding: 18px 20px 20px;
    border-top: 1px solid #e8eef5;
    background: #fff;
}
.access-actions-note {
    margin-right: auto;
    color: #64748b;
    font-size: 12px;
    font-weight: 700;
    align-self: center;
}
.rollback-btn {
    border: none;
    border-radius: 10px;
    background: #fff7ed;
    color: #c2410c;
    font-weight: 900;
    padding: 11px 16px;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 8px;
}
.rollback-btn:hover {
    background: #ffedd5;
}
.rollback-btn:disabled {
    cursor: not-allowed;
    opacity: 0.52;
}
.access-denied-card {
    text-align: center;
    max-width: 620px;
    margin: 40px auto;
}
.access-denied-icon {
    width: 72px;
    height: 72px;
    margin: 0 auto 18px;
    border-radius: 22px;
    background: #fee2e2;
    color: #b91c1c;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28px;
}
html[data-theme="dark"] .access-stat,
html[data-theme="dark"] .access-matrix,
html[data-theme="dark"] .access-actions,
html[data-theme="dark"] .access-policy-strip,
html[data-theme="dark"] .access-policy-pill {
    background: #111827;
    border-color: #263244;
}
html[data-theme="dark"] .access-matrix-head,
html[data-theme="dark"] .permission-table th {
    background: #0f172a;
    border-color: #263244;
}
html[data-theme="dark"] .access-matrix-title,
html[data-theme="dark"] .access-stat-number,
html[data-theme="dark"] .module-name,
html[data-theme="dark"] .access-policy-pill strong {
    color: #e5e7eb;
}
html[data-theme="dark"] .access-matrix-subtitle,
html[data-theme="dark"] .access-stat-label,
html[data-theme="dark"] .permission-toggle,
html[data-theme="dark"] .module-desc,
html[data-theme="dark"] .access-policy-pill span,
html[data-theme="dark"] .access-actions-note {
    color: #94a3b8;
}
html[data-theme="dark"] .rollback-btn {
    background: #431407;
    color: #fdba74;
}
html[data-theme="dark"] .permission-na {
    background: #1f2937;
    color: #64748b;
}
html[data-theme="dark"] .permission-table tbody tr:hover {
    background: #0f172a;
}
html[data-theme="dark"] .permission-table tbody tr.access-row-active {
    background: linear-gradient(90deg, rgba(34, 197, 94, 0.09), transparent 55%);
}
@media (max-width: 900px) {
    .access-hero-content {
        grid-template-columns: 1fr;
    }
    .access-filter-card {
        min-width: 0;
    }
    .access-stats {
        grid-template-columns: 1fr;
    }
    .access-matrix-head,
    .access-policy-strip {
        grid-template-columns: 1fr;
    }
    .permission-module {
        min-width: 280px;
    }
}
</style>

<?php if (isset($_GET['success']) && $_GET['success'] === 'saved'): ?>
    <div class="status-message status-success">Capaian bahagian berjaya dikemaskini.</div>
<?php elseif (isset($_GET['success']) && $_GET['success'] === 'user_saved'): ?>
    <div class="status-message status-success">Capaian khusus pengguna berjaya dikemaskini.</div>
<?php elseif (isset($_GET['success']) && $_GET['success'] === 'rollback'): ?>
    <div class="status-message status-success">Rollback capaian berjaya. Tetapan telah dikembalikan kepada versi sebelumnya.</div>
<?php elseif (isset($_GET['error']) && $_GET['error'] === 'invalid_unit'): ?>
    <div class="status-message status-danger">Bahagian tidak sah.</div>
<?php elseif (isset($_GET['error']) && $_GET['error'] === 'invalid_user'): ?>
    <div class="status-message status-danger">Pengguna tidak sah.</div>
<?php elseif (isset($_GET['error']) && $_GET['error'] === 'no_rollback'): ?>
    <div class="status-message status-danger">Tiada rekod rollback yang tersedia untuk bahagian ini.</div>
<?php elseif (isset($_GET['error']) && $_GET['error'] === 'rollback_failed'): ?>
    <div class="status-message status-danger">Rollback gagal kerana rekod sejarah tidak sah.</div>
<?php endif; ?>

<div class="access-hero">
    <div class="access-hero-content">
        <div>
            <div class="access-eyebrow"><i class="fa-solid fa-shield-halved"></i> Kawalan Capaian Bahagian</div>
            <h3>Capaian Bahagian</h3>
        </div>
        <form method="GET" class="access-filter-card">
            <label for="bahagian"><i class="fa-solid fa-building-user"></i> Bahagian / Unit</label>
            <select id="bahagian" name="bahagian" onchange="this.form.submit()">
                <?php foreach ($bahagianList as $bahagian): ?>
                    <option value="<?= htmlspecialchars($bahagian) ?>" <?= $selectedBahagian === $bahagian ? 'selected' : '' ?>>
                        <?= htmlspecialchars($bahagian) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </form>
    </div>
</div>

<div class="access-stats">
    <div class="access-stat">
        <div class="access-stat-icon"><i class="fa-solid fa-building"></i></div>
        <div>
            <div class="access-stat-number"><?= htmlspecialchars($selectedBahagian) ?></div>
            <div class="access-stat-label">Bahagian Dipilih</div>
        </div>
    </div>
    <div class="access-stat">
        <div class="access-stat-icon"><i class="fa-solid fa-layer-group"></i></div>
        <div>
            <div class="access-stat-number"><?= (int) $moduleWithAccessCount ?>/<?= count($modules) ?></div>
            <div class="access-stat-label">Modul Ada Capaian</div>
        </div>
    </div>
    <div class="access-stat">
        <div class="access-stat-icon"><i class="fa-solid fa-toggle-on"></i></div>
        <div>
            <div class="access-stat-number"><?= (int) $activePermissionCount ?></div>
            <div class="access-stat-label">Permission Aktif</div>
        </div>
    </div>
    <div class="access-stat">
        <div class="access-stat-icon rollback-icon"><i class="fa-solid fa-rotate-left"></i></div>
        <div>
            <div class="access-stat-number <?= $latestRollback ? 'rollback-ready' : '' ?>">
                <?= $latestRollback ? 'Sedia' : 'Tiada' ?>
            </div>
            <div class="access-stat-label">
                <?= $latestRollback ? 'Rollback: ' . date('d/m/Y H:i', strtotime($latestRollback['created_at'])) : 'Rollback Tersedia' ?>
            </div>
        </div>
    </div>
</div>

<form action="proses_capaian_pengguna.php" method="POST" class="table-container access-matrix">
    <input type="hidden" name="bahagian" value="<?= htmlspecialchars($selectedBahagian) ?>">
    <div class="access-matrix-head">
        <div>
            <div class="access-matrix-title"><i class="fa-solid fa-fingerprint"></i> Matriks Capaian: <?= htmlspecialchars($selectedBahagian) ?></div>
            <div class="access-matrix-subtitle">Semua pengguna dalam bahagian ini akan mewarisi tetapan capaian di bawah.</div>
        </div>
    </div>
    <div class="access-policy-strip">
        <?php foreach ($actionMeta as $meta): ?>
            <div class="access-policy-pill">
                <i class="fa-solid <?= htmlspecialchars($meta['icon']) ?>"></i>
                <div>
                    <strong><?= htmlspecialchars($meta['label']) ?></strong>
                    <span><?= htmlspecialchars($meta['text']) ?></span>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
    <table class="permission-table">
        <thead>
            <tr>
                <th>Modul</th>
                <?php foreach ($actionMeta as $meta): ?>
                    <th class="permission-cell"><i class="fa-solid <?= htmlspecialchars($meta['icon']) ?>"></i> <?= htmlspecialchars($meta['label']) ?></th>
                <?php endforeach; ?>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($modules as $moduleKey => $moduleLabel): ?>
                <?php
                $row = $permissions[$moduleKey] ?? [];
                $allowedActions = access_module_allowed_actions($moduleKey);
                $rowPermissionCount = 0;
                foreach ($actionMeta as $action => $meta) {
                    if (in_array($action, $allowedActions, true)) {
                        $rowPermissionCount += (int) !empty($row[$meta['column']]);
                    }
                }
                $meta = $moduleMeta[$moduleKey] ?? ['icon' => 'fa-table-list', 'tag' => 'Modul', 'desc' => 'Tetapan capaian modul sistem.'];
                ?>
                <tr class="<?= $rowPermissionCount > 0 ? 'access-row-active' : '' ?>">
                    <td class="permission-module">
                        <div class="module-name">
                            <i class="fa-solid <?= htmlspecialchars($meta['icon']) ?>"></i>
                            <div class="module-copy">
                                <div class="module-title-line">
                                    <span><?= htmlspecialchars($moduleLabel) ?></span>
                                    <span class="module-tag"><?= htmlspecialchars($meta['tag']) ?></span>
                                    <span class="module-status <?= $rowPermissionCount > 0 ? 'active' : '' ?>">
                                        <?= $rowPermissionCount > 0 ? $rowPermissionCount . ' akses aktif' : 'Tiada akses' ?>
                                    </span>
                                </div>
                                <div class="module-desc"><?= htmlspecialchars($meta['desc']) ?></div>
                            </div>
                        </div>
                    </td>
                    <?php foreach ($actionMeta as $action => $meta): ?>
                    <td class="permission-cell">
                        <?php if (!in_array($action, $allowedActions, true)): ?>
                            <span class="permission-na">Tidak digunakan</span>
                        <?php else: ?>
                        <label class="permission-toggle">
                            <input type="checkbox" name="permissions[<?= htmlspecialchars($moduleKey) ?>][<?= htmlspecialchars($action) ?>]" value="1" <?= !empty($row[$meta['column']]) ? 'checked' : '' ?>>
                            <span class="toggle-track"></span>
                            <span><?= htmlspecialchars($meta['label']) ?></span>
                        </label>
                        <?php endif; ?>
                    </td>
                    <?php endforeach; ?>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <div class="access-actions">
        <span class="access-actions-note">Semak sebelum simpan kerana tetapan ini akan digunakan kepada semua pengguna dalam bahagian dipilih.</span>
        <a href="dashboard.php" class="secondary-btn">Kembali</a>
        <button type="submit" class="primary-btn">Simpan Capaian</button>
    </div>
</form>

<div id="capaian-user" class="access-hero" style="margin-top:24px;">
    <div class="access-hero-content">
        <div>
            <div class="access-eyebrow"><i class="fa-solid fa-user-shield"></i> Kawalan Capaian Individu</div>
            <h3>Capaian Pengguna</h3>
        </div>
        <form method="GET" class="access-filter-card">
            <input type="hidden" name="bahagian" value="<?= htmlspecialchars($selectedBahagian) ?>">
            <label for="user_id"><i class="fa-solid fa-user"></i> Pilih Pengguna</label>
            <select id="user_id" name="user_id" onchange="this.form.submit()">
                <?php foreach ($userList as $user): ?>
                    <option value="<?= (int) $user['id'] ?>" <?= $selectedUserId === (int) $user['id'] ? 'selected' : '' ?>>
                        <?= htmlspecialchars($user['nama'] . ' - ' . $user['emel'] . ' (' . $user['jabatan'] . ')') ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </form>
    </div>
</div>

<?php if ($selectedUser): ?>
<form action="proses_capaian_user.php" method="POST" class="table-container access-matrix">
    <input type="hidden" name="user_id" value="<?= (int) $selectedUserId ?>">
    <input type="hidden" name="bahagian" value="<?= htmlspecialchars($selectedBahagian) ?>">
    <div class="access-matrix-head">
        <div>
            <div class="access-matrix-title"><i class="fa-solid fa-user-lock"></i> Matriks Capaian: <?= htmlspecialchars($selectedUser['nama']) ?></div>
            <div class="access-matrix-subtitle">Tetapan khusus untuk <?= htmlspecialchars($selectedUser['emel']) ?> dalam <?= htmlspecialchars($selectedBahagian) ?>. Default checkbox ikut capaian bahagian; selepas disimpan ia menjadi capaian khusus pengguna.</div>
        </div>
    </div>
    <table class="permission-table">
        <thead>
            <tr>
                <th>Modul</th>
                <?php foreach ($actionMeta as $meta): ?>
                    <th class="permission-cell"><i class="fa-solid <?= htmlspecialchars($meta['icon']) ?>"></i> <?= htmlspecialchars($meta['label']) ?></th>
                <?php endforeach; ?>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($modules as $moduleKey => $moduleLabel): ?>
                <?php
                $row = $userPermissions[$moduleKey] ?? ($permissions[$moduleKey] ?? []);
                $hasUserOverride = isset($userPermissions[$moduleKey]);
                $allowedActions = access_module_allowed_actions($moduleKey);
                $rowPermissionCount = 0;
                foreach ($actionMeta as $action => $meta) {
                    if (in_array($action, $allowedActions, true)) {
                        $rowPermissionCount += (int) !empty($row[$meta['column']]);
                    }
                }
                $meta = $moduleMeta[$moduleKey] ?? ['icon' => 'fa-table-list', 'tag' => 'Modul', 'desc' => 'Tetapan capaian modul sistem.'];
                ?>
                <tr class="<?= $rowPermissionCount > 0 ? 'access-row-active' : '' ?>">
                    <td class="permission-module">
                        <div class="module-name">
                            <i class="fa-solid <?= htmlspecialchars($meta['icon']) ?>"></i>
                            <div class="module-copy">
                                <div class="module-title-line">
                                    <span><?= htmlspecialchars($moduleLabel) ?></span>
                                    <span class="module-tag"><?= htmlspecialchars($meta['tag']) ?></span>
                                    <span class="module-status <?= $rowPermissionCount > 0 ? 'active' : '' ?>">
                                        <?= $hasUserOverride ? ($rowPermissionCount > 0 ? $rowPermissionCount . ' akses khusus' : 'Tiada akses khusus') : 'Ikut bahagian' ?>
                                    </span>
                                </div>
                                <div class="module-desc"><?= htmlspecialchars($meta['desc']) ?></div>
                            </div>
                        </div>
                    </td>
                    <?php foreach ($actionMeta as $action => $meta): ?>
                    <td class="permission-cell">
                        <?php if (!in_array($action, $allowedActions, true)): ?>
                            <span class="permission-na">Tidak digunakan</span>
                        <?php else: ?>
                        <label class="permission-toggle">
                            <input type="checkbox" name="permissions[<?= htmlspecialchars($moduleKey) ?>][<?= htmlspecialchars($action) ?>]" value="1" <?= !empty($row[$meta['column']]) ? 'checked' : '' ?>>
                            <span class="toggle-track"></span>
                            <span><?= htmlspecialchars($meta['label']) ?></span>
                        </label>
                        <?php endif; ?>
                    </td>
                    <?php endforeach; ?>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <div class="access-actions">
        <span class="access-actions-note">Tetapan ini hanya untuk pengguna yang dipilih dan akan override capaian bahagian.</span>
        <a href="dashboard.php" class="secondary-btn">Kembali</a>
        <button type="submit" class="primary-btn">Simpan Capaian User</button>
    </div>
</form>
<?php else: ?>
<div class="content-card">Tiada pengguna aktif ditemui untuk ditetapkan capaian individu.</div>
<?php endif; ?>
<?php render_layout_end(); ?>
