<?php
require_once __DIR__ . '/../includes/aclhelper.php';
require_login();
$acl = require_acl('can_view');
$user = current_user() ?: [];
$isSuperAdmin = (int)($user['role_id'] ?? 0) === 1;

function admin_col_exists(mysqli $con, string $table, string $column): bool {
    $table = preg_replace('/[^A-Za-z0-9_]/', '', $table);
    $column = $con->real_escape_string($column);
    $result = $con->query("SHOW COLUMNS FROM {$table} LIKE '{$column}'");
    return $result && $result->num_rows > 0;
}

function admin_pick(array $row, array $keys, string $default = ''): string {
    foreach ($keys as $key) {
        if (isset($row[$key]) && trim((string)$row[$key]) !== '') return trim((string)$row[$key]);
    }
    return $default;
}

function admin_int(array $row, array $keys, int $default = 0): int {
    foreach ($keys as $key) {
        if (isset($row[$key])) return (int)$row[$key];
    }
    return $default;
}

function admin_menu_link(array $row): string {
    return admin_pick($row, ['menu_link', 'url', 'link', 'href'], '#');
}

if (!admin_col_exists($con, 'jos_admin_menus', 'parent_id')) {
    $con->query('ALTER TABLE jos_admin_menus ADD COLUMN parent_id INT NOT NULL DEFAULT 0');
}
if (!admin_col_exists($con, 'jos_admin_menus', 'sort_order')) {
    $con->query('ALTER TABLE jos_admin_menus ADD COLUMN sort_order INT NOT NULL DEFAULT 0');
}
if (!admin_col_exists($con, 'jos_admin_menus', 'show_in_menu')) {
    $con->query('ALTER TABLE jos_admin_menus ADD COLUMN show_in_menu TINYINT(1) NOT NULL DEFAULT 1');
}

if (isset($_GET['cleanup_menu_visibility']) && $isSuperAdmin) {
    $visible = ['Dashboard','Masters','D. Masters','Payroll Config','Operations','Payroll','Reports','Employees','Departments','Designations','Locations','Shifts','Leave Types','Holidays','Attendance Rules','Salary Heads','Pay Groups','Payroll Locations','Statutory Settings','Attendance','Manual Attendance','Shift Assign','Leave Requests','Payroll Process','Salary Slip','Payroll Lock','Bank Export','Attendance Report','Employee Report','Payroll Report','Statutory Report'];
    $names = array_map(fn($name) => "'" . $con->real_escape_string($name) . "'", $visible);
    $con->query('UPDATE jos_admin_menus SET show_in_menu=0 WHERE status=1');
    $con->query('UPDATE jos_admin_menus SET show_in_menu=1 WHERE menu_name IN (' . implode(',', $names) . ')');
    $con->query("UPDATE jos_admin_menus SET parent_id=0 WHERE menu_name IN ('Dashboard','Masters','D. Masters','Payroll Config','Operations','Payroll','Reports')");
    $con->query("UPDATE jos_admin_menus SET status=0, show_in_menu=0 WHERE UPPER(menu_name) IN ('SETTINGS','C. PASSWORD','C.PASSWORD','SALARY CONFIG','LOGOUT')");
    header('Content-Type: text/plain; charset=utf-8');
    echo 'Menu visibility cleaned';
    exit;
}

function admin_upsert_menu(mysqli $con, string $name, int $parentId, string $link, string $remarks, int $sort, int $status = 1): int {
    $stmt = $con->prepare('SELECT id FROM jos_admin_menus WHERE menu_name=? LIMIT 1');
    $stmt->bind_param('s', $name);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $id = (int)($row['id'] ?? 0);
    if ($id) {
        $stmt = $con->prepare('UPDATE jos_admin_menus SET parent_id=?, menu_link=?, url=?, remarks=?, sort_order=?, status=? WHERE id=?');
        $stmt->bind_param('isssiii', $parentId, $link, $link, $remarks, $sort, $status, $id);
        $stmt->execute();
        $stmt->close();
        return $id;
    }
    $stmt = $con->prepare('INSERT INTO jos_admin_menus (menu_name, parent_id, menu_link, url, remarks, sort_order, status) VALUES (?,?,?,?,?,?,?)');
    $stmt->bind_param('sisssii', $name, $parentId, $link, $link, $remarks, $sort, $status);
    $stmt->execute();
    $id = (int)$con->insert_id;
    $stmt->close();
    return $id;
}

