<?php
require_once 'auth.php';
include 'db.php';
requireLogin($conn, ['superadmin']);

$role = $_SESSION['role'] ?? 'superadmin';

// FILTER PARAMETERS
$filter_user = $_GET['filter_user'] ?? '';
$filter_role = $_GET['filter_role'] ?? '';
$filter_department = normalizeDepartmentValue($_GET['filter_department'] ?? '');
$filter_activity = $_GET['filter_activity'] ?? '';
$filter_date_from = $_GET['filter_date_from'] ?? '';
$filter_date_to = $_GET['filter_date_to'] ?? '';
$logs_per_page = 15;
$current_page = max(1, (int) ($_GET['page'] ?? 1));
$activity_sort_columns = [
    'time' => 'Masa',
    'user' => 'User',
    'role' => 'Role',
    'department' => 'Bahagian',
    'activity' => 'Aktiviti',
    'description' => 'Keterangan',
];
$activity_sort_column = trim((string) ($_GET['sort'] ?? ''));
$activity_sort_dir = strtolower(trim((string) ($_GET['dir'] ?? '')));
if (!isset($activity_sort_columns[$activity_sort_column])) {
    $activity_sort_column = '';
}
if (!in_array($activity_sort_dir, ['asc', 'desc'], true)) {
    $activity_sort_dir = 'asc';
}

// ACTIVITY TYPES for dropdown
$activity_types = [
    'login' => 'Login',
    'logout' => 'Logout',
    'auto_logout' => 'Auto Logout',
    'login_failed' => 'Login Failed',
    'login_pending' => 'Login Pending',
    'login_rejected' => 'Login Rejected',
    'create_folder' => 'Cipta Fail',
    'update_folder' => 'Kemaskini Fail',
    'delete_folder' => 'Padam Fail',
    'restore_folder' => 'Pulihkan Fail',
    'close_folder' => 'Tutup Fail',
    'surat_create' => 'Cipta Surat',
    'surat_create_failed' => 'Cipta Surat Gagal',
    'surat_update' => 'Kemaskini Surat',
    'surat_delete' => 'Padam Surat',
    'surat_restore' => 'Pulihkan Surat',
    'surat_attachment_delete' => 'Padam Lampiran Surat',
    'download_document_attachment' => 'Download Lampiran Surat',
    'support_draft_letter' => 'Sokongan Surat',
    'decide_draft_letter' => 'Keputusan Surat',
    'export_draft_letter_pdf' => 'Export PDF Surat',
    'create_user' => 'Daftar User',
    'create_user_pending' => 'Permohonan Daftar User',
    'update_user' => 'Kemaskini User',
    'delete_user' => 'Padam User',
    'user_status_update' => 'Kemaskini Status User',
    'update_user_role' => 'Kemaskini Role User',
    'update_profile' => 'Kemaskini Profil',
    'change_password' => 'Tukar Kata Laluan',
    'create_signature' => 'Daftar Tandatangan',
    'update_signature' => 'Ubah Tandatangan',
    'update_department_permissions' => 'Kemaskini Capaian Bahagian',
    'update_user_permissions' => 'Kemaskini Capaian User',
    'reset_user_permissions' => 'Reset Capaian User',
];

$activity_filter_groups = [
    'surat_create' => ['create_document', 'create_draft_letter'],
    'surat_create_failed' => ['create_document_failed'],
    'surat_update' => ['update_document', 'update_draft_letter'],
    'surat_delete' => ['delete_document', 'delete_draft_letter'],
    'surat_restore' => ['restore_document', 'restore_draft_letter'],
    'surat_attachment_delete' => ['delete_attachment', 'delete_document_attachment', 'delete_draft_attachment'],
    'user_status_update' => ['update_user_status', 'update_user_status_bulk'],
];

// Build WHERE clause
$where = ["1=1"];
$params = [];
$types = "";

if (!empty($filter_user)) {
    $where[] = "(l.user_name LIKE ? OR l.user_email LIKE ?)";
    $params[] = "%{$filter_user}%";
    $params[] = "%{$filter_user}%";
    $types .= "ss";
}

if (!empty($filter_role) && $filter_role !== 'all') {
    $where[] = "l.user_role = ?";
    $params[] = $filter_role;
    $types .= "s";
}

if ($filter_department !== '' && $filter_department !== 'all') {
    $where[] = "COALESCE(u.department, '') = ?";
    $params[] = $filter_department;
    $types .= "s";
}

if (!empty($filter_activity) && $filter_activity !== 'all') {
    if (isset($activity_filter_groups[$filter_activity])) {
        $group_values = $activity_filter_groups[$filter_activity];
        $where[] = "l.activity_type IN (" . implode(',', array_fill(0, count($group_values), '?')) . ")";
        foreach ($group_values as $group_value) {
            $params[] = $group_value;
            $types .= "s";
        }
    } else {
        $where[] = "l.activity_type = ?";
        $params[] = $filter_activity;
        $types .= "s";
    }
}

if (!empty($filter_date_from)) {
    $where[] = "DATE(l.created_at) >= ?";
    $params[] = $filter_date_from;
    $types .= "s";
}

