<?php
require_once 'auth.php';
include 'db.php';
requireLogin($conn);

// Semak status & role
$user_email = $_SESSION['email'] ?? '';
$check_status = mysqli_prepare($conn, "SELECT status, role FROM users WHERE email = ?");
mysqli_stmt_bind_param($check_status, "s", $user_email);
mysqli_stmt_execute($check_status);
$status_result = mysqli_stmt_get_result($check_status);
$user_data = mysqli_fetch_assoc($status_result);

if (!$user_data || $user_data['status'] !== 'approved') {
    destroyActiveSession();
    header("Location: login.php?error=account_blocked");
    exit();
}

if (!isset($_SESSION['role'])) {
    $_SESSION['role'] = $user_data['role'] ?? 'user';
}

$role = $_SESSION['role'];
$user_department = currentUserDepartment($conn);
$current_user_id = (int) ($_SESSION['user_id'] ?? 0);

// DAPATKAN SEMUA BAHAGIAN YANG ADA FOLDER (UNTUK SEMUA ROLE)
if ($role === 'superadmin') {
    $sql_depts = "SELECT DISTINCT department FROM folders WHERE department != '' AND deleted_at IS NULL ORDER BY department";
    $result_depts = mysqli_query($conn, $sql_depts);
} else {
    $sql_depts = "SELECT DISTINCT department FROM folders WHERE department = ? AND department != '' AND deleted_at IS NULL ORDER BY department";
    $stmt_depts = mysqli_prepare($conn, $sql_depts);
    mysqli_stmt_bind_param($stmt_depts, "s", $user_department);
    mysqli_stmt_execute($stmt_depts);
    $result_depts = mysqli_stmt_get_result($stmt_depts);
}
$available_depts = $result_depts ? mysqli_fetch_all($result_depts, MYSQLI_ASSOC) : [];