function admin_grant_menu(mysqli $con, int $roleId, int $menuId): void {
    $stmt = $con->prepare('SELECT id FROM jos_admin_rolemenus WHERE role_id=? AND menu_id=? LIMIT 1');
    $stmt->bind_param('ii', $roleId, $menuId);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    if ($row) {
        $id = (int)$row['id'];
        $stmt = $con->prepare('UPDATE jos_admin_rolemenus SET can_view=1, can_add=1, can_edit=1, can_delete=1, status=1 WHERE id=?');
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $stmt->close();
        return;
    }
    $stmt = $con->prepare('INSERT INTO jos_admin_rolemenus (role_id, menu_id, can_view, can_add, can_edit, can_delete, status) VALUES (?,?,?,?,?,?,?)');
    $one = 1;
    $stmt->bind_param('iiiiiii', $roleId, $menuId, $one, $one, $one, $one, $one);
    $stmt->execute();
    $stmt->close();
}

if (isset($_GET['debug_menu_rows']) && $isSuperAdmin) {
    header('Content-Type: text/plain; charset=utf-8');
    $cols = $con->query('SHOW COLUMNS FROM jos_admin_menus');
    echo "COLUMNS\n";
    if ($cols) while ($c = $cols->fetch_assoc()) echo $c['Field'] . "\n";
    echo "\nROWS\n";
    $q = "SELECT id, menu_name, parent_id, menu_link, url, sort_order, status FROM jos_admin_menus WHERE menu_name IN ('Dashboard','Masters','D. Masters','Payroll Config','Operations','Payroll','Reports','Employees','Salary Heads') OR UPPER(menu_name) IN ('DASHBOARD','MASTERS','D. MASTERS','PAYROLL CONFIG','OPERATIONS','PAYROLL','REPORTS') ORDER BY id ASC";
    $r = $con->query($q);
    if ($r) while ($row = $r->fetch_assoc()) echo json_encode($row) . "\n";
    exit;
}