if (!empty($filter_date_to)) {
    $where[] = "DATE(l.created_at) <= ?";
    $params[] = $filter_date_to;
    $types .= "s";
}

$where_sql = implode(' AND ', $where);
$count_sql = "SELECT COUNT(*) AS total
        FROM activity_logs l
        LEFT JOIN users u ON l.user_id = u.id
        WHERE " . $where_sql;

if (!empty($params)) {
    $count_stmt = mysqli_prepare($conn, $count_sql);
    mysqli_stmt_bind_param($count_stmt, $types, ...$params);
    mysqli_stmt_execute($count_stmt);
    $count_result = mysqli_stmt_get_result($count_stmt);
} else {
    $count_result = mysqli_query($conn, $count_sql);
}

$total_logs = (int) (mysqli_fetch_assoc($count_result)['total'] ?? 0);
$total_pages = max(1, (int) ceil($total_logs / $logs_per_page));
if ($current_page > $total_pages) {
    $current_page = $total_pages;
}
$offset = ($current_page - 1) * $logs_per_page;

// QUERY: Activity Logs dengan User Info
$activity_order_sql = $activity_sort_column !== ''
    ? getActivitySortExpression($activity_sort_column, $conn) . ' ' . strtoupper($activity_sort_dir) . ', l.id DESC'
    : 'l.created_at DESC';

$sql = "SELECT l.*, u.department, u.last_login 
        FROM activity_logs l 
        LEFT JOIN users u ON l.user_id = u.id 
        WHERE " . $where_sql . " 
        ORDER BY {$activity_order_sql} 
        LIMIT " . $logs_per_page . " OFFSET " . $offset;

if (!empty($params)) {
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, $types, ...$params);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
} else {
    $result = mysqli_query($conn, $sql);
}

$logs = mysqli_fetch_all($result, MYSQLI_ASSOC);

// QUERY: Senarai User untuk Filter
$users_list = mysqli_query($conn, "SELECT id, fullname, email, role, last_login FROM users ORDER BY fullname");
$users = mysqli_fetch_all($users_list, MYSQLI_ASSOC);
$departments = array_values(array_filter(array_map('normalizeDepartmentValue', getDepartmentList())));

function buildActivityStatsInList($conn, $activity_types) {
    $quoted = [];
    foreach ($activity_types as $activity_type) {
        $quoted[] = "'" . mysqli_real_escape_string($conn, $activity_type) . "'";
    }
    return implode(',', $quoted);
}

$login_stat_types = ['login'];
$logout_stat_types = ['logout', 'auto_logout'];
$folder_stat_types = [
    'create_folder',
    'create_folder_failed',
    'update_folder',
    'update_folder_failed',
    'delete_folder',
    'delete_folder_failed',
    'delete_folder_unauthorized',
    'delete_folder_blocked',
    'restore_folder',
    'close_folder',
    'close_folder_failed',
    'close_folder_unauthorized',
    'view_folder_failed',
];
$document_stat_types = [
    'create_document',
    'create_document_failed',
    'update_document',
    'delete_document',
    'delete_document_failed',
    'delete_document_unauthorized',
    'restore_document',
    'delete_attachment',
    'delete_document_attachment',
    'download_document_attachment',
    'create_draft_letter',
    'update_draft_letter',
    'delete_draft_letter',
    'restore_draft_letter',
    'delete_draft_attachment',
    'support_draft_letter',
    'decide_draft_letter',
    'export_draft_letter_pdf',
];

$login_stat_sql = buildActivityStatsInList($conn, $login_stat_types);
$logout_stat_sql = buildActivityStatsInList($conn, $logout_stat_types);
$folder_stat_sql = buildActivityStatsInList($conn, $folder_stat_types);
$document_stat_sql = buildActivityStatsInList($conn, $document_stat_types);

// STATS: Total activities by type
$stats_sql = "SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN activity_type IN ({$login_stat_sql}) THEN 1 ELSE 0 END) as logins,
    SUM(CASE WHEN activity_type IN ({$logout_stat_sql}) THEN 1 ELSE 0 END) as logouts,
    SUM(CASE WHEN activity_type IN ({$folder_stat_sql}) THEN 1 ELSE 0 END) as folder_actions,
    SUM(CASE WHEN activity_type IN ({$document_stat_sql}) THEN 1 ELSE 0 END) as document_actions
    FROM activity_logs 
    WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
$stats_result = mysqli_query($conn, $stats_sql);
$stats = mysqli_fetch_assoc($stats_result);

function isLoginLogoutActivity($activity_type) {
    $activity_type = strtolower((string) $activity_type);
    return strpos($activity_type, 'login') !== false || strpos($activity_type, 'logout') !== false;
}

function getActivityBadgeClass($activity_type) {
    $activity_type = strtolower((string) $activity_type);
    if (strpos($activity_type, 'login') !== false) {
        return 'badge-login';
    }
    if (strpos($activity_type, 'logout') !== false) {
        return 'badge-logout';
    }
    if (strpos($activity_type, 'update') !== false) {
        return 'badge-update';
    }
    if (strpos($activity_type, 'delete') !== false) {
        return 'badge-delete';
    }
    return 'badge-create';
}