// DAPATKAN DATA UNTUK SETIAP BAHAGIAN
$dept_data = [];
foreach ($available_depts as $dept_row) {
    $dept_name = $dept_row['department'];
    
    // Total fail untuk bahagian ini
    $sql_total = "SELECT COUNT(*) as total FROM folders WHERE department = ? AND deleted_at IS NULL";
    $stmt_total = mysqli_prepare($conn, $sql_total);
    mysqli_stmt_bind_param($stmt_total, "s", $dept_name);
    mysqli_stmt_execute($stmt_total);
    $total_result = mysqli_stmt_get_result($stmt_total);
    $total_folders = mysqli_fetch_assoc($total_result)['total'];
    
    // Senarai fail dengan current file number (latest) - SEMUA fail dalam bahagian
    $visible_document_filter = "d.folder_id = f.id
                        AND d.deleted_at IS NULL
                        AND (
                            ld.id IS NULL
                            OR NOT (ld.status = 'draf' OR ld.approval_status = 'draft')
                            OR ld.created_by = ?
                            OR ? = 'superadmin'
                        )";
    $sql_folders = "SELECT f.id, f.folder_code, f.folder_name, f.folder_type,
                    (SELECT d.ref_no FROM documents d LEFT JOIN letter_drafts ld ON ld.document_id = d.id AND ld.deleted_at IS NULL WHERE {$visible_document_filter} ORDER BY d.id DESC LIMIT 1) as latest_ref_no,
                    (SELECT d.file_numbering FROM documents d LEFT JOIN letter_drafts ld ON ld.document_id = d.id AND ld.deleted_at IS NULL WHERE {$visible_document_filter} ORDER BY d.id DESC LIMIT 1) as latest_file_numbering,
                    (SELECT COUNT(*) FROM documents d LEFT JOIN letter_drafts ld ON ld.document_id = d.id AND ld.deleted_at IS NULL WHERE {$visible_document_filter}) as file_count
                    FROM folders f 
                    WHERE f.department = ? AND f.deleted_at IS NULL
                    ORDER BY f.folder_name";
    $stmt_folders = mysqli_prepare($conn, $sql_folders);
    mysqli_stmt_bind_param($stmt_folders, "isisiss", $current_user_id, $role, $current_user_id, $role, $current_user_id, $role, $dept_name);
    mysqli_stmt_execute($stmt_folders);
    $folders_result = mysqli_stmt_get_result($stmt_folders);
    $folders = mysqli_fetch_all($folders_result, MYSQLI_ASSOC);
    $office_folders = [];
    $personal_folders = [];

    foreach ($folders as &$folder) {
        $folder['folder_type'] = normalizeFolderType($folder['folder_type'] ?? '');
        if ($folder['folder_type'] === 'sendirian') {
            $personal_folders[] = $folder;
        } else {
            $office_folders[] = $folder;
        }
    }
    unset($folder);

    $total_documents = array_sum(array_map('intval', array_column($folders, 'file_count')));
    
    $dept_data[$dept_name] = [
        'total_folders' => $total_folders,
        'total_documents' => $total_documents,
        'folders' => $folders,
        'office_folders' => $office_folders,
        'personal_folders' => $personal_folders
    ];
}
?>
<!DOCTYPE html>
<html lang="ms">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard | MAINPP WORKSPACE</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <?php renderAppShellAssets(); ?>
    <style>
        :root {
            --primary: #0077b6; --primary-dark: #005f99; --secondary: #00b4d8;
            --deep-blue: #023e5f;
            --superadmin: #6c5ce7; --superadmin-dark: #5b4cdb;
            --bg-light: rgba(245, 250, 253, 0.72); --bg-card: rgba(255, 255, 255, 0.68); --text-main: #163447;
            --text-muted: #2d5367; --border: rgba(255, 255, 255, 0.48); --sidebar-width: 280px;
            --success: #1a9955; --danger: #dc3545; --warning: #ffc107;
            --glass: rgba(255, 255, 255, 0.58);
            --glass-strong: rgba(255, 255, 255, 0.76);
            --shadow-soft: 0 24px 70px rgba(2, 62, 95, 0.16);
        }
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Segoe UI', 'Inter', Tahoma, Geneva, Verdana, sans-serif; }
        body {
            min-height: 100vh;
            display: flex;
            color: var(--text-main);
            background:
                linear-gradient(135deg, rgba(245, 250, 253, 0.90), rgba(222, 246, 252, 0.76)),
                url('assets/auth-bg.png') center/cover no-repeat fixed;
            overflow-x: hidden;
        }

        body::before,
        body::after {
            content: "";
            position: fixed;
            pointer-events: none;
            z-index: 0;
        }

        body::before {
            width: 42vw;
            height: 42vw;
            right: -16vw;
            top: -18vw;
            border-radius: 50%;
            background: radial-gradient(circle, rgba(0, 180, 216, 0.24), transparent 62%);
            filter: blur(4px);
        }

        body::after {
            width: 48vw;
            height: 48vw;
            left: 120px;
            bottom: -30vw;
            border-radius: 46px;
            background:
                linear-gradient(155deg, rgba(255, 255, 255, 0.20), rgba(255, 255, 255, 0.03)),
                repeating-linear-gradient(0deg, transparent 0 34px, rgba(0, 119, 182, 0.08) 35px 36px);
            border: 1px solid rgba(255, 255, 255, 0.32);
            transform: rotate(-9deg);
        }
        
        /* Sidebar */

        .sidebar {
            width: var(--sidebar-width);
            background:
                linear-gradient(180deg, rgba(2, 62, 95, 0.94), rgba(0, 119, 182, 0.84)),
                radial-gradient(circle at 22% 8%, rgba(0, 180, 216, 0.28), transparent 32%);
            border-right: 1px solid rgba(255, 255, 255, 0.22);
            position: fixed;
            height: 100vh;
            padding: 20px 0;
            overflow-y: auto;
            overflow-x: hidden;
            z-index: 1000;
            box-shadow: 18px 0 44px rgba(2, 38, 60, 0.20);
            transition: width 0.3s ease;
            display:flex;
            flex-direction:column;
            backdrop-filter: blur(18px) saturate(1.25);
            -webkit-backdrop-filter: blur(18px) saturate(1.25);
        }
        .sidebar.collapsed { width: 70px; }
        .sidebar-header {
            text-align: center;
            padding: 0 20px 20px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.16);
            margin-bottom: 20px;
            white-space: nowrap;
            overflow: hidden;
            background: transparent !important;
        }
        .sidebar.collapsed .sidebar-header h3, .sidebar.collapsed .sidebar-header p, .sidebar.collapsed .menu-text { display: none; }
        .sidebar-header img { width: 54px; margin-bottom: 10px; transition: margin 0.3s ease; filter: drop-shadow(0 10px 18px rgba(0,0,0,0.25)); }
        .sidebar.collapsed .sidebar-header img { margin: 0 auto 10px; }
        .sidebar-header h3 { font-size: 1rem; font-weight: 800; color: #fff; margin-bottom: 4px; letter-spacing: 0.01em; }
        .sidebar-header p { font-size: 0.75rem; color: rgba(255,255,255,0.72); }
        .role-badge { display: inline-block; padding: 3px 10px; border-radius: 12px; font-size: 0.7rem; font-weight: 600; margin-left: 8px; }
        .role-badge.user { background: #e6f4ff; color: var(--primary); }
        .role-badge.admin { background: #d4edda; color: var(--success); }
        .role-badge.superadmin { background: linear-gradient(90deg, var(--superadmin), var(--superadmin-dark)); color: #fff; }
        .sidebar-menu { list-style: none; padding: 0 10px; display:flex; flex-direction:column; flex:1; }
        .sidebar-section { padding: 10px 18px 6px; color: rgba(255,255,255,0.58); font-size: 0.72rem; font-weight: 800; text-transform: uppercase; letter-spacing: 0.06em; }
        .sidebar-spacer { margin-top: auto; }
        .sidebar-menu li a { display: flex; align-items: center; gap: 12px; padding: 12px 18px; color: rgba(255,255,255,0.88); text-decoration: none; border-radius: 10px; margin-bottom: 5px; transition: all 0.2s ease; font-size: 0.9rem; white-space: nowrap; }
        .sidebar-menu li a:hover, .sidebar-menu li a.active { background: rgba(255,255,255,0.18); color: #fff; box-shadow: inset 0 0 0 1px rgba(255,255,255,0.18); }
        .sidebar-menu li a i { width: 20px; text-align: center; font-size: 1.1rem; }
        .sidebar-menu .dropdown { position: relative; }
        .sidebar-menu .dropdown-toggle { display: flex; align-items: center; justify-content: space-between; width: 100%; padding: 12px 18px; color: rgba(255,255,255,0.88); background: none; border: none; border-radius: 10px; cursor: pointer; font-size: 0.9rem; text-align: left; transition: all 0.2s ease; }
        .sidebar-menu .dropdown-toggle:hover, .sidebar-menu .dropdown-toggle.active { background: rgba(255,255,255,0.18); color: #fff; box-shadow: inset 0 0 0 1px rgba(255,255,255,0.18); }
        .sidebar-menu .dropdown-toggle i.chevron { transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1); font-size: 0.8rem; }
        .sidebar-menu .dropdown.active .dropdown-toggle i.chevron { transform: rotate(180deg); }
        .sidebar-menu .dropdown-menu { display: flex; flex-direction: column; padding-left: 42px; margin-top: 4px; max-height: 0; opacity: 0; overflow: hidden; transition: max-height 0.3s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.25s ease; }
        .sidebar-menu .dropdown.active .dropdown-menu { max-height: 260px; opacity: 1; }
        .sidebar-menu .dropdown-menu a { padding: 8px 18px; color: rgba(255,255,255,0.78); text-decoration: none; border-radius: 8px; font-size: 0.85rem; display: flex; align-items: center; gap: 8px; opacity: 0; transform: translateY(-5px); transition: opacity 0.2s ease, transform 0.2s ease; }
        .sidebar-menu .dropdown.active .dropdown-menu a { opacity: 1; transform: translateY(0); }
        .sidebar-menu .dropdown-menu a:hover, .sidebar-menu .dropdown-menu a.active { background: rgba(255,255,255,0.16); color: #fff; }
        .sidebar.collapsed + .main { margin-left: 70px; }
        .sidebar-toggle { position: absolute; right: 10px; top: 20px; width: 28px; height: 28px; background: rgba(255,255,255,0.20); color: #fff; border: 1px solid rgba(255,255,255,0.28); border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 0.7rem; box-shadow: 0 10px 22px rgba(0,0,0,0.14); transition: transform 0.3s ease; z-index: 1001; }
        .sidebar.collapsed .sidebar-toggle { transform: rotate(180deg); }
        .main { position: relative; z-index: 1; margin-left: var(--sidebar-width); flex: 1; padding: 28px 32px; transition: margin-left 0.3s ease; }
        .top-bar {
            background: var(--glass);
            padding: 18px 24px;
            border-radius: 18px;
            box-shadow: var(--shadow-soft);
            margin-bottom: 18px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border: 1px solid var(--border);
            backdrop-filter: blur(22px) saturate(1.25);
            -webkit-backdrop-filter: blur(22px) saturate(1.25);
        }
        .top-bar h2 { color: var(--primary-dark); font-size: 1.35rem; font-weight: 850; display: flex; align-items: center; gap: 10px; }
        .top-bar h2 i { color: var(--secondary); }
        .user-info { display: flex; align-items: center; gap: 15px; font-size: 0.9rem; color: var(--text-muted); }
        .user-info span { color: var(--primary); font-weight: 600; }
        .user-info a { color: var(--danger); text-decoration: none; font-weight: 500; display: flex; align-items: center; gap: 5px; }
        .user-info a:hover { text-decoration: underline; }
        
        /* Tabs Navigation */
        .tabs-container {
            background: var(--glass);
            border-radius: 22px;
            padding: 22px;
            margin-bottom: 25px;
            box-shadow: var(--shadow-soft);
            border: 1px solid var(--border);
            backdrop-filter: blur(24px) saturate(1.25);
            -webkit-backdrop-filter: blur(24px) saturate(1.25);
            position: relative;
        }
        .tabs-nav-scroll {
            overflow-x: auto;
            overflow-y: hidden;
            scroll-behavior: smooth;
            scrollbar-width: none;
            -ms-overflow-style: none;
            padding-bottom: 4px;
        }
        .tabs-nav-scroll::-webkit-scrollbar {
            display: none;
        }
        .tabs-nav { display: flex; gap: 10px; margin-bottom: 24px; border-bottom: 1px solid rgba(0,119,182,0.14); padding-bottom: 12px; flex-wrap: nowrap; }
        .tab-btn { padding: 10px 18px; background: rgba(255,255,255,0.64); border: 1px solid rgba(0,119,182,0.12); border-radius: 999px; cursor: pointer; font-weight: 750; color: var(--primary-dark); transition: all 0.25s ease; box-shadow: 0 8px 20px rgba(2,62,95,0.06); white-space: nowrap; flex: 0 0 auto; }
        .tab-btn:hover { transform: translateY(-1px); background: rgba(0, 119, 182, 0.12); color: var(--primary-dark); }
        .tab-btn.active { background: linear-gradient(90deg, var(--primary), var(--secondary)); color: #fff; box-shadow: 0 14px 28px rgba(0,119,182,0.24); }
        .tab-scroll-btn {
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            width: 32px;
            height: 32px;
            border-radius: 50%;
            border: 1px solid rgba(0,119,182,0.18);
            background: rgba(255,255,255,0.85);
            color: var(--primary-dark);
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 8px 20px rgba(2,62,95,0.10);
            z-index: 2;
            backdrop-filter: blur(12px);
        }
        .tab-scroll-btn:hover {
            background: #fff;
            box-shadow: 0 12px 24px rgba(0,119,182,0.18);
        }
        .tab-scroll-left { left: 10px; }
        .tab-scroll-right { right: 10px; }
        
        .tab-content { display: none; }
        .tab-content.active { display: block; animation: fadeIn 0.3s ease; }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        /* Stats Cards */
        .stats-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(210px, 1fr)); gap: 16px; margin-bottom: 26px; }
        .stat-box { position: relative; overflow: hidden; background: linear-gradient(135deg, rgba(0,119,182,0.94), rgba(0,180,216,0.86)); color: #fff; padding: 22px; border-radius: 18px; text-align: left; box-shadow: 0 18px 34px rgba(0,119,182,0.24); border: 1px solid rgba(255,255,255,0.24); }
        .stat-box::after { content: ""; position: absolute; width: 140px; height: 140px; right: -46px; bottom: -70px; border-radius: 50%; background: rgba(255,255,255,0.16); }
        .stat-box i { position: relative; z-index: 1; width: 46px; height: 46px; border-radius: 14px; background: rgba(255,255,255,0.18); display: inline-flex; align-items: center; justify-content: center; }
        .stat-box h3 { position: relative; z-index: 1; font-size: 2.25rem; margin: 12px 0 4px; line-height: 1; }
        .stat-box p { position: relative; z-index: 1; font-size: 0.9rem; opacity: 0.92; font-weight: 700; }
        
        /* Fail Office Cards */
        .folders-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 18px; margin-bottom: 30px; }
        .folder-card { background: rgba(255,255,255,0.70); border: 1px solid rgba(255,255,255,0.58); border-radius: 18px; padding: 18px; box-shadow: 0 14px 30px rgba(2,62,95,0.10); transition: transform 0.2s ease, box-shadow 0.2s ease; backdrop-filter: blur(18px) saturate(1.18); -webkit-backdrop-filter: blur(18px) saturate(1.18); }
        .folder-card:hover { transform: translateY(-2px); box-shadow: 0 20px 40px rgba(2,62,95,0.15); }
        .folder-header { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; margin-bottom: 15px; padding-bottom: 12px; border-bottom: 1px solid rgba(0,119,182,0.12); }
        .folder-title { font-size: 1.05rem; font-weight: 800; color: var(--primary-dark); line-height: 1.3; }
        .folder-code { background: rgba(0,119,182,0.10); padding: 5px 10px; border-radius: 999px; font-size: 0.82rem; color: var(--primary-dark); font-weight: 750; }
        .folder-stats { display: flex; gap: 15px; margin-bottom: 15px; }
        .folder-stat { flex: 1; text-align: center; padding: 12px; background: rgba(0,180,216,0.09); border-radius: 12px; border: 1px solid rgba(0,119,182,0.10); }
        .folder-stat strong { display: block; font-size: 1.4rem; color: var(--primary-dark); }
        .folder-stat span { font-size: 0.85rem; color: var(--text-muted); font-weight: 650; }
        .current-ref { background: rgba(255, 243, 205, 0.78); color: #6b4a00; padding: 10px 12px; border-radius: 12px; font-size: 0.9rem; text-align: center; margin-top: 10px; border: 1px solid rgba(133,100,4,0.12); }
        .current-ref strong { display: block; font-weight: 600; }

        /* Fail Personal Table */
        .folder-section-title { color: var(--primary-dark); font-size: 1rem; font-weight: 850; margin: 5px 0 15px; display: flex; align-items: center; gap: 8px; }
        .folder-section-title i { color: var(--secondary); }
        .dashboard-section-heading { color: var(--primary-dark); margin-bottom: 20px; font-size: 1.18rem; font-weight: 850; display: flex; align-items: center; gap: 9px; }
        .dashboard-section-heading i { color: var(--secondary); }
        .folder-count { font-size: 0.85rem; color: var(--text-muted); font-weight: 650; }
        .folder-type-badge { background: #fff4e5; color: #9a5b00; padding: 4px 10px; border-radius: 999px; font-size: 0.75rem; font-weight: 600; }
        .folder-table-wrap { background: rgba(255,255,255,0.68); border: 1px solid rgba(255,255,255,0.58); border-radius: 18px; overflow-x: auto; margin-bottom: 28px; box-shadow: 0 14px 30px rgba(2,62,95,0.09); }
        .folder-table { width: 100%; border-collapse: collapse; min-width: 760px; }
        .folder-table th { background: rgba(0,119,182,0.09); color: var(--primary-dark); font-weight: 850; text-align: center; padding: 14px 16px; border-bottom: 1px solid rgba(0,119,182,0.13); }
        .folder-table td { padding: 14px 16px; border-bottom: 1px solid rgba(0,119,182,0.10); vertical-align: middle; text-align: center; background: rgba(255,255,255,0.66); }
        .folder-table td.empty-state { text-align: center; }
        .folder-table tr:hover td { background: rgba(231, 248, 252, 0.72); }
        .folder-name { font-weight: 750; color: var(--primary-dark); }
        .folder-code-pill { background: #e6f4ff; color: var(--primary-dark); padding: 4px 10px; border-radius: 999px; font-size: 0.8rem; font-weight: 700; display: inline-block; }
        .ref-pill { background: #fff3cd; color: #856404; padding: 4px 10px; border-radius: 999px; font-size: 0.8rem; font-weight: 600; display: inline-block; }
        .ref-empty { color: var(--text-muted); font-size: 0.85rem; }
        .current-ref.empty { background: rgba(255, 255, 255, 0.58); color: var(--text-muted); border-color: rgba(0,119,182,0.10); }
        .folder-open-link { display: inline-flex; align-items: center; justify-content: center; gap: 6px; width: 38px; height: 34px; border-radius: 9px; background: linear-gradient(90deg, var(--primary), var(--secondary)); color: #fff; text-decoration: none; font-size: 0.85rem; font-weight: 700; box-shadow: 0 10px 20px rgba(0,119,182,0.22); }
        .folder-open-link:hover { filter: brightness(1.04); transform: translateY(-1px); }
        
        .empty-state { text-align: center; padding: 40px; color: var(--text-muted); }
        .empty-state i { font-size: 3rem; margin-bottom: 15px; opacity: 0.5; }
        
        .page-footer { text-align: center; padding: 20px; color: var(--text-muted); font-size: 0.8rem; margin-top: 30px; }

        @media (max-width: 992px) {
            .sidebar { width: 70px; }
            .sidebar .sidebar-header h3, .sidebar .sidebar-header p, .sidebar .menu-text, .sidebar .role-badge, .sidebar .dropdown-menu, .sidebar .sidebar-section { display: none; }
            .main { margin-left: 70px; }
            .sidebar-toggle { display: none; }
        }
        .sidebar {
            overflow: hidden;
        }
        .sidebar-header {
            flex: 0 0 auto;
        }
        .sidebar-menu {
            flex: 1 1 auto;
            min-height: 0;
            overflow-y: auto;
            overflow-x: hidden;
            padding-bottom: 0;
            overscroll-behavior: contain;
            scrollbar-width: thin;
            scrollbar-color: #8f8f8f transparent;
        }
        .sidebar-menu::-webkit-scrollbar {
            width: 10px;
        }
        .sidebar-menu::-webkit-scrollbar-track {
            background: transparent;
        }
        .sidebar-menu::-webkit-scrollbar-thumb {
            background: #8f8f8f;
            border-radius: 999px;
            border: 2px solid transparent;
            background-clip: content-box;
        }
        .sidebar-menu::-webkit-scrollbar-button {
            display: none;
            width: 0;
            height: 0;
        }
    
        /* Button hover animation */
        .main .btn,
        .main .tab-btn,
        .main .action-btn,
        .main .btn-action,
        .main .filter-btn,
        .main .button,
        .main .generate-closing-btn,
        .main .attachment-remove-btn,
        .main .page-add-btn,
        .main .page-delete-btn,
        .main .delete-current-page-btn,
        .main .form-actions a,
        .main .form-actions button,
        .main .filter-actions a,
        .main .filter-actions button,
        .main .document-command a,
        .main .document-command button,
        .main table a[class*="btn"],
        .main table button[class*="btn"],
        .main input[type="submit"],
        .main input[type="button"] {
            transition: transform 0.2s ease, filter 0.2s ease, box-shadow 0.2s ease, background-color 0.2s ease, border-color 0.2s ease !important;
            will-change: transform;
        }

        .main .btn:hover:not(:disabled),
        .main .tab-btn:hover:not(:disabled),
        .main .action-btn:hover:not(:disabled),
        .main .btn-action:hover:not(:disabled),
        .main .filter-btn:hover:not(:disabled),
        .main .button:hover:not(:disabled),
        .main .generate-closing-btn:hover:not(:disabled),
        .main .attachment-remove-btn:hover:not(:disabled),
        .main .page-add-btn:hover:not(:disabled),
        .main .page-delete-btn:hover:not(:disabled),
        .main .delete-current-page-btn:hover:not(:disabled),
        .main .form-actions a:hover,
        .main .form-actions button:hover:not(:disabled),
        .main .filter-actions a:hover,
        .main .filter-actions button:hover:not(:disabled),
        .main .document-command a:hover,
        .main .document-command button:hover:not(:disabled),
        .main table a[class*="btn"]:hover,
        .main table button[class*="btn"]:hover:not(:disabled),
        .main input[type="submit"]:hover:not(:disabled),
        .main input[type="button"]:hover:not(:disabled) {
            transform: translateY(-1px);
            filter: brightness(1.04);
            box-shadow: 0 14px 28px rgba(0, 119, 182, 0.18);
        }

        .main .btn:active:not(:disabled),
        .main .tab-btn:active:not(:disabled),
        .main .action-btn:active:not(:disabled),
        .main .btn-action:active:not(:disabled),
        .main .filter-btn:active:not(:disabled),
        .main .button:active:not(:disabled),
        .main .generate-closing-btn:active:not(:disabled),
        .main .attachment-remove-btn:active:not(:disabled),
        .main .page-add-btn:active:not(:disabled),
        .main .page-delete-btn:active:not(:disabled),
        .main .delete-current-page-btn:active:not(:disabled),
        .main .form-actions a:active,
        .main .form-actions button:active:not(:disabled),
        .main .filter-actions a:active,
        .main .filter-actions button:active:not(:disabled),
        .main .document-command a:active,
        .main .document-command button:active:not(:disabled),
        .main table a[class*="btn"]:active,
        .main table button[class*="btn"]:active:not(:disabled),
        .main input[type="submit"]:active:not(:disabled),
        .main input[type="button"]:active:not(:disabled) {
            transform: translateY(0);
            filter: brightness(0.98);
        }</style>
</head>
<body class="role-<?= htmlspecialchars($role) ?>">

    <aside class="sidebar" id="sidebar">
        <button class="sidebar-toggle" id="sidebarToggle" title="Tutup/Buka Menu">
            <i class="fas fa-chevron-left"></i>
        </button>
        <div class="sidebar-header">
            <img src="mainpp.png" alt="Logo MAINPP">
            <h3>MAINPP WORKSPACE</h3>
        </div>
        <ul class="sidebar-menu">
            <?php renderUnifiedSidebarMenu($conn, $role, 'dashboard.php'); ?>
        </ul>
    </aside>

    <main class="main">
        <div class="top-bar">
            <h2><i class="fas fa-layer-group"></i> Dashboard</h2>
            <?php renderTopBarUserMenu($conn, $role, 'dashboard.php'); ?>
        </div>

        <?php
        renderBreadcrumb([
            ['label' => 'Dashboard', 'url' => 'dashboard.php', 'current' => true]
        ]);
        ?>

        <!-- TABS NAVIGATION -->
        <div class="tabs-container">
            <button type="button" class="tab-scroll-btn tab-scroll-left" id="tabScrollLeft" aria-label="Scroll ke kiri">
                <i class="fas fa-chevron-left"></i>
            </button>
            <div class="tabs-nav-scroll" id="tabsNavScroll">
                <div class="tabs-nav">
                    <?php if (empty($available_depts)): ?>
                        <span style="color: var(--text-muted); padding: 10px;">Tiada bahagian dijumpai.</span>
                    <?php else: ?>
                        <?php foreach ($available_depts as $index => $dept_row): ?>
                            <button class="tab-btn <?= $index === 0 ? 'active' : '' ?>" onclick="switchTab('<?= htmlspecialchars($dept_row['department']) ?>', this)">
                                <?= htmlspecialchars($dept_row['department']) ?>
                            </button>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
            <button type="button" class="tab-scroll-btn tab-scroll-right" id="tabScrollRight" aria-label="Scroll ke kanan">
                <i class="fas fa-chevron-right"></i>
            </button>
        </div>

            <!-- TAB CONTENT FOR EACH DEPARTMENT -->
            <?php if (empty($available_depts)): ?>
                <div class="tab-content active">
                    <div class="empty-state">
                        <i class="fas fa-folder-open"></i>
                        <p>Tiada fail dalam sistem.</p>
                    </div>
                </div>
            <?php else: ?>
                <?php foreach ($available_depts as $index => $dept_row): 
                    $dept_name = $dept_row['department'];
                    $data = $dept_data[$dept_name];
                ?>
                <div id="tab-<?= htmlspecialchars(str_replace(' ', '-', strtolower($dept_name))) ?>" class="tab-content <?= $index === 0 ? 'active' : '' ?>">
                    
                    <!-- STATS -->
                    <div class="stats-row">
                        <div class="stat-box">
                            <i class="fas fa-folder-open" style="font-size: 2rem; opacity: 0.8;"></i>
                            <h3><?= $data['total_folders'] ?></h3>
                            <p>Jumlah Fail</p>
                        </div>
                        <div class="stat-box">
                            <i class="fas fa-file-alt" style="font-size: 2rem; opacity: 0.8;"></i>
                            <h3><?= number_format($data['total_documents'] ?? 0) ?></h3>
                            <p>Jumlah Surat</p>
                        </div>
                    </div>

                    <!-- FOLDERS GRID -->
                    <h3 class="dashboard-section-heading">
                        <i></i> Senarai Fail
                    </h3>

                    <div class="folder-section-title">
                        <span>Fail Office</span>
                    </div>
                    <div class="folders-grid">
                        <?php if (empty($data['office_folders'])): ?>
                            <div class="empty-state" style="grid-column: 1/-1;">
                                <i class="fas fa-folder-open"></i>
                                <p>Tiada fail office untuk bahagian ini.</p>
                            </div>
                        <?php else: ?>
                            <?php foreach (($data['office_folders'] ?? []) as $folder): ?>
                            <div class="folder-card">
                                <div class="folder-header">
                                    <span class="folder-title"><?= htmlspecialchars($folder['folder_name']) ?></span>
                                    <span class="folder-code"><?= htmlspecialchars($folder['folder_code']) ?></span>
                                </div>
                                <div class="folder-stats">
                                    <div class="folder-stat">
                                        <strong><?= $folder['file_count'] ?></strong>
                                        <span>Jumlah Surat</span>
                                    </div>
                                </div>
                                <?php if (!empty($folder['latest_file_numbering'])): ?>
                                    <div class="current-ref">
                                        <strong>Current File No:</strong>
                                        <?= htmlspecialchars($folder['folder_code'] . '(' . $folder['latest_file_numbering'] . ')') ?>
                                    </div>
                                <?php else: ?>
                                    <div class="current-ref empty">
                                        <strong>Current File No:</strong>
                                        Tiada surat
                                    </div>
                                <?php endif; ?>
                            </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>

                    <div class="folder-section-title">
                        <span>Fail Personal</span>
                    </div>
                    <?php
                        $personal_pagination = paginateArrayItems($data['personal_folders'] ?? [], 'personal_page_' . $index, 15);
                        $display_personal_folders = $personal_pagination['items'];
                    ?>
                    <div class="folder-table-wrap">
                        <table class="folder-table">
                            <thead>
                                <tr>
                                    <th>Bil.</th>
                                    <th>Nama Fail</th>
                                    <th>Jenis</th>
                                    <th>Jumlah Surat</th>
                                    <th>Tindakan</th>
                                </tr>
                            </thead>
                            <tbody>
                        <?php if (empty($display_personal_folders)): ?>
                                <tr>
                                    <td colspan="5" class="empty-state">
                                        <i class="fas fa-folder-open"></i>
                                        <p>Tiada fail personal untuk bahagian ini.</p>
                                    </td>
                                </tr>
                        <?php else: ?>
                            <?php foreach ($display_personal_folders as $folder_index => $folder): ?>
                            <tr>
                                <td><?= (int) $personal_pagination['offset'] + $folder_index + 1 ?></td>
                                <td><span class="folder-name"><?= htmlspecialchars($folder['folder_name']) ?></span></td>
                                <td><span class="folder-type-badge"><?= htmlspecialchars(getFolderTypeLabel($folder['folder_type'])) ?></span></td>
                                <td><?= (int) $folder['file_count'] ?></td>
                                <td><a href="view_folder.php?id=<?= (int) $folder['id'] ?>" class="folder-open-link"><i class="fas fa-eye"></i></a></td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                            </tbody>
                        </table>
                        <?php renderPaginationControls($personal_pagination, 'fail'); ?>
                    </div>

                </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

        <div class="page-footer">
            Hakcipta Terpelihara &copy; <?= date('Y') ?> Majlis Agama Islam Negeri Pulau Pinang.
        </div>
    </main>

    <script>
                const sidebar = document.getElementById('sidebar');
        const toggleBtn = document.getElementById('sidebarToggle');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', () => sidebar.classList.toggle('collapsed'));
        }
        if (window.innerWidth < 992) sidebar.classList.add('collapsed');

        document.querySelectorAll('.sidebar-menu .dropdown-toggle, .dropdown-toggle').forEach(btn => {
            btn.addEventListener('click', function(e) {
                e.preventDefault();
                const dropdown = this.parentElement;
                const isActive = dropdown.classList.contains('active');
                document.querySelectorAll('.sidebar-menu .dropdown, .dropdown').forEach(item => {
                    if (item !== dropdown) item.classList.remove('active');
                });
                dropdown.classList.toggle('active', !isActive);
            });
        });
        // Tab Switching
        function switchTab(deptName, btn) {
            document.querySelectorAll('.tab-content').forEach(tab => {
                tab.classList.remove('active');
            });
            document.querySelectorAll('.tab-btn').forEach(button => {
                button.classList.remove('active');
            });
            const tabId = 'tab-' + deptName.toLowerCase().replace(/ /g, '-');
            document.getElementById(tabId).classList.add('active');
            btn.classList.add('active');
        }

        // Tab Scroll
        (function () {
            const scrollContainer = document.getElementById('tabsNavScroll');
            const leftBtn = document.getElementById('tabScrollLeft');
            const rightBtn = document.getElementById('tabScrollRight');
            if (!scrollContainer || !leftBtn || !rightBtn) {
                return;
            }

            const scrollAmount = 220;

            function updateButtons() {
                const maxScrollLeft = scrollContainer.scrollWidth - scrollContainer.clientWidth;
                leftBtn.style.display = scrollContainer.scrollLeft <= 0 ? 'none' : 'inline-flex';
                rightBtn.style.display = scrollContainer.scrollLeft >= maxScrollLeft - 1 ? 'none' : 'inline-flex';
            }

            leftBtn.addEventListener('click', function () {
                scrollContainer.scrollBy({ left: -scrollAmount, behavior: 'smooth' });
            });

            rightBtn.addEventListener('click', function () {
                scrollContainer.scrollBy({ left: scrollAmount, behavior: 'smooth' });
            });

            scrollContainer.addEventListener('scroll', updateButtons);
            window.addEventListener('resize', updateButtons);
            updateButtons();
        })();
        
        // Confirm Logout
        function confirmLogout() { return confirm("Adakah anda pasti ingin log keluar?"); }
    </script>
    <?php renderSessionTimeoutScript(); ?>
</body>
</html>