$notice = '';
$error = '';
$editMenu = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf($_POST['_csrf'] ?? null)) {
        $error = 'Security token expired. Please refresh and try again.';
    } elseif (($_POST['action'] ?? '') === 'save_menu' && ($isSuperAdmin || !empty($acl['can_add']) || !empty($acl['can_edit']))) {
        $id = max(0, (int)($_POST['id'] ?? 0));
        $name = trim((string)($_POST['menu_name'] ?? ''));
        $parentId = max(0, (int)($_POST['parent_id'] ?? 0));
        $link = trim((string)($_POST['menu_link'] ?? '#'));
        $remarks = trim((string)($_POST['remarks'] ?? ''));
        $sort = (int)($_POST['sort_order'] ?? 0);
        $status = !empty($_POST['status']) ? 1 : 0;
        $showInMenu = isset($_POST['show_in_menu']) ? (int)$_POST['show_in_menu'] : 1;
        $showInMenu = $showInMenu ? 1 : 0;

        if ($name === '') {
            $error = 'Menu name is required.';
        } else {
            $fields = [
                'menu_name' => $name,
                'parent_id' => $parentId,
                'menu_link' => $link,
                'url' => $link,
                'remarks' => $remarks,
                'sort_order' => $sort,
                'show_in_menu' => $showInMenu,
                'status' => $status,
            ];
            foreach (array_keys($fields) as $field) {
                if (!admin_col_exists($con, 'jos_admin_menus', $field)) unset($fields[$field]);
            }

            if ($id > 0) {
                $set = [];
                $types = '';
                $values = [];
                foreach ($fields as $field => $value) {
                    $set[] = $field . '=?';
                    $types .= is_int($value) ? 'i' : 's';
                    $values[] = $value;
                }
                $types .= 'i';
                $values[] = $id;
                $stmt = $con->prepare('UPDATE jos_admin_menus SET ' . implode(', ', $set) . ' WHERE id=?');
                $stmt->bind_param($types, ...$values);
                $stmt->execute();
                $stmt->close();
                audit_log('menu.update', 'jos_admin_menus', (string)$id, $name);
                $notice = 'Menu updated successfully.';
            } else {
                $cols = array_keys($fields);
                $placeholders = implode(',', array_fill(0, count($cols), '?'));
                $types = '';
                $values = [];
                foreach ($fields as $value) {
                    $types .= is_int($value) ? 'i' : 's';
                    $values[] = $value;
                }
                $stmt = $con->prepare('INSERT INTO jos_admin_menus (' . implode(',', $cols) . ') VALUES (' . $placeholders . ')');
                $stmt->bind_param($types, ...$values);
                $stmt->execute();
                $id = (int)$con->insert_id;
                $stmt->close();
                audit_log('menu.create', 'jos_admin_menus', (string)$id, $name);
                $notice = 'Menu created successfully.';
            }
        }
    } elseif (($_POST['action'] ?? '') === 'repair_standard' && $isSuperAdmin) {
        $con->query("UPDATE jos_admin_menus SET status=0 WHERE UPPER(menu_name) IN ('SETTINGS','C. PASSWORD','C.PASSWORD','SALARY CONFIG','LOGOUT')");
        $plan = [
            ['Dashboard', 'dashboard.php', 'Console home', 10, []],
            ['Masters', '#', 'Primary HR master data', 20, [['Employees','masters/employees.php','Employee master'],['Departments','masters/departments.php','Department master'],['Designations','masters/designations.php','Designation master'],['Locations','masters/locations.php','Location master']]],
            ['D. Masters', '#', 'Daily attendance masters', 30, [['Shifts','masters/shifts.php','Shift master'],['Leave Types','masters/leave-types.php','Leave type master'],['Holidays','masters/holidays.php','Holiday master'],['Attendance Rules','masters/attendance-rules.php','Attendance rule master']]],
            ['Payroll Config', '#', 'Salary and payroll configuration', 40, [['Salary Heads','payroll-config/salary-heads.php','Earnings and deductions'],['Pay Groups','payroll-config/pay-groups.php','Pay group setup'],['Payroll Locations','payroll-config/payroll-locations.php','Payroll location setup'],['Statutory Settings','payroll-config/statutory-settings.php','PF ESIC PT TDS setup']]],
            ['Operations', '#', 'Daily HR operations', 50, [['Attendance','operations/attendance.php','Attendance operations'],['Manual Attendance','operations/manual-attendance.php','Manual attendance'],['Shift Assign','operations/shift-assign.php','Shift assignment'],['Leave Requests','operations/leave-requests.php','Leave approvals']]],
            ['Payroll', '#', 'Payroll processing', 60, [['Payroll Process','payroll/process.php','Run payroll'],['Salary Slip','payroll/salary-slip.php','Salary slips'],['Payroll Lock','payroll/lock.php','Payroll lock'],['Bank Export','payroll/bank-export.php','Bank export']]],
            ['Reports', '#', 'HR and payroll reports', 70, [['Attendance Report','reports/attendance.php','Attendance report'],['Employee Report','reports/employees.php','Employee report'],['Payroll Report','reports/payroll.php','Payroll report'],['Statutory Report','reports/statutory.php','PF ESIC TDS report']]],
        ];
        foreach ($plan as $top) {
            [$name, $link, $remarks, $sort, $children] = $top;
            $parentId = admin_upsert_menu($con, $name, 0, $link, $remarks, $sort, 1);
            admin_grant_menu($con, 1, $parentId);
            $childSort = $sort * 100;
            foreach ($children as $child) {
                $childId = admin_upsert_menu($con, $child[0], $parentId, $child[1], $child[2], $childSort++, 1);
                admin_grant_menu($con, 1, $childId);
            }
        }
        audit_log('menu.repair_standard', 'jos_admin_menus', null, 'standard menu groups repaired');
        $notice = 'Standard menu groups repaired successfully.';
    } elseif (($_POST['action'] ?? '') === 'save_permission' && $isSuperAdmin) {
        $roleId = max(0, (int)($_POST['role_id'] ?? 0));
        $menuId = max(0, (int)($_POST['menu_id'] ?? 0));
        $canView = !empty($_POST['can_view']) ? 1 : 0;
        $canAdd = !empty($_POST['can_add']) ? 1 : 0;
        $canEdit = !empty($_POST['can_edit']) ? 1 : 0;
        $canDelete = !empty($_POST['can_delete']) ? 1 : 0;
        $status = !empty($_POST['perm_status']) ? 1 : 0;

        if (!$roleId || !$menuId) {
            $error = 'Select both role and menu for permission.';
        } else {
            $stmt = $con->prepare('SELECT id FROM jos_admin_rolemenus WHERE role_id=? AND menu_id=? LIMIT 1');
            $stmt->bind_param('ii', $roleId, $menuId);
            $stmt->execute();
            $existing = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            if ($existing) {
                $id = (int)$existing['id'];
                $stmt = $con->prepare('UPDATE jos_admin_rolemenus SET can_view=?, can_add=?, can_edit=?, can_delete=?, status=? WHERE id=?');
                $stmt->bind_param('iiiiii', $canView, $canAdd, $canEdit, $canDelete, $status, $id);
                $stmt->execute();
                $stmt->close();
            } else {
                $stmt = $con->prepare('INSERT INTO jos_admin_rolemenus (role_id, menu_id, can_view, can_add, can_edit, can_delete, status) VALUES (?,?,?,?,?,?,?)');
                $stmt->bind_param('iiiiiii', $roleId, $menuId, $canView, $canAdd, $canEdit, $canDelete, $status);
                $stmt->execute();
                $stmt->close();
            }
            audit_log('menu.permission', 'jos_admin_rolemenus', (string)$menuId, 'role=' . $roleId);
            $notice = 'Permission saved successfully.';
        }
    }
}