function getActivityDisplayLabelMap() {
    return [
        'create_document' => 'Cipta Surat',
        'create_draft_letter' => 'Cipta Surat',
        'create_document_failed' => 'Cipta Surat Gagal',
        'update_document' => 'Kemaskini Surat',
        'update_draft_letter' => 'Kemaskini Surat',
        'delete_document' => 'Padam Surat',
        'delete_draft_letter' => 'Padam Surat',
        'restore_document' => 'Pulihkan Surat',
        'restore_draft_letter' => 'Pulihkan Surat',
        'delete_attachment' => 'Padam Lampiran Surat',
        'delete_document_attachment' => 'Padam Lampiran Surat',
        'delete_draft_attachment' => 'Padam Lampiran Surat',
        'download_document_attachment' => 'Download Lampiran Surat',
        'update_user_status' => 'Kemaskini Status User',
        'update_user_status_bulk' => 'Kemaskini Status User',
    ];
}

function getActivitySortExpression($column, $conn) {
    if ($column === 'time') {
        return 'l.created_at';
    }
    if ($column === 'user') {
        return 'l.user_name';
    }
    if ($column === 'role') {
        return 'l.user_role';
    }
    if ($column === 'department') {
        return "COALESCE(u.department, '')";
    }
    if ($column === 'description') {
        return 'l.activity_description';
    }
    if ($column === 'activity') {
        $case_sql = 'CASE';
        foreach (getActivityDisplayLabelMap() as $activity_type => $label) {
            $case_sql .= " WHEN l.activity_type = '" . mysqli_real_escape_string($conn, $activity_type) . "' THEN '" . mysqli_real_escape_string($conn, $label) . "'";
        }
        $case_sql .= " ELSE REPLACE(l.activity_type, '_', ' ') END";
        return $case_sql;
    }

    return 'l.created_at';
}

function getActivityDisplayLabel($activity_type) {
    $labels = getActivityDisplayLabelMap();

    if (isset($labels[$activity_type])) {
        return $labels[$activity_type];
    }

    return ucwords(str_replace('_', ' ', (string) $activity_type));
}

function buildActivityPageUrl($page) {
    $query = $_GET;
    $query['page'] = max(1, (int) $page);
    return 'user_activity.php?' . http_build_query($query);
}

function buildActivitySortUrl($column, $current_sort, $current_dir) {
    $query = $_GET;
    unset($query['page']);

    if ($current_sort !== $column) {
        $query['sort'] = $column;
        $query['dir'] = 'asc';
    } elseif ($current_dir === 'asc') {
        $query['sort'] = $column;
        $query['dir'] = 'desc';
    } else {
        unset($query['sort'], $query['dir']);
    }

    $query_string = http_build_query($query);
    return 'user_activity.php' . ($query_string !== '' ? '?' . $query_string : '');
}

function renderActivitySortableHeader($label, $column, $current_sort, $current_dir) {
    $is_active = $current_sort === $column;
    $indicator = $is_active ? ($current_dir === 'desc' ? '&darr;' : '&uarr;') : '&#8597;';
    $aria_sort = $is_active ? ($current_dir === 'desc' ? 'descending' : 'ascending') : 'none';

    echo '<th aria-sort="' . htmlspecialchars($aria_sort) . '">';
    echo '<a class="sort-link' . ($is_active ? ' active' : '') . '" href="' . htmlspecialchars(buildActivitySortUrl($column, $current_sort, $current_dir)) . '">';
    echo '<span>' . htmlspecialchars($label) . '</span><span class="sort-indicator">' . $indicator . '</span>';
    echo '</a>';
    echo '</th>';
}

function renderActivityLogsTable($logs, $empty_text, $offset = 0, $sort_column = '', $sort_dir = 'asc') {
    ?>
    <div class="table-responsive activity-table-scroll" tabindex="0" role="region" aria-label="Jadual aktiviti pengguna">
        <table>
            <thead>
                <tr>
                    <th>Bil</th>
                    <?php renderActivitySortableHeader('Masa', 'time', $sort_column, $sort_dir); ?>
                    <?php renderActivitySortableHeader('User', 'user', $sort_column, $sort_dir); ?>
                    <?php renderActivitySortableHeader('Role', 'role', $sort_column, $sort_dir); ?>
                    <?php renderActivitySortableHeader('Bahagian', 'department', $sort_column, $sort_dir); ?>
                    <?php renderActivitySortableHeader('Aktiviti', 'activity', $sort_column, $sort_dir); ?>
                    <?php renderActivitySortableHeader('Keterangan', 'description', $sort_column, $sort_dir); ?>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($logs)): ?>
                <tr>
                    <td colspan="7" style="text-align: center; padding: 40px; color: var(--text-muted);">
                        <i class="fas fa-inbox" style="font-size: 3rem; opacity: 0.3; margin-bottom: 10px;"></i><br>
                        <?= htmlspecialchars($empty_text) ?>
                    </td>
                </tr>
                <?php else: ?>
                <?php foreach ($logs as $index => $log): ?>
                <?php
                    $badge_class = getActivityBadgeClass($log['activity_type'] ?? '');
                    $role_class = 'badge-user';
                    if (($log['user_role'] ?? '') === 'admin') {
                        $role_class = 'badge-admin';
                    } elseif (($log['user_role'] ?? '') === 'superadmin') {
                        $role_class = 'badge-superadmin';
                    }
                    $bil = $offset + $index + 1;
                    $activity_description = trim((string) ($log['activity_description'] ?? ''));
                    if ($activity_description === '') {
                        $activity_description = 'Tiada keterangan terperinci direkodkan untuk aktiviti ini.';
                    }
                ?>
                <tr>
                    <td><?= $bil ?></td>
                    <td>
                        <strong><?= date('d/m/Y', strtotime($log['created_at'])) ?></strong><br>
                        <small style="color: var(--text-muted);"><?= date('H:i:s', strtotime($log['created_at'])) ?></small>
                    </td>
                    <td>
                        <div class="user-detail">
                            <strong><?= htmlspecialchars($log['user_name']) ?></strong>
                            <small><?= htmlspecialchars($log['user_email']) ?></small>
                            <?php if (!empty($log['last_login'])): ?>
                            <small style="color: var(--success);">
                                <i class="fas fa-clock"></i> Last: <?= date('d/m H:i', strtotime($log['last_login'])) ?>
                            </small>
                            <?php endif; ?>
                        </div>
                    </td>
                    <td><span class="badge <?= $role_class ?>"><?= ucfirst($log['user_role']) ?></span></td>
                    <td><?= htmlspecialchars($log['department'] ?? '-') ?></td>
                    <td><span class="badge <?= $badge_class ?>"><?= htmlspecialchars(getActivityDisplayLabel($log['activity_type'] ?? '')) ?></span></td>
                    <td class="activity-desc" title="<?= htmlspecialchars($activity_description) ?>">
                        <?= htmlspecialchars($activity_description) ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    <?php
}
?>
<!DOCTYPE html>
<html lang="ms">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pemantauan Aktiviti Pengguna | 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;
            --superadmin: #6c5ce7; --superadmin-dark: #5b4cdb;
            --bg-light: #f8fbfd; --bg-card: #ffffff; --text-main: #1a3a5c;
            --text-muted: #6c757d; --border: #e0e8f0; --sidebar-width: 240px;
            --success: #1a9955; --danger: #dc3545; --warning: #ffc107;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Segoe UI', 'Inter', Tahoma, Geneva, Verdana, sans-serif; }
        body { background: linear-gradient(135deg, #e0f7fa 0%, #f1f8e9 100%); min-height: 100vh; display: flex; color: var(--text-main); }
        
        /* Sidebar Styles */

        .sidebar { width: var(--sidebar-width); background: linear-gradient(180deg, #fff 0%, #f8fbfd 100%); border-right: 1px solid var(--border); position: fixed; height: 100vh; padding: 20px 0; overflow-y: auto; overflow-x: hidden; z-index: 1000; box-shadow: 2px 0 10px rgba(0,0,0,0.03); transition: width 0.3s ease; display:flex; flex-direction:column; }
        .sidebar.collapsed { width: 70px; }
        .sidebar-header { text-align: center; padding: 0 20px 20px; border-bottom: 1px solid var(--border); margin-bottom: 20px; white-space: nowrap; overflow: hidden; }
        .sidebar.collapsed .sidebar-header h3, .sidebar.collapsed .sidebar-header p, .sidebar.collapsed .menu-text { display: none; }
        .sidebar-header img { width: 50px; margin-bottom: 10px; transition: margin 0.3s ease; }
        .sidebar.collapsed .sidebar-header img { margin: 0 auto 10px; }
        .sidebar-header h3 { font-size: 1rem; font-weight: 700; color: var(--primary); margin-bottom: 4px; }
        .sidebar-header p { font-size: 0.75rem; color: var(--text-muted); }
        .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: var(--text-muted); font-size: 0.72rem; font-weight: 700; 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: var(--text-main); text-decoration: none; border-radius: 8px; margin-bottom: 4px; transition: all 0.2s ease; font-size: 0.9rem; white-space: nowrap; }
        .sidebar-menu li a:hover, .sidebar-menu li a.active { background: linear-gradient(90deg, var(--primary), var(--secondary)); color: #fff; }
        .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: var(--text-main); background: none; border: none; border-radius: 8px; 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: linear-gradient(90deg, var(--primary), var(--secondary)); color: #fff; }
        .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: var(--text-main); text-decoration: none; border-radius: 6px; 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: #e6f4ff; color: var(--primary); }
        .sidebar.collapsed + .main { margin-left: 70px; }
        .sidebar-toggle { position: absolute; right: -12px; top: 20px; width: 24px; height: 24px; background: var(--primary); color: #fff; border: none; border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 0.7rem; box-shadow: 0 2px 6px rgba(0,0,0,0.15); transition: transform 0.3s ease; z-index: 1001; }
        .sidebar.collapsed .sidebar-toggle { transform: rotate(180deg); }
        .main { margin-left: var(--sidebar-width); flex: 1; min-width: 0; padding: 25px 30px; transition: margin-left 0.3s ease; }
        .top-bar { background: var(--bg-card); padding: 15px 25px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.04); margin-bottom: 25px; display: flex; justify-content: space-between; align-items: center; border: 1px solid var(--border); }
        .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; }
        
        /* Stats Cards */
        .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-bottom: 25px; }
        .stat-card { background: var(--bg-card); padding: 20px; border-radius: 12px; text-align: center; border-top: 4px solid var(--primary); box-shadow: 0 2px 8px rgba(0,0,0,0.04); }
        .stat-card.warning { border-top-color: var(--warning); }
        .stat-card.success { border-top-color: var(--success); }
        .stat-card.danger { border-top-color: var(--danger); }
        .stat-card h3 { font-size: 2rem; margin: 10px 0; color: var(--text-main); }
        .stat-card p { font-size: 0.9rem; color: var(--text-muted); }
        .stat-card i { font-size: 1.8rem; color: var(--primary); margin-bottom: 8px; }
        
        /* Filter Box */
        .filter-box { background: var(--bg-card); padding: 20px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.04); margin-bottom: 25px; border: 1px solid var(--border); }
        .filter-box h4 { color: var(--primary); margin-bottom: 15px; font-size: 1.1rem; display: flex; align-items: center; gap: 8px; }
        .filter-form { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; align-items: end; }
        .filter-form .form-group { display: flex; flex-direction: column; gap: 5px; }
        .filter-form label { font-size: 0.85rem; font-weight: 600; color: var(--text-main); }
        .filter-form input, .filter-form select { padding: 10px 14px; border: 1px solid var(--border); border-radius: 8px; font-size: 0.9rem; }
        .filter-form button { padding: 10px 18px; background: linear-gradient(90deg, var(--primary), var(--secondary)); color: #fff; border: none; border-radius: 999px; cursor: pointer; font-size: 0.95rem; font-weight: 850; display: inline-flex; align-items: center; gap: 7px; text-decoration: none; }
        .filter-form button:hover { opacity: 0.95; }
        .filter-form a { padding: 10px 18px; background: #526b79; color: #fff; border-radius: 999px; text-decoration: none; text-align: center; display: inline-flex; align-items: center; gap: 7px; }
        
        .search-actions { display: flex; gap: 10px; margin-top: 20px; flex-wrap: wrap; }
        .btn { padding: 10px 18px; border: none; border-radius: 999px; cursor: pointer; font-size: 0.95rem; font-weight: 850; display: inline-flex; align-items: center; gap: 7px; text-decoration: none; transition: transform 0.2s ease, filter 0.2s ease, box-shadow 0.2s ease; }
        .btn:hover { transform: translateY(-1px); filter: brightness(1.04); }
        .btn-primary { background: linear-gradient(90deg, var(--primary), var(--secondary)); color: #fff; }
        .btn-secondary { background: #526b79; color: #fff; }
        .search-actions .btn { width: 40px; min-height: 38px; height: 38px; min-width: 40px; padding: 0; border-radius: 999px; justify-content: center; gap: 0; }
        .search-actions .btn i { margin: 0; }
        .search-actions .btn-secondary { background: rgba(255,255,255,0.70); color: var(--primary); border: 1px solid rgba(0,119,182,0.18); box-shadow: 0 10px 22px rgba(2,62,95,0.08); }
        /* Table */
        .card { background: var(--bg-card); border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.04); padding: 22px; border: 1px solid var(--border); }
        .activity-card-spaced { margin-top: 25px; min-width: 0; }
        .card-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 18px; padding-bottom: 14px; border-bottom: 1px solid var(--border); }
        .card-title { color: var(--primary); font-size: 1.15rem; font-weight: 600; }
        .table-responsive { overflow-x: auto; }
        .activity-table-scroll { width: 100%; min-width: 0; max-width: 100%; overflow-x: auto; overflow-y: hidden; box-sizing: border-box; padding-bottom: 2px; }
        table { width: 100%; min-width: 1250px; border-collapse: collapse; font-size: 0.9rem; }
        table th { background: #f8fafc; color: var(--primary); font-weight: 600; text-align: center; padding: 14px; border-bottom: 2px solid var(--border); white-space: nowrap; }
        .sort-link { color: inherit; display: inline-flex; align-items: center; justify-content: center; gap: 6px; text-decoration: none; width: 100%; }
        .sort-link:hover, .sort-link.active { color: var(--primary-dark); }
        .sort-indicator { font-size: 0.78rem; line-height: 1; opacity: 0.82; }
        table td { padding: 14px; border-bottom: 1px solid var(--border); vertical-align: middle; text-align: left; }
        table td.empty-state { text-align: center; }
        table tr:hover { background: #f8fbfd; }
        .badge { padding: 5px 12px; border-radius: 20px; font-size: 0.75rem; font-weight: 500; display: inline-block; }
        .badge-login { background: #d4edda; color: #155724; }
        .badge-logout { background: #fff3cd; color: #856404; }
        .badge-create { background: #e6f4ff; color: #0077b6; }
        .badge-update { background: #d1ecf1; color: #0c5460; }
        .badge-delete { background: #f8d7da; color: #721c24; }
        .badge-user { background: #e6f4ff; color: var(--primary); }
        .badge-admin { background: #d4edda; color: var(--success); }
        .badge-superadmin { background: linear-gradient(90deg, var(--superadmin), var(--superadmin-dark)); color: #fff; }
        
        .activity-desc { min-width: 520px; white-space: nowrap; }
        .user-detail { display: flex; flex-direction: column; gap: 2px; }
        .user-detail strong { font-size: 0.95rem; }
        .user-detail small { color: var(--text-muted); font-size: 0.85rem; }
        .pagination-wrap { display: flex; justify-content: space-between; align-items: center; gap: 14px; flex-wrap: wrap; margin-top: 20px; padding-top: 16px; border-top: 1px solid var(--border); }
        .pagination-info { color: var(--text-muted); font-size: 0.9rem; }
        .pagination { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
        .pagination a, .pagination span { min-width: 36px; height: 36px; padding: 0 10px; border: 1px solid var(--border); border-radius: 8px; display: inline-flex; align-items: center; justify-content: center; text-decoration: none; font-size: 0.9rem; font-weight: 600; color: var(--primary); background: #fff; }
        .pagination a:hover { background: #e6f4ff; border-color: var(--primary); }
        .pagination .active-page { background: linear-gradient(90deg, var(--primary), var(--secondary)); color: #fff; border-color: transparent; }
        .pagination .disabled-page { color: var(--text-muted); background: #f8fafc; cursor: not-allowed; }
        
        .page-footer { text-align: center; padding: 20px; color: var(--text-muted); font-size: 0.8rem; margin-top: 30px; }

        :root {
            --primary: #0077b6;
            --primary-dark: #005f99;
            --secondary: #00b4d8;
            --deep-blue: #023e5f;
            --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;
            --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);
        }
        body {
            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;
            color: var(--text-main);
            overflow-x: hidden;
        }
        body::before {
            content: '';
            position: fixed;
            inset: 0;
            background:
                radial-gradient(circle at 18% 18%, rgba(0,180,216,0.22), transparent 28%),
                radial-gradient(circle at 86% 12%, rgba(0,119,182,0.18), transparent 28%),
                linear-gradient(120deg, rgba(255,255,255,0.28), rgba(255,255,255,0.08));
            pointer-events: none;
            z-index: 0;
        }
        body::after {
            content: '';
            position: fixed;
            width: 520px;
            height: 520px;
            right: -180px;
            bottom: -220px;
            background: rgba(0,180,216,0.18);
            filter: blur(8px);
            transform: rotate(18deg);
            border-radius: 42px;
            pointer-events: none;
            z-index: 0;
        }
        .sidebar {
            background: linear-gradient(180deg, rgba(2,62,95,0.94), rgba(0,119,182,0.84));
            border-right: 1px solid rgba(255,255,255,0.22);
            box-shadow: 18px 0 44px rgba(2,38,60,0.20);
            backdrop-filter: blur(18px) saturate(1.25);
            overflow: hidden;
        }
        .sidebar-header {
            flex: 0 0 auto;
            background: transparent !important;
            border-bottom: 1px solid rgba(255,255,255,0.16);
        }
        .sidebar-header img {
            width: 58px;
            filter: drop-shadow(0 8px 14px rgba(0,0,0,0.22));
        }
        .sidebar-header h3 { color: #fff; font-weight: 800; }
        .sidebar-header p { color: rgba(255,255,255,0.72); }
        .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;
        }
        .sidebar-section { color: rgba(255,255,255,0.56); }
        .sidebar-menu li a,
        .sidebar-menu .dropdown-toggle {
            color: rgba(255,255,255,0.88);
        }
        .sidebar-menu li a:hover,
        .sidebar-menu li a.active,
        .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-menu a { color: rgba(255,255,255,0.78); }
        .sidebar-menu .dropdown-menu a:hover,
        .sidebar-menu .dropdown-menu a.active {
            background: rgba(255,255,255,0.16);
            color: #fff;
        }
        .sidebar-toggle {
            right: 10px;
            top: 28px;
            width: 28px;
            height: 28px;
            background: rgba(255,255,255,0.18);
            border: 1px solid rgba(255,255,255,0.22);
            box-shadow: 0 8px 20px rgba(0,0,0,0.15);
        }
        .main {
            padding: 28px 32px;
            position: relative;
            z-index: 1;
        }
        .top-bar,
        .stat-card,
        .filter-box,
        .card {
            background: var(--glass);
            border: 1px solid var(--border);
            box-shadow: var(--shadow-soft);
            backdrop-filter: blur(24px) saturate(1.35);
        }
        .top-bar {
            border-radius: 18px;
            padding: 16px 24px;
        }
        .top-bar h2,
        .filter-box h4,
        .card-title {
            color: var(--deep-blue);
            font-weight: 800;
        }
        .stat-card,
        .filter-box,
        .card {
            border-radius: 22px;
        }
        .stat-card {
            border-top: 4px solid var(--secondary);
        }
        .stat-card h3 {
            color: var(--deep-blue);
            font-weight: 800;
        }
        .stat-card i {
            color: var(--primary);
        }
        .filter-form input,
        .filter-form select {
            background: rgba(255,255,255,0.76);
            border-color: rgba(255,255,255,0.62);
            border-radius: 12px;
            color: var(--text-main);
        }
        .filter-form input:focus,
        .filter-form select:focus {
            border-color: rgba(0,180,216,0.82);
            box-shadow: 0 0 0 4px rgba(0,180,216,0.16);
            outline: none;
        }
        .filter-form button,
        .btn-primary {
            background: linear-gradient(90deg, var(--primary), var(--secondary));
            box-shadow: 0 14px 28px rgba(0,119,182,0.18);
        }
        .filter-form a,
        .btn-secondary {
            background: #526b79;
            color: #fff;
            border: none;
        }
        .btn,
        .filter-form button,
        .filter-form a {
            padding: 10px 18px;
            border-radius: 999px;
            font-weight: 850;
            gap: 7px;
            transition: transform 0.2s ease, filter 0.2s ease, box-shadow 0.2s ease;
        }
        .btn:hover,
        .filter-form button:hover,
        .filter-form a:hover {
            transform: translateY(-1px);
            filter: brightness(1.04);
        }
        .search-actions .btn,
        .filter-form .search-actions button,
        .filter-form .search-actions a {
            width: 40px;
            min-height: 38px;
            height: 38px;
            min-width: 40px;
            padding: 0;
            border-radius: 999px;
            justify-content: center;
            gap: 0;
        }
        .filter-form .search-actions .btn-secondary {
            background: rgba(255,255,255,0.70);
            color: var(--primary);
            border: 1px solid rgba(0,119,182,0.18);
            box-shadow: 0 10px 22px rgba(2,62,95,0.08);
        }
        table {
            border-collapse: separate;
            border-spacing: 0;
        }
        table th {
            background: rgba(255,255,255,0.70);
            color: var(--deep-blue);
            border-bottom: 1px solid rgba(0,119,182,0.16);
        }
        .sort-link {
            color: inherit;
        }
        .sort-link:hover,
        .sort-link.active {
            color: var(--primary);
        }
        table td {
            border-bottom: 1px solid rgba(0,119,182,0.10);
        }
        table tr:hover {
            background: rgba(255,255,255,0.42);
        }
        .badge {
            font-weight: 700;
            border: 1px solid rgba(255,255,255,0.48);
        }
        .pagination a,
        .pagination span {
            background: rgba(255,255,255,0.76);
            border-color: rgba(0,119,182,0.16);
            border-radius: 12px;
        }
        .pagination a:hover {
            background: rgba(0,180,216,0.14);
        }
        .pagination .active-page {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: #fff;
        }
        .pagination .disabled-page {
            background: rgba(255,255,255,0.42);
        }
        .main .pagination-wrap {
            padding-right: 24px;
        }
        .main .pagination {
            margin-right: 8px;
        }
        .page-footer { color: var(--text-muted); }

        @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; }
        }
        @media (max-width: 640px) {
            .main .pagination-wrap {
                justify-content: center;
                padding-right: 0;
            }
            .main .pagination-info {
                width: 100%;
                text-align: center;
            }
            .main .pagination {
                width: 100%;
                justify-content: center;
                margin-right: 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-superadmin">

    <aside class="sidebar" id="sidebar">
    <button class="sidebar-toggle" id="sidebarToggle" title="Tutup/Buka Menu" aria-label="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, 'user_activity.php'); ?>
        </ul>
</aside>

    <main class="main">
        <div class="top-bar">
            <h2><i class="fas fa-history"></i> Pemantauan Aktiviti Pengguna</h2>
            <?php renderTopBarUserMenu($conn, $role, 'user_activity.php'); ?>
        </div>

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

        <!-- STATS -->
        <div class="stats-grid">
            <div class="stat-card success">
                <i class="fas fa-sign-in-alt"></i>
                <h3><?= $stats['logins'] ?? 0 ?></h3>
                <p>Login (7 Hari)</p>
            </div>
            <div class="stat-card warning">
                <i class="fas fa-sign-out-alt"></i>
                <h3><?= $stats['logouts'] ?? 0 ?></h3>
                <p>Logout (7 Hari)</p>
            </div>
            <div class="stat-card">
                <i class="fas fa-folder"></i>
                <h3><?= $stats['folder_actions'] ?? 0 ?></h3>
                <p>Tindakan Fail (7 Hari)</p>
            </div>
            <div class="stat-card danger">
                <i class="fas fa-file-alt"></i>
                <h3><?= $stats['document_actions'] ?? 0 ?></h3>
                <p>Tindakan Surat (7 Hari)</p>
            </div>
        </div>

        <!-- FILTER -->
        <div class="filter-box">
            <h4><i></i> Carian Rekod Aktiviti</h4>
            <form method="GET" class="filter-form">
                <?php if ($activity_sort_column !== ''): ?>
                <input type="hidden" name="sort" value="<?= htmlspecialchars($activity_sort_column) ?>">
                <input type="hidden" name="dir" value="<?= htmlspecialchars($activity_sort_dir) ?>">
                <?php endif; ?>
                <div class="form-group">
                    <label>Cari User</label>
                    <input type="text" name="filter_user" placeholder="Nama atau emel..." value="<?= htmlspecialchars($filter_user) ?>">
                </div>
                <div class="form-group">
                    <label>Role</label>
                    <select name="filter_role">
                        <option value="all">Semua Role</option>
                        <option value="user" <?= $filter_role === 'user' ? 'selected' : '' ?>>User</option>
                        <option value="admin" <?= $filter_role === 'admin' ? 'selected' : '' ?>>Admin</option>
                        <option value="superadmin" <?= $filter_role === 'superadmin' ? 'selected' : '' ?>>Superadmin</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Bahagian</label>
                    <select name="filter_department">
                        <option value="all">Semua Bahagian</option>
                        <?php foreach ($departments as $department): ?>
                            <option value="<?= htmlspecialchars($department) ?>" <?= $filter_department === $department ? 'selected' : '' ?>><?= htmlspecialchars($department) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>Jenis Aktiviti</label>
                    <select name="filter_activity">
                        <option value="all">Semua Aktiviti</option>
                        <?php foreach ($activity_types as $key => $label): ?>
                            <option value="<?= $key ?>" <?= $filter_activity === $key ? 'selected' : '' ?>><?= $label ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>Tarikh Dari</label>
                    <input type="date" name="filter_date_from" value="<?= htmlspecialchars($filter_date_from) ?>">
                </div>
                <div class="form-group">
                    <label>Tarikh Hingga</label>
                    <input type="date" name="filter_date_to" value="<?= htmlspecialchars($filter_date_to) ?>">
                </div>
                <div class="search-actions">
                    <button type="submit" class="btn btn-primary" title="Cari" aria-label="Cari"><i class="fas fa-search"></i></button>
                    <a href="user_activity.php" class="btn btn-secondary" title="Reset" aria-label="Reset"><i class="fas fa-rotate-left"></i></a>
                </div>
            </form>
        </div>

        <!-- ACTIVITY TABLE -->
        <div class="card">
            <div class="card-header">
                <div class="card-title">
                    <i class="fas fa-list-check"></i>
                    Semua Aktiviti (<?= $total_logs ?> rekod)
                </div>
            </div>
            <?php renderActivityLogsTable($logs, 'Tiada rekod aktiviti dijumpai.', $offset, $activity_sort_column, $activity_sort_dir); ?>
        </div>

        <div class="pagination-wrap">
            <div class="pagination-info">
                <?php
                    $from_record = $total_logs > 0 ? $offset + 1 : 0;
                    $to_record = min($offset + $logs_per_page, $total_logs);
                ?>
                Papar <?= $from_record ?> - <?= $to_record ?> daripada <?= $total_logs ?> rekod
            </div>
            <div class="pagination">
                <?php if ($current_page > 1): ?>
                    <a href="<?= htmlspecialchars(buildActivityPageUrl($current_page - 1)) ?>" title="Halaman sebelumnya"><i class="fas fa-chevron-left"></i></a>
                <?php else: ?>
                    <span class="disabled-page" title="Halaman sebelumnya" aria-label="Halaman sebelumnya"><i class="fas fa-chevron-left"></i></span>
                <?php endif; ?>

                <?php
                    $start_page = max(1, $current_page - 2);
                    $end_page = min($total_pages, $current_page + 2);
                    if ($start_page > 1) {
                        echo '<a href="' . htmlspecialchars(buildActivityPageUrl(1)) . '">1</a>';
                        if ($start_page > 2) {
                            echo '<span class="disabled-page">...</span>';
                        }
                    }
                    for ($page = $start_page; $page <= $end_page; $page++):
                ?>
                    <?php if ($page === $current_page): ?>
                        <span class="active-page"><?= $page ?></span>
                    <?php else: ?>
                        <a href="<?= htmlspecialchars(buildActivityPageUrl($page)) ?>"><?= $page ?></a>
                    <?php endif; ?>
                <?php endfor; ?>
                <?php
                    if ($end_page < $total_pages) {
                        if ($end_page < $total_pages - 1) {
                            echo '<span class="disabled-page">...</span>';
                        }
                        echo '<a href="' . htmlspecialchars(buildActivityPageUrl($total_pages)) . '">' . $total_pages . '</a>';
                    }
                ?>

                <?php if ($current_page < $total_pages): ?>
                    <a href="<?= htmlspecialchars(buildActivityPageUrl($current_page + 1)) ?>" title="Halaman seterusnya"><i class="fas fa-chevron-right"></i></a>
                <?php else: ?>
                    <span class="disabled-page" title="Halaman seterusnya" aria-label="Halaman seterusnya"><i class="fas fa-chevron-right"></i></span>
                <?php endif; ?>
            </div>
        </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);
            });
        });
        function confirmLogout() {
            return confirm("Adakah anda pasti ingin log keluar?");
        }
    </script>
    <?php renderSessionTimeoutScript(); ?>
</body>
</html>