if (isset($_GET['edit'])) {
    $editId = max(0, (int)$_GET['edit']);
    $stmt = $con->prepare('SELECT * FROM jos_admin_menus WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $editId);
    $stmt->execute();
    $editMenu = $stmt->get_result()->fetch_assoc();
    $stmt->close();
}

$menus = [];
$result = $con->query('SELECT * FROM jos_admin_menus ORDER BY parent_id ASC, sort_order ASC, id ASC');
if ($result) while ($row = $result->fetch_assoc()) $menus[] = $row;

$roles = [];
$result = $con->query('SELECT * FROM jos_admin_roles ORDER BY id ASC');
if ($result) while ($row = $result->fetch_assoc()) $roles[] = $row;

$permissions = [];
$result = $con->query('SELECT * FROM jos_admin_rolemenus');
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $permissions[(int)$row['role_id'] . ':' . (int)$row['menu_id']] = $row;
    }
}

function menu_label_by_id(array $menus, int $id): string {
    foreach ($menus as $menu) if ((int)$menu['id'] === $id) return admin_pick($menu, ['menu_name', 'title', 'name'], 'Menu');
    return 'Root';
}

$editId = (int)($editMenu['id'] ?? 0);
$editName = $editMenu ? admin_pick($editMenu, ['menu_name', 'title', 'name'], '') : '';
$editParent = $editMenu ? admin_int($editMenu, ['parent_id'], 0) : 0;
$editLink = $editMenu ? admin_menu_link($editMenu) : '#';
$editRemarks = $editMenu ? admin_pick($editMenu, ['remarks', 'description'], '') : '';
$editSort = $editMenu ? admin_int($editMenu, ['sort_order', 'ordering', 'menu_order', 'sequence', 'display_order'], 0) : 0;
$editStatus = $editMenu ? admin_int($editMenu, ['status'], 1) : 1;
$editShowInMenu = $editMenu ? admin_int($editMenu, ['show_in_menu'], 1) : 1;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Menu & ACL Manager - Attendance Box</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        body { font-family: Inter, system-ui, sans-serif; background:#f8fafc; color:#0f172a; }
        .field { width:100%; border:1px solid #dbe3ef; border-radius:10px; padding:10px 12px; font-size:13px; background:white; outline:none; }
        .field:focus { border-color:#2563eb; box-shadow:0 0 0 3px rgba(37,99,235,.12); }
        .label { display:block; font-size:11px; font-weight:800; color:#64748b; text-transform:uppercase; letter-spacing:.08em; margin-bottom:6px; }
        .btn { display:inline-flex; align-items:center; justify-content:center; gap:8px; border-radius:10px; padding:10px 14px; font-size:13px; font-weight:700; border:1px solid transparent; }
        .btn-primary { background:#1d4ed8; color:white; }
        .btn-soft { background:#eff6ff; color:#1d4ed8; border-color:#bfdbfe; }
        .btn-danger { background:#fff1f2; color:#be123c; border-color:#fecdd3; }
        .card { background:white; border:1px solid #e5edf6; border-radius:14px; box-shadow:0 10px 28px rgba(15,23,42,.05); }
    </style>
</head>
<body>
    <div class="min-h-screen">
        <header class="bg-white border-b border-slate-200 px-6 py-4 flex items-center justify-between">
            <div>
                <div class="text-xs font-bold text-blue-700 uppercase tracking-wide">Attendance Box</div>
                <h1 class="text-xl font-extrabold mt-1">Menu & ACL Manager</h1>
            </div>
            <div class="flex items-center gap-2">
                <a class="btn btn-soft" href="../dashboard.php"><i class="fa-solid fa-arrow-left"></i> Dashboard</a>
                <form method="post" class="inline-flex"><input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>"><input type="hidden" name="action" value="repair_standard"><button class="btn btn-soft" type="submit"><i class="fa-solid fa-screwdriver-wrench"></i> Repair Groups</button></form>
                <a class="btn btn-soft" href="menus.php"><i class="fa-solid fa-rotate"></i> Refresh</a>
            </div>
        </header>

        <main class="p-6 max-w-[1500px] mx-auto space-y-5">
            <?php if ($notice): ?><div class="rounded-xl border border-emerald-200 bg-emerald-50 text-emerald-700 px-4 py-3 text-sm font-semibold"><?= h($notice) ?></div><?php endif; ?>
            <?php if ($error): ?><div class="rounded-xl border border-red-200 bg-red-50 text-red-700 px-4 py-3 text-sm font-semibold"><?= h($error) ?></div><?php endif; ?>

            <section class="grid grid-cols-1 xl:grid-cols-[420px_1fr] gap-5">
                <div class="card p-5">
                    <h2 class="text-base font-extrabold mb-1"><?= $editMenu ? 'Edit Menu' : 'Create Menu' ?></h2>
                    <p class="text-sm text-slate-500 mb-5">Create parent menus and child menus used by the console navigation.</p>
                    <form method="post" class="space-y-4">
                        <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>">
                        <input type="hidden" name="action" value="save_menu">
                        <input type="hidden" name="id" value="<?= $editId ?>">
                        <div>
                            <label class="label">Menu Name</label>
                            <input class="field" name="menu_name" value="<?= h($editName) ?>" placeholder="Payroll Config" required>
                        </div>
                        <div class="grid grid-cols-2 gap-3">
                            <div>
                                <label class="label">Parent</label>
                                <select class="field" name="parent_id">
                                    <option value="0">Root Menu</option>
                                    <?php foreach ($menus as $menu): $mid=(int)$menu['id']; if ($mid === $editId) continue; ?>
                                        <option value="<?= $mid ?>" <?= $editParent === $mid ? 'selected' : '' ?>><?= h(admin_pick($menu, ['menu_name', 'title', 'name'], 'Menu')) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div>
                                <label class="label">Sort Order</label>
                                <input class="field" type="number" name="sort_order" value="<?= $editSort ?>">
                            </div>
                        </div>
                        <div>
                            <label class="label">Menu Link</label>
                            <input class="field" name="menu_link" value="<?= h($editLink) ?>" placeholder="settings/menus.php or #">
                        </div>
                        <div>
                            <label class="label">Remarks</label>
                            <input class="field" name="remarks" value="<?= h($editRemarks) ?>" placeholder="Short menu description">
                        </div>
                        <div>
                            <label class="label">Show in Top Menu</label>
                            <select class="field" name="show_in_menu">
                                <option value="1" <?= $editShowInMenu ? 'selected' : '' ?>>Yes (Visible in Menu)</option>
                                <option value="0" <?= !$editShowInMenu ? 'selected' : '' ?>>No (Hidden - only for ACL)</option>
                            </select>
                        </div>
                        <label class="inline-flex items-center gap-2 text-sm font-semibold text-slate-700">
                            <input type="checkbox" name="status" value="1" <?= $editStatus ? 'checked' : '' ?>> Active
                        </label>
                        <div class="flex gap-2 pt-2">
                            <button class="btn btn-primary" type="submit"><i class="fa-solid fa-floppy-disk"></i> Save Menu</button>
                            <?php if ($editMenu): ?><a class="btn btn-soft" href="menus.php">Cancel</a><?php endif; ?>
                        </div>
                    </form>
                </div>

                <div class="card overflow-hidden">
                    <div class="px-5 py-4 border-b border-slate-100 flex items-center justify-between">
                        <div>
                            <h2 class="text-base font-extrabold">Menu Records</h2>
                            <p class="text-sm text-slate-500">Dashboard navigation reads these records with role permissions.</p>
                        </div>
                    </div>
                    <div class="overflow-auto max-h-[620px]">
                        <table class="w-full text-sm">
                            <thead class="bg-slate-50 text-[11px] uppercase tracking-wide text-slate-500 sticky top-0">
                                <tr>
                                    <th class="text-left px-4 py-3">Menu</th>
                                    <th class="text-left px-4 py-3">Parent</th>
                                    <th class="text-left px-4 py-3">Link</th>
                                    <th class="text-left px-4 py-3">Sort</th>
                                    <th class="text-left px-4 py-3">Menu Type</th>
                                    <th class="text-left px-4 py-3">Status</th>
                                    <th class="text-right px-4 py-3">Action</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100">
                                <?php foreach ($menus as $menu): $mid=(int)$menu['id']; $parent=admin_int($menu, ['parent_id'], 0); ?>
                                    <tr class="hover:bg-slate-50">
                                        <td class="px-4 py-3 font-semibold"><?= h(admin_pick($menu, ['menu_name', 'title', 'name'], 'Menu')) ?></td>
                                        <td class="px-4 py-3 text-slate-500"><?= h(menu_label_by_id($menus, $parent)) ?></td>
                                        <td class="px-4 py-3 text-slate-500"><?= h(admin_menu_link($menu)) ?></td>
                                        <td class="px-4 py-3 text-slate-500"><?= admin_int($menu, ['sort_order', 'ordering', 'menu_order', 'sequence', 'display_order'], 0) ?></td>
                                        <td class="px-4 py-3"><span class="text-xs font-bold px-2 py-1 rounded-full <?= admin_int($menu, ['show_in_menu'], 1) ? 'bg-blue-50 text-blue-700' : 'bg-amber-50 text-amber-700' ?>"><?= admin_int($menu, ['show_in_menu'], 1) ? 'Menu' : 'ACL Only' ?></span></td>
                                        <td class="px-4 py-3"><span class="text-xs font-bold px-2 py-1 rounded-full <?= admin_int($menu, ['status'], 1) ? 'bg-emerald-50 text-emerald-700' : 'bg-slate-100 text-slate-500' ?>"><?= admin_int($menu, ['status'], 1) ? 'Active' : 'Inactive' ?></span></td>
                                        <td class="px-4 py-3 text-right"><a class="btn btn-soft !py-2" href="?edit=<?= $mid ?>"><i class="fa-solid fa-pen"></i> Edit</a></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </section>

            <section class="card p-5">
                <h2 class="text-base font-extrabold mb-1">Role Permissions</h2>
                <p class="text-sm text-slate-500 mb-5">Assign menu access by role. Dashboard and protected pages use these permissions.</p>
                <?php if (!$isSuperAdmin): ?>
                    <div class="rounded-xl bg-amber-50 border border-amber-200 text-amber-700 px-4 py-3 text-sm font-semibold">Only Super Admin can edit role permissions.</div>
                <?php else: ?>
                    <form method="post" class="grid grid-cols-1 lg:grid-cols-[1fr_1fr_auto_auto_auto_auto_auto_auto] gap-3 items-end">
                        <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>">
                        <input type="hidden" name="action" value="save_permission">
                        <div>
                            <label class="label">Role</label>
                            <select class="field" name="role_id" required>
                                <?php foreach ($roles as $role): ?>
                                    <option value="<?= (int)$role['id'] ?>"><?= h(admin_pick($role, ['role_name', 'name', 'title'], 'Role #' . (int)$role['id'])) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div>
                            <label class="label">Menu</label>
                            <select class="field" name="menu_id" required>
                                <?php foreach ($menus as $menu): ?>
                                    <option value="<?= (int)$menu['id'] ?>"><?= h(admin_pick($menu, ['menu_name', 'title', 'name'], 'Menu')) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <?php foreach ([['can_view','View'],['can_add','Add'],['can_edit','Edit'],['can_delete','Delete'],['perm_status','Active']] as $box): ?>
                            <label class="inline-flex items-center gap-2 text-sm font-semibold text-slate-700 pb-3"><input type="checkbox" name="<?= h($box[0]) ?>" value="1" checked> <?= h($box[1]) ?></label>
                        <?php endforeach; ?>
                        <button class="btn btn-primary" type="submit"><i class="fa-solid fa-shield-halved"></i> Save ACL</button>
                    </form>
                <?php endif; ?>

                <div class="overflow-auto mt-5 max-h-[520px] border border-slate-100 rounded-xl">
                    <table class="w-full text-sm">
                        <thead class="bg-slate-50 text-[11px] uppercase tracking-wide text-slate-500 sticky top-0">
                            <tr><th class="text-left px-4 py-3">Role</th><th class="text-left px-4 py-3">Menu</th><th class="px-4 py-3">View</th><th class="px-4 py-3">Add</th><th class="px-4 py-3">Edit</th><th class="px-4 py-3">Delete</th><th class="px-4 py-3">Status</th></tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100">
                            <?php foreach ($roles as $role): foreach ($menus as $menu): $key=(int)$role['id'] . ':' . (int)$menu['id']; $perm=$permissions[$key] ?? null; if (!$perm) continue; ?>
                                <tr class="hover:bg-slate-50">
                                    <td class="px-4 py-3 font-semibold"><?= h(admin_pick($role, ['role_name', 'name', 'title'], 'Role #' . (int)$role['id'])) ?></td>
                                    <td class="px-4 py-3"><?= h(admin_pick($menu, ['menu_name', 'title', 'name'], 'Menu')) ?></td>
                                    <?php foreach (['can_view','can_add','can_edit','can_delete','status'] as $flag): ?>
                                        <td class="px-4 py-3 text-center"><?= !empty($perm[$flag]) ? '<span class="text-emerald-600 font-bold">Yes</span>' : '<span class="text-slate-400">No</span>' ?></td>
                                    <?php endforeach; ?>
                                </tr>
                            <?php endforeach; endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </section>
        </main>
    </div>
</body>
</html>