<?php
/**
 * Student Dashboard - TutorKita System (COMPLETE VERSION)
 * All 7 Tabs Fully Functional
 * Bilingual Support: Bahasa Melayu (Primary) + English
 * Mobile Responsive with Bootstrap 5
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$db_path = dirname(__DIR__) . '/db.php';
require_once $db_path;

// Include helper functions
$functions_path = dirname(__DIR__) . '/includes/functions.php';
if (file_exists($functions_path)) {
    require_once $functions_path;
}

// Check student session
if (!isset($_SESSION['user_type']) || $_SESSION['user_type'] !== 'student') {
    header('Location: ../index.php');
    exit;
}

// Check maintenance mode
try {
    $stmt = $pdo->query("SELECT maintenance_mode FROM admin WHERE id = 1");
    $mMode = $stmt->fetch();
    if ($mMode && $mMode['maintenance_mode'] == '1') {
        session_destroy();
        header('Location: ../index.php?maintenance=1');
        exit;
    }
} catch (Exception $e) {
    error_log('Notification error: ' . $e->getMessage());
}


// Get student info
$student = [];
$portalName = 'TutorKita';
$portalTagline = 'Platform Pembelajaran Terbaik';
$portalLogo = '';
$portalFavicon = '';
$themeColor = '#667eea';
$portalBackground = '';
$systemLanguage = 'ms'; // Default: Bahasa Melayu

try {
    // Get admin settings for portal customization
    $stmt = $pdo->prepare("SELECT portal_name, portal_tagline, portal_logo, portal_favicon, theme_color FROM admin WHERE id = 1");
    $stmt->execute();
    $adminSettings = $stmt->fetch();
    if ($adminSettings) {
        $portalName = $adminSettings['portal_name'] ?: 'TutorKita';
        $portalTagline = $adminSettings['portal_tagline'] ?: 'Platform Pembelajaran Terbaik';
        $portalLogo = $adminSettings['portal_logo'] ?: '';
        $portalFavicon = $adminSettings['portal_favicon'] ?: '';
        $themeColor = $adminSettings['theme_color'] ?: '#667eea';
    }

    // Get student data
    $stmt = $pdo->prepare("SELECT * FROM students WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $student = $stmt->fetch() ?: [];

} catch (Exception $e) {
    $student = [];
}

$studentName = $student['full_name'] ?? ($_SESSION['full_name'] ?? 'Pelajar');
$studentEmoji = $student['profile_emoji'] ?? '👨‍🎓';
$studentSubjects = json_decode($student['required_subjects'] ?? '[]', true) ?: [];
$studentAge = $student['age'] ?? '-';
$studentLevel = $student['education_level'] ?? '-';
$studentGrade = $student['grade_level'] ?? '-';
$studentPhone = $student['phone'] ?? '-';
$studentParent = $student['parent_guardian_name'] ?? '-';

// Helper function for color adjustment (inline if not in functions.php)
if (!function_exists('adjustBrightness')) {
    function adjustBrightness($hex, $steps)
    {
        $hex = str_replace('#', '', $hex);
        $r = hexdec(substr($hex, 0, 2));
        $g = hexdec(substr($hex, 2, 2));
        $b = hexdec(substr($hex, 4, 2));
        $r = max(0, min(255, $r + $steps));
        $g = max(0, min(255, $g + $steps));
        $b = max(0, min(255, $b + $steps));
        return '#' . str_pad(dechex($r), 2, '0', STR_PAD_LEFT)
            . str_pad(dechex($g), 2, '0', STR_PAD_LEFT)
            . str_pad(dechex($b), 2, '0', STR_PAD_LEFT);
    }
}

$currentTab = isset($_GET['tab']) ? $_GET['tab'] : 'dashboard';

// Dynamic Greeting logic
$hour = date('H');
if ($hour < 12) {
    $dynamicGreeting = 'Selamat Pagi';
} elseif ($hour < 14) {
    $dynamicGreeting = 'Selamat Tengah Hari';
} elseif ($hour < 19) {
    $dynamicGreeting = 'Selamat Petang';
} else {
    $dynamicGreeting = 'Selamat Malam';
}
?>
<!DOCTYPE html>
<html lang="ms">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard Pelajar - <?php echo htmlspecialchars($portalName); ?></title>

    <!-- Favicon -->
    <link rel="icon" type="image/x-icon"
        href="<?php echo htmlspecialchars(!empty($portalFavicon) ? $portalFavicon : '../favicon.ico'); ?>">

    <!-- Google Fonts: Inter -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">

    <!-- Bootstrap 5 -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- FontAwesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <!-- Animate.css -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">

    <!-- SweetAlert2 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-bootstrap-4/bootstrap-4.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <!-- Main Stylesheet -->
    <link rel="stylesheet" href="../css/style.css">

    <style>
        :root {
            --primary-color:
                <?php echo $themeColor; ?>
            ;
            --primary-dark:
                <?php echo adjustBrightness($themeColor, -20); ?>
            ;
            --primary-light:
                <?php echo adjustBrightness($themeColor, 20); ?>
            ;
            --glass-bg: rgba(255, 255, 255, 0.85);
            --glass-border: rgba(255, 255, 255, 0.4);
            --premium-shadow: 0 10px 30px -5px rgba(0, 0, 0, 0.1);
            --radius-xl: 32px;
            --radius-lg: 20px;
        }

        body {
            font-family: 'Inter', system-ui, -apple-system, sans-serif;
            background-color: #f8fafc;
            color: #1e293b;
            -webkit-tap-highlight-color: transparent;
        }

        .realtime-clock {
            font-size: 1.5rem;
            font-weight: bold;
            color: var(--primary-color);
        }

        .realtime-date {
            color: #666;
            font-size: 0.9rem;
        }

        .welcome-banner {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
            color: white;
            padding: 40px;
            border-radius: 20px;
            margin-bottom: 30px;
            display: flex;
            align-items: center;
            gap: 30px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        }

        .welcome-banner h1 {
            color: white;
            margin-bottom: 10px;
            font-size: 2rem;
        }

        .welcome-emoji {
            font-size: 5rem;
            animation: bounce 2s infinite;
        }

        @keyframes bounce {

            0%,
            100% {
                transform: translateY(0);
            }

            50% {
                transform: translateY(-10px);
            }
        }

        .stat-card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
            transition: all 0.3s ease;
            border-left: 4px solid var(--primary-color);
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
        }

        .stat-icon {
            font-size: 3rem;
            margin-bottom: 10px;
        }

        .stat-value {
            font-size: 2.5rem;
            font-weight: bold;
            color: var(--primary-color);
        }

        .stat-label {
            color: #666;
            font-size: 0.9rem;
        }

        .schedule-card,
        .announcement-card,
        .module-card,
        .class-card,
        .forum-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 15px;
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.08);
            transition: all 0.3s ease;
            border-left: 4px solid var(--primary-color);
        }

        .schedule-card:hover,
        .announcement-card:hover,
        .module-card:hover,
        .class-card:hover,
        .forum-card:hover {
            transform: translateX(5px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.12);
        }

        /* Notification Bell & Dropdown Styles */
        .notification-bell-wrapper {
            position: relative;
            margin-right: 15px;
        }

        .notification-bell-btn {
            background: #f1f5f9;
            border: none;
            width: 45px;
            height: 45px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.4rem;
            cursor: pointer;
            color: var(--primary-color);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
        }

        .notification-bell-btn:hover {
            background: #e2e8f0;
            transform: translateY(-2px);
        }

        .notification-badge {
            position: absolute;
            top: -5px;
            right: -5px;
            background: #ef4444;
            color: white;
            font-size: 0.7rem;
            font-weight: 800;
            padding: 2px 6px;
            border-radius: 10px;
            border: 2px solid white;
            min-width: 18px;
            height: 18px;
            display: none;
            align-items: center;
            justify-content: center;
        }

        .notification-badge.show {
            display: flex;
            animation: badgePulse 1.5s infinite;
        }

        @keyframes badgePulse {
            0% {
                transform: scale(1);
                box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.7);
            }

            70% {
                transform: scale(1.1);
                box-shadow: 0 0 0 10px rgba(239, 68, 68, 0);
            }

            100% {
                transform: scale(1);
                box-shadow: 0 0 0 0 rgba(239, 68, 68, 0);
            }
        }

        @keyframes bellShake {

            0%,
            100% {
                transform: rotate(0);
            }

            20% {
                transform: rotate(15deg);
            }

            40% {
                transform: rotate(-15deg);
            }

            60% {
                transform: rotate(10deg);
            }

            80% {
                transform: rotate(-10deg);
            }
        }

        .notification-dropdown {
            position: absolute;
            top: 100%;
            right: 0;
            width: 320px;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
            margin-top: 10px;
            display: none;
            z-index: 1000;
            border: 1px solid #eee;
            overflow: hidden;
        }

        .notification-dropdown.show {
            display: block;
            animation: slideInUp 0.3s ease-out;
        }

        .notification-header {
            padding: 15px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: #f8f9fa;
        }

        .notification-list {
            max-height: 350px;
            overflow-y: auto;
        }

        .notification-item {
            padding: 12px 15px;
            border-bottom: 1px solid #f8f9fa;
            display: flex;
            gap: 12px;
            transition: background 0.2s;
            cursor: pointer;
        }

        .notification-item:hover {
            background: #f1f5f9;
        }

        .notification-item.unread {
            background: #f0f7ff;
            border-left: 3px solid var(--primary-color);
        }

        .notification-icon {
            font-size: 1.2rem;
            width: 35px;
            height: 35px;
            background: white;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
        }

        .notification-info {
            flex: 1;
        }

        .notif-title {
            font-weight: 700;
            font-size: 0.85rem;
            color: #333;
            margin-bottom: 2px;
        }

        .notif-msg {
            font-size: 0.75rem;
            color: #666;
            line-height: 1.3;
        }

        .notif-time {
            font-size: 0.7rem;
            color: #999;
            margin-top: 5px;
        }

        /* Existing Styles ... */
        .emoji-picker {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 10px;
        }

        .emoji-option {
            font-size: 2rem;
            width: 50px;
            height: 50px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: white;
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .emoji-option:hover {
            transform: scale(1.1);
            border-color: var(--primary-color);
        }

        .emoji-option.selected {
            border-color: var(--primary-color);
            background: rgba(102, 126, 234, 0.1);
        }

        .tab-content {
            display: none;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .tab-content.active {
            display: block;
            opacity: 1;
        }

        /* Mobile Adjustments */
        .mobile-bottom-nav {
            display: none;
        }

        .mobile-header {
            display: none;
        }

        @media (max-width: 1024px) {
            .mobile-bottom-nav {
                display: flex !important;
                position: fixed;
                bottom: 20px;
                left: 20px;
                right: 20px;
                height: 70px;
                background: rgba(255, 255, 255, 0.9);
                backdrop-filter: blur(20px);
                border-radius: 25px;
                z-index: 1000;
                justify-content: space-around;
                align-items: center;
                box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
            }

            .nav-tab-item {
                display: flex;
                flex-direction: column;
                align-items: center;
                color: #94a3b8;
                font-size: 0.7rem;
                font-weight: 600;
                text-decoration: none !important;
            }

            .nav-tab-item.active {
                color: var(--primary-color);
            }

            .mobile-header {
                display: flex !important;
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                height: 75px;
                background: white;
                z-index: 1001;
                align-items: center;
                justify-content: space-between;
                padding: 0 15px;
                box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            }

            .main-content {
                margin-left: 0 !important;
                padding: 90px 16px 120px 16px !important;
            }
        }
    
    .card {
        border-radius: 20px;
        border: none;
        box-shadow: 0 10px 40px rgba(0,0,0,0.05);
        overflow: hidden;
        position: relative;
        background: #ffffff;
    }
    
    .card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 6px;
        background: linear-gradient(90deg, var(--primary-color) 0%, #764ba2 100%);
    }
    
    .card-header {
        background: #ffffff;
        padding: 20px 25px;
        border-bottom: 1px solid #f0f0f0;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    
    .card-title {
        margin: 0;
        font-size: 1.15rem;
        font-weight: 700;
        color: #1a1a2e;
    }
    
    .module-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
        gap: 15px;
        align-items: start;
    }
    
    @media (max-width: 576px) {
        .module-grid {
            grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
        }
    }
    </style>
</head>


<!-- Sidebar Overlay -->
<div class="sidebar-overlay" id="sidebarOverlay" onclick="toggleMobileMenu()"></div>

<div class="dashboard-layout">
    <aside class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <div class="sidebar-logo">
                <?php if (!empty($portalLogo)): ?>
                    <img src="<?php echo htmlspecialchars($portalLogo); ?>" alt="Logo"
                        style="width: 80px; height: 80px; object-fit: contain;">
                <?php else: ?>
                    <span style="font-size: 1.5rem;">📚</span>
                <?php endif; ?>
            </div>
            <h2 class="sidebar-title"><?php echo htmlspecialchars($portalName); ?></h2>
            <p class="sidebar-subtitle">Panel Pelajar</p>

            <!-- Profile Identity Section in Sidebar -->
            <div class="sidebar-profile"
                style="margin-top: 25px; padding: 15px; background: rgba(255, 255, 255, 0.1); border-radius: 12px; display: flex; align-items: center; gap: 12px; border: 1px solid rgba(255, 255, 255, 0.1);">
                <div
                    style="font-size: 2rem; background: white; width: 50px; height: 50px; display: flex; align-items: center; justify-content: center; border-radius: 12px; box-shadow: 0 4px 10px rgba(0,0,0,0.1);">
                    <?php echo htmlspecialchars($studentEmoji); ?>
                </div>
                <div style="overflow: hidden;">
                    <h4
                        style="margin: 0; font-size: 0.95rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: white;">
                        <?php echo htmlspecialchars($studentName); ?>
                    </h4>
                    <p style="margin: 0; font-size: 0.75rem; opacity: 0.8; color: white;">
                        @<?php echo htmlspecialchars($student['username'] ?? 'pelajar'); ?>
                    </p>
                </div>
            </div>
        </div>

        <nav class="sidebar-nav">
            <a href="#" onclick="switchTab(event, 'dashboard'); closeMobileMenu();" class="nav-item active"
                id="nav-dashboard">
                <span class="nav-icon">🏠</span> Dashboard
            </a>
            <a href="#" onclick="switchTab(event, 'schedule'); closeMobileMenu();" class="nav-item" id="nav-schedule">
                <span class="nav-icon">📅</span> Jadual
            </a>
            <a href="#" onclick="switchTab(event, 'modules'); closeMobileMenu();" class="nav-item" id="nav-modules">
                <span class="nav-icon">📚</span> Modul Saya
            </a>
            <a href="#" onclick="switchTab(event, 'classes'); closeMobileMenu();" class="nav-item" id="nav-classes">
                <span class="nav-icon">🏫</span> Kelas Saya
            </a>
            <a href="#" onclick="switchTab(event, 'forum'); closeMobileMenu();" class="nav-item" id="nav-forum">
                <span class="nav-icon">💬</span> Forum
            </a>
            <a href="#" onclick="switchTab(event, 'announcements'); closeMobileMenu();" class="nav-item"
                id="nav-announcements">
                <span class="nav-icon">📢</span> Pengumuman
            </a>
            <a href="#" onclick="switchTab(event, 'profile'); closeMobileMenu();" class="nav-item" id="nav-profile">
                <span class="nav-icon">👤</span> Profil
            </a>
        </nav>

        <div style="padding: 20px; margin-top: auto;">
            <button class="btn btn-secondary" style="width: 100%;" onclick="logout()">
                <span>🚪</span> Log Keluar
            </button>
        </div>
    </aside>

    <main class="main-content">



        <div class="page-header">
            <div style="flex: 1;">
                <h1 class="page-title" id="userGreeting">Selamat sejahtera,
                    <?php echo htmlspecialchars($studentName); ?>!
                </h1>
                <p class="page-subtitle"><?php echo htmlspecialchars($portalTagline); ?></p>
            </div>
            <div style="text-align: right; padding-right: 20px; display: flex; align-items: center; gap: 20px;">
                <!-- Notification Bell -->
                <div class="notification-bell-wrapper">
                    <button class="notification-bell-btn" id="notifBtn" onclick="toggleNotifDropdown(event)">
                        🔔 <span class="notification-badge" id="notifBadge">0</span>
                    </button>
                    <div class="notification-dropdown" id="notifDropdown">
                        <div class="notification-header">
                            <h4>Notifikasi</h4>
                            <div style="display: flex; gap: 10px;">
                                <button class="btn btn-sm btn-link" onclick="markAllAsRead()"
                                    style="text-decoration: none; font-size: 0.8rem; color: var(--primary-color);">Tanda semua dibaca</button>
                                <button class="btn btn-sm btn-link" onclick="deleteAllNotifications()"
                                    style="text-decoration: none; font-size: 0.8rem; color: var(--danger-color);">Padam semua</button>
                            </div>
                        </div>
                        <div class="notification-list" id="notifList">
                            <p class="text-center text-muted p-4">Tiada notifikasi</p>
                        </div>
                        <div class="notification-footer">
                            <a href="#" onclick="switchTab(event, 'announcements'); toggleNotifDropdown();">Lihat Semua
                                Pengumuman</a>
                        </div>
                    </div>
                </div>

                <div>
                    <div id="realtimeClock" class="realtime-clock">00:00:00</div>
                    <div id="realtimeDate" class="realtime-date">Mengira...</div>
                </div>
            </div>
        </div>

        <!-- TAB 1: DASHBOARD -->
        <div id="dashboard" class="tab-content active">
            <!-- Animated Student Welcome Banner -->
            <div class="welcome-banner premium-gradient animate__animated animate__fadeIn"
                style="position: relative; overflow: hidden; padding: 40px; border-radius: var(--radius-xl); margin-bottom: 30px; color: white;">
                <div class="floating-bubbles">
                    <div class="bubble"
                        style="width: 40px; height: 40px; left: 10%; bottom: -10%; animation-delay: 0s;"></div>
                    <div class="bubble"
                        style="width: 20px; height: 20px; left: 30%; bottom: -10%; animation-delay: 2s;"></div>
                    <div class="bubble"
                        style="width: 60px; height: 60px; left: 50%; bottom: -10%; animation-delay: 4s;"></div>
                    <div class="bubble"
                        style="width: 30px; height: 30px; left: 70%; bottom: -10%; animation-delay: 1s;"></div>
                    <div class="bubble"
                        style="width: 50px; height: 50px; left: 90%; bottom: -10%; animation-delay: 3s;"></div>
                </div>
                <div class="reveal-up"
                    style="display: flex; align-items: center; gap: 25px; position: relative; z-index: 2;">
                    <div class="welcome-emoji-big lift-on-hover"
                        style="font-size: 5rem; background: rgba(255,255,255,0.15); width: 120px; height: 120px; display: flex; align-items: center; justify-content: center; border-radius: 30px; backdrop-filter: blur(10px); box-shadow: var(--shadow-md);">
                        <?php echo htmlspecialchars($studentEmoji); ?>
                    </div>
                    <div>
                        <h1
                            style="color: white; margin-bottom: 8px; font-size: 2.8rem; font-weight: 800; letter-spacing: -1px;">
                            <?php echo htmlspecialchars($dynamicGreeting); ?>,
                            <?php echo htmlspecialchars(explode(' ', $studentName)[0]); ?>! 👋
                        </h1>
                        <p style="font-size: 1.1rem; opacity: 0.95; font-weight: 500;">
                            Anda ada <span id="classTodayCount"
                                style="font-weight: 700; text-decoration: underline;">0</span> sesi kelas untuk bulan ini.
                            Jom belajar!
                        </p>
                        <div
                            style="margin-top: 20px; font-weight: 500; background: rgba(255,255,255,0.15); padding: 8px 18px; border-radius: 30px; display: inline-block; backdrop-filter: blur(5px);">
                            <span id="bannerDay">...</span>, <span id="bannerDate">...</span> | <span
                                id="bannerTime">00:00:00</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Premium Student Stats Grid -->
            <div class="stats-grid"
                style="display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 25px; margin-bottom: 30px;">
                <div class="stat-card lift-on-hover glow-on-hover animate__animated animate__zoomIn"
                    style="background: white; border-radius: var(--radius-xl); padding: 30px; display: flex; align-items: center; box-shadow: var(--shadow-md); position: relative; overflow: hidden;">
                    <div class="stat-icon"
                        style="background: rgba(102, 126, 234, 0.1); width: 70px; height: 70px; border-radius: 20px; font-size: 2.5rem; display: flex; align-items: center; justify-content: center; margin-right: 20px;">
                        📚</div>
                    <div class="stat-content">
                        <div class="stat-value" id="studentSubjectCount"
                            style="font-size: 2.8rem; font-weight: 800; background: var(--gradient-primary); -webkit-background-clip: text; -webkit-text-fill-color: transparent; border: none;">
                            <?php echo count($studentSubjects); ?>
                        </div>
                        <div class="stat-label"
                            style="font-weight: 600; color: #718096; text-transform: uppercase; font-size: 0.8rem; letter-spacing: 1px;">
                            Subjek Berdaftar</div>
                    </div>
                </div>

                <div class="stat-card lift-on-hover glow-on-hover animate__animated animate__zoomIn"
                    style="animation-delay: 0.1s; background: white; border-radius: var(--radius-xl); padding: 30px; display: flex; align-items: center; box-shadow: var(--shadow-md); position: relative; overflow: hidden;">
                    <div class="stat-icon"
                        style="background: rgba(40, 167, 69, 0.1); width: 70px; height: 70px; border-radius: 20px; font-size: 2.5rem; display: flex; align-items: center; justify-content: center; margin-right: 20px;">
                        🎯</div>
                    <div class="stat-content">
                        <div class="stat-value"
                            style="font-size: 1.6rem; font-weight: 800; background: var(--gradient-success); -webkit-background-clip: text; -webkit-text-fill-color: transparent; border: none;">
                            <?php echo htmlspecialchars($studentLevel); ?>
                        </div>
                        <div class="stat-label"
                            style="font-weight: 600; color: #718096; text-transform: uppercase; font-size: 0.8rem; letter-spacing: 1px;">
                            Tahap Pendidikan</div>
                    </div>
                </div>

                <div class="stat-card lift-on-hover glow-on-hover animate__animated animate__zoomIn"
                    style="animation-delay: 0.2s; background: white; border-radius: var(--radius-xl); padding: 30px; display: flex; align-items: center; box-shadow: var(--shadow-md); position: relative; overflow: hidden;">
                    <div class="stat-icon"
                        style="background: rgba(240, 147, 251, 0.1); width: 70px; height: 70px; border-radius: 20px; font-size: 2.5rem; display: flex; align-items: center; justify-content: center; margin-right: 20px;">
                        📅</div>
                    <div class="stat-content">
                        <div class="stat-value" id="upcomingClassesCount"
                            style="font-size: 2.8rem; font-weight: 800; background: var(--gradient-warning); -webkit-background-clip: text; -webkit-text-fill-color: transparent; border: none;">
                            0</div>
                        <div class="stat-label"
                            style="font-weight: 600; color: #718096; text-transform: uppercase; font-size: 0.8rem; letter-spacing: 1px;">
                            Kelas Akan Datang</div>
                    </div>
                </div>

                <div class="stat-card lift-on-hover glow-on-hover animate__animated animate__zoomIn"
                    style="animation-delay: 0.3s; background: white; border-radius: var(--radius-xl); padding: 30px; display: flex; align-items: center; box-shadow: var(--shadow-md); position: relative; overflow: hidden;">
                    <div class="stat-icon"
                        style="background: rgba(255, 107, 107, 0.1); width: 70px; height: 70px; border-radius: 20px; font-size: 2.5rem; display: flex; align-items: center; justify-content: center; margin-right: 20px;">
                        📖</div>
                    <div class="stat-content">
                        <div class="stat-value" id="modulesCount"
                            style="font-size: 2.8rem; font-weight: 800; background: var(--gradient-danger); -webkit-background-clip: text; -webkit-text-fill-color: transparent; border: none;">
                            0</div>
                        <div class="stat-label"
                            style="font-weight: 600; color: #718096; text-transform: uppercase; font-size: 0.8rem; letter-spacing: 1px;">
                            Modul Tersedia</div>
                    </div>
                </div>
            </div>

            <div
                style="display: grid; grid-template-columns: repeat(auto-fit, minmax(400px, 1fr)); gap: 25px; margin-top: 25px;">
                <!-- Today's Schedule Widget -->
                <div class="card animate__animated animate__fadeInLeft">
                    <div class="card-header">
                        <h3 class="card-title">📅 Jadual Bulan Ini</h3>
                        <a href="#" onclick="switchTab(event, 'schedule')" class="btn btn-sm btn-primary">Lihat
                            Semua</a>
                    </div>
                    <div class="card-body" id="todayScheduleWidget">
                        <p class="text-center text-muted">Memuatkan...</p>
                    </div>
                </div>

                <!-- Recent Announcements Widget -->
                <div class="card animate__animated animate__fadeInRight">
                    <div class="card-header">
                        <h3 class="card-title">📢 Pengumuman Terkini</h3>
                        <a href="#" onclick="switchTab(event, 'announcements')" class="btn btn-sm btn-primary">Lihat
                            Semua</a>
                    </div>
                    <div class="card-body" id="recentAnnouncementsWidget">
                        <p class="text-center text-muted">Memuatkan...</p>
                    </div>
                </div>

                <!-- Tutor & Sokongan -->
                <div class="card animate__animated animate__fadeInUp" style="animation-delay: 0.1s;">
                    <div class="card-header">
                        <h3 class="card-title">👨‍🏫 Tutor & Sokongan</h3>
                    </div>
                    <div class="card-body" id="studentContactsWidget">
                        <p class="text-center text-muted">Memuatkan...</p>
                    </div>
                    <div class="card-footer" style="padding: 12px 20px; background: #f8fafc;">
                        <small style="color: #64748b;">
                            ℹ️ Jika perlukan bantuan, sboleh berhubung dengan Tutor anda.
                        </small>
                    </div>
                </div>

                <!-- My Info Card -->
                <div class="card animate__animated animate__fadeInUp">
                    <div class="card-header">
                        <h3 class="card-title">📋 Maklumat Saya</h3>
                    </div>
                    <div class="card-body">
                        <div class="info-row">
                            <span class="info-label">Nama Penuh</span>
                            <span class="info-value"><?php echo htmlspecialchars($studentName); ?></span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">Umur</span>
                            <span class="info-value"><?php echo htmlspecialchars($studentAge); ?> tahun</span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">Tahap</span>
                            <span class="info-value"><?php echo htmlspecialchars($studentLevel); ?></span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">Tahun/Tingkatan</span>
                            <span class="info-value"><?php echo htmlspecialchars($studentGrade); ?></span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">Nama Pengguna</span>
                            <span
                                class="info-value">@<?php echo htmlspecialchars($student['username'] ?? '-'); ?></span>
                        </div>
                    </div>
                </div>

                <!-- My Subjects Card -->
                <div class="card animate__animated animate__fadeInUp" style="animation-delay: 0.1s;">
                    <div class="card-header">
                        <h3 class="card-title">📚 Subjek Saya</h3>
                    </div>
                    <div class="card-body">
                        <?php if (!empty($studentSubjects)): ?>
                            <div style="display: flex; flex-wrap: wrap; gap: 10px;">
                                <?php foreach ($studentSubjects as $subject): ?>
                                    <span class="subject-tag"><?php echo htmlspecialchars($subject); ?></span>
                                <?php endforeach; ?>
                            </div>
                        <?php else: ?>
                            <p class="text-muted text-center">Tiada subjek didaftarkan</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- TAB 2: SCHEDULE -->
        <div id="schedule" class="tab-content">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">📅 Jadual Waktu Kelas</h3>
                    <div style="display: flex; gap: 10px;">
                        <select class="form-control form-select" id="scheduleSubjectFilter" onchange="filterSchedule()"
                            style="width: auto;">
                            <option value="all">Semua Subjek</option>
                            <?php foreach ($studentSubjects as $subject): ?>
                                <option value="<?php echo htmlspecialchars($subject); ?>">
                                    <?php echo htmlspecialchars($subject); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <button class="btn btn-primary btn-sm" onclick="loadStudentSchedule()">
                            <i class="fas fa-sync"></i> Muat Semula
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <div id="studentSchedule">
                        <p class="text-center text-muted">Memuatkan...</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- TAB 3: MODULES -->
        <div id="modules" class="tab-content">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">📚 Modul Pembelajaran Saya</h3>
                    <div style="display: flex; gap: 10px;">
                        <input type="text" class="form-control" id="moduleSearch" placeholder="🔍 Cari modul..."
                            oninput="filterModules()" style="width: 250px;">
                        <select class="form-control form-select" id="moduleSubjectFilter" onchange="filterModules()"
                            style="width: auto;">
                            <option value="all">Semua Subjek</option>
                            <?php foreach ($studentSubjects as $subject): ?>
                                <option value="<?php echo htmlspecialchars($subject); ?>">
                                    <?php echo htmlspecialchars($subject); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="card-body">
                    <div id="studentModules" class="module-grid">
                        <p class="text-center text-muted">Memuatkan...</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- TAB 4: CLASSES -->
        <div id="classes" class="tab-content">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">🏫 Kelas Online Saya</h3>
                    <div style="display: flex; gap: 10px;">
                        <select class="form-control form-select" id="classSubjectFilter" onchange="filterClasses()"
                            style="width: auto;">
                            <option value="all">Semua Subjek</option>
                            <?php foreach ($studentSubjects as $subject): ?>
                                <option value="<?php echo htmlspecialchars($subject); ?>">
                                    <?php echo htmlspecialchars($subject); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <select class="form-control form-select" id="classStatusFilter" onchange="filterClasses()"
                            style="width: auto;">
                            <option value="upcoming">Akan Datang</option>
                            <option value="past">Lepas</option>
                            <option value="all">Semua</option>
                        </select>
                    </div>
                </div>
                <div class="card-body">
                    <div id="studentClasses">
                        <div id="upcomingClassesList">
                            <p class="text-center text-muted">Memuatkan...</p>
                        </div>
                        <div id="pastClassesList" style="margin-top: 20px;"></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- TAB 5: FORUM -->
        <div id="forum" class="tab-content">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">💬 Forum Perbincangan</h3>
                    <div style="display: flex; gap: 10px;">
                        <input type="text" class="form-control" id="forumSearch" placeholder="🔍 Cari forum..."
                            oninput="filterForum()" style="width: 250px;">
                        <select class="form-control form-select" id="forumSubjectFilter" onchange="filterForum()"
                            style="width: auto;">
                            <option value="all">Semua Subjek</option>
                            <?php foreach ($studentSubjects as $subject): ?>
                                <option value="<?php echo htmlspecialchars($subject); ?>">
                                    <?php echo htmlspecialchars($subject); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="card-body">
                    <div id="studentForum" style="display: flex; flex-direction: column; gap: 15px;">
                        <p class="text-center text-muted">Memuatkan...</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- TAB 6: ANNOUNCEMENTS -->
        <div id="announcements" class="tab-content">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">📢 Pengumuman</h3>
                    <div style="display: flex; gap: 10px;">
                        <select class="form-control form-select" id="announcementPriorityFilter"
                            onchange="filterAnnouncements()" style="width: auto;">
                            <option value="all">Semua Prioriti</option>
                            <option value="Urgent">Urgent</option>
                            <option value="Penting">Penting</option>
                            <option value="Normal">Normal</option>
                        </select>
                    </div>
                </div>
                <div class="card-body">
                    <div id="studentAnnouncements" style="display: flex; flex-direction: column; gap: 15px;">
                        <p class="text-center text-muted">Memuatkan...</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- TAB 7: PROFILE -->
        <div id="profile" class="tab-content">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">👤 Profil Saya</h3>
                </div>
                <div class="card-body">
                    <div
                        style="display: flex; align-items: center; gap: 20px; margin-bottom: 30px; padding: 20px; background: linear-gradient(135deg, var(--primary-color), var(--primary-dark)); border-radius: 15px; color: white;">
                        <div style="font-size: 5rem;"><?php echo htmlspecialchars($studentEmoji); ?></div>
                        <div>
                            <h3 style="color: white; margin: 0;"><?php echo htmlspecialchars($studentName); ?></h3>
                            <p style="margin: 5px 0 0 0; opacity: 0.9;">
                                @<?php echo htmlspecialchars($student['username'] ?? ''); ?></p>
                        </div>
                    </div>

                    <form id="profileForm" onsubmit="updateProfile(event)">
                        <input type="hidden" name="profile_emoji" id="selectedEmoji"
                            value="<?php echo htmlspecialchars($studentEmoji); ?>">

                        <div class="form-group" style="margin-bottom: 20px;">
                            <label class="form-label">Pilih Emoji Profil</label>
                            <div class="emoji-picker" id="studentEmojiPicker">
                                <?php
                                $emojis = ['👨‍🎓', '👩‍🎓', '🧑‍🎓', '👦', '👧', '🧒', '😀', '😎', '😊', '🤓', '⭐', '🌟', '💫', '✨', '🎯'];
                                foreach ($emojis as $emoji) {
                                    $selected = $studentEmoji === $emoji ? 'selected' : '';
                                    echo '<div class="emoji-option ' . $selected . '" data-emoji="' . $emoji . '">' . $emoji . '</div>';
                                }
                                ?>
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary mt-4 w-100">Kemas Kini Profil</button>
                    </form>
                </div>
            </div>
        </div>
    </main>
</div>

<!-- Mobile Bottom Navigation (iPhone Modern App Style) -->
<nav class="mobile-bottom-nav">
    <a href="#" onclick="switchTab(event, 'dashboard')" class="nav-tab-item active" id="mob-nav-dashboard">
        <span class="nav-icon">🏠</span>
        <span>Dashboard</span>
    </a>
    <a href="#" onclick="switchTab(event, 'schedule')" class="nav-tab-item" id="mob-nav-schedule">
        <span class="nav-icon">📅</span>
        <span>Jadual</span>
    </a>
    <a href="#" onclick="switchTab(event, 'modules')" class="nav-tab-item" id="mob-nav-modules">
        <span class="nav-icon">📚</span>
        <span>Modul</span>
    </a>
    <a href="#" onclick="switchTab(event, 'forum')" class="nav-tab-item" id="mob-nav-forum">
        <span class="nav-icon">💬</span>
        <span>Forum</span>
    </a>
    <a href="#" onclick="switchTab(event, 'profile')" class="nav-tab-item" id="mob-nav-profile">
        <span class="nav-icon">👤</span>
        <span>Profil</span>
    </a>
    <a href="#" onclick="event.preventDefault(); event.stopPropagation(); toggleMobileMenu()" class="nav-tab-item">
        <span class="nav-icon">☰</span>
        <span>Menu</span>
    </a>
</nav>

<!-- Announcement Detail Modal -->
<div class="modal-overlay" id="announcementDetailModal">
    <div class="modal" style="max-width: 700px;">
        <div class="modal-header">
            <h3 class="modal-title" id="announcementDetailTitle">📢 Pengumuman</h3>
            <button class="modal-close" onclick="closeModal('announcementDetailModal')">×</button>
        </div>
        <div class="modal-body">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                <div>
                    <span class="badge badge-primary" id="announcementDetailCategory">-</span>
                    <span id="announcementDetailPriority">-</span>
                </div>
                <small class="text-muted" id="announcementDetailDate">-</small>
            </div>

            <div style="margin-bottom: 15px;">
                <strong>Guru:</strong> <span id="announcementDetailTeacher">-</span>
            </div>

            <div class="form-group">
                <div id="announcementDetailContent"
                    style="background: #f8f9fa; padding: 20px; border-radius: 10px; white-space: pre-wrap;">-</div>
            </div>

            <div id="announcementDetailAttachment" style="margin-top: 15px;"></div>

            <div style="margin-top: 20px;">
                <button type="button" class="btn btn-secondary" style="width: 100%;"
                    onclick="closeModal('announcementDetailModal')">Tutup</button>
            </div>
        </div>
    </div>
</div>

<!-- Module Detail Modal -->
<div class="modal-overlay" id="moduleDetailModal">
    <div class="modal" style="max-width: 700px;">
        <div class="modal-header">
            <h3 class="modal-title" id="moduleDetailTitle">📚 Modul</h3>
            <button class="modal-close" onclick="closeModal('moduleDetailModal')">×</button>
        </div>
        <div class="modal-body">
            <div style="margin-bottom: 15px;">
                <span class="badge badge-primary" id="moduleDetailSubject">-</span>
                <span class="badge badge-secondary" id="moduleDetailTeacher">-</span>
            </div>

            <div class="form-group">
                <label class="form-label"><strong>Penerangan:</strong></label>
                <p id="moduleDetailDescription" style="background: #f8f9fa; padding: 15px; border-radius: 8px;">-
                </p>
            </div>

            <div class="form-group">
                <label class="form-label"><strong>Kandungan/Nota:</strong></label>
                <div id="moduleDetailContent"
                    style="background: #f8f9fa; padding: 15px; border-radius: 8px; max-height: 300px; overflow-y: auto; white-space: pre-wrap;">
                    -</div>
            </div>

            <div class="form-group">
                <label class="form-label"><strong>Pautan & Sumber:</strong></label>
                <div id="moduleDetailLinks"></div>
            </div>

            <div style="margin-top: 20px;">
                <button type="button" class="btn btn-secondary" style="width: 100%;"
                    onclick="closeModal('moduleDetailModal')">Tutup</button>
            </div>
        </div>
    </div>
</div>

<!-- Forum Detail Modal -->
<div class="modal-overlay" id="forumDetailModal">
    <div class="modal" style="max-width: 800px;">
        <div class="modal-header">
            <h3 class="modal-title" id="forumDetailTitle">💬 Forum</h3>
            <button class="modal-close" onclick="closeModal('forumDetailModal')">×</button>
        </div>
        <div class="modal-body">
            <!-- Forum Post -->
            <div style="background: #f8f9fa; padding: 20px; border-radius: 10px; margin-bottom: 20px;">
                <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 10px;">
                    <div>
                        <span class="badge badge-primary" id="forumDetailSubject">-</span>
                        <span class="badge badge-secondary" id="forumDetailTeacher">-</span>
                    </div>
                    <small class="text-muted" id="forumDetailDate">-</small>
                </div>
                <div id="forumDetailContent" style="margin-top: 15px; white-space: pre-wrap;">-</div>
                <div id="forumDetailAttachment" style="margin-top: 15px;"></div>
                <div id="forumDetailLink" style="margin-top: 10px;"></div>
            </div>

            <!-- Replies Section -->
            <div style="margin-bottom: 20px;">
                <h5 style="margin-bottom: 15px;">💬 Balasan (<span id="forumReplyCount">0</span>)</h5>
                <div id="forumRepliesList" style="max-height: 300px; overflow-y: auto;">
                    <p class="text-center text-muted">Tiada balasan</p>
                </div>
            </div>

            <!-- Reply Form -->
            <div style="background: #f8f9fa; padding: 15px; border-radius: 10px;">
                <h5 style="margin-bottom: 10px;">✍️ Tambah Balasan</h5>
                <form id="forumReplyForm" onsubmit="submitForumReply(event)">
                    <input type="hidden" id="replyForumId" value="">

                    <div style="margin-bottom: 10px;">
                        <div id="studentFilePreview"
                            style="display:none; background: #eef2ff; padding: 8px 12px; border-radius: 8px; margin-bottom: 8px; font-size: 0.85rem; border: 1px dashed var(--primary-color);">
                            <div style="display: flex; justify-content: space-between; align-items: center;">
                                <span
                                    style="display: flex; align-items: center; gap: 5px; color: var(--primary-color); font-weight: 600;">
                                    <i class="fas fa-file"></i> <span id="studentFileName">Filename</span>
                                </span>
                                <button type="button" onclick="clearStudentFile()"
                                    style="border:none; background:none; color: #ef4444; cursor: pointer;">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                        </div>
                        <label for="studentReplyAttachment" class="btn btn-sm btn-light border"
                            style="cursor: pointer; border-radius: 20px; padding: 5px 15px; font-size: 0.85rem; color: #666;">
                            <i class="fas fa-paperclip color-primary"></i> Lampirkan Gambar/PDF
                        </label>
                        <input type="file" id="studentReplyAttachment" style="display: none;"
                            accept="image/jpeg,image/png,application/pdf" onchange="previewStudentFile()">
                    </div>

                    <div class="form-group">
                        <textarea class="form-control" id="replyContent" rows="3" placeholder="Tulis balasan anda..."
                            required></textarea>
                    </div>
                    <button type="submit" class="btn btn-primary" style="width: 100%;">📤 Hantar Balasan</button>
                </form>
            </div>

            <div style="margin-top: 15px;">
                <button type="button" class="btn btn-secondary" style="width: 100%;"
                    onclick="closeModal('forumDetailModal')">Tutup</button>
            </div>
        </div>
    </div>
</div>

<!-- Scripts -->
<script src="../js/main.js"></script>
<script src="../js/student.js"></script>
<script>
    // Mobile Menu Toggle
    function toggleMobileMenu() {
        const sidebar = document.getElementById('sidebar');
        const overlay = document.getElementById('sidebarOverlay');

        if (!sidebar || !overlay) return;

        const isOpen = sidebar.classList.contains('open');

        if (isOpen) {
            sidebar.classList.remove('open');
            overlay.classList.remove('show');
            document.body.style.overflow = '';
        } else {
            sidebar.classList.add('open');
            overlay.classList.add('show');
            document.body.style.overflow = 'hidden';
        }
    }

    function closeMobileMenu() {
        const sidebar = document.getElementById('sidebar');
        const overlay = document.getElementById('sidebarOverlay');
        if (sidebar) sidebar.classList.remove('open');
        if (overlay) overlay.classList.remove('show');
        document.body.style.overflow = '';
    }

    function updateClock() {
        const now = new Date();
        const days = ['Ahad', 'Isnin', 'Selasa', 'Rabu', 'Khamis', 'Jumaat', 'Sabtu'];
        const months = ['Januari', 'Februari', 'Mac', 'April', 'Mei', 'Jun', 'Julai', 'Ogos', 'September', 'Oktober', 'November', 'Disember'];

        const hours24 = now.getHours();
        const minutes = now.getMinutes().toString().padStart(2, '0');
        const seconds = now.getSeconds().toString().padStart(2, '0');

        let suffix = 'Pagi';
        if (hours24 >= 19) suffix = 'Malam';
        else if (hours24 >= 14) suffix = 'Petang';
        else if (hours24 >= 12) suffix = 'Tengah Hari';
        else suffix = 'Pagi';

        const hours12 = (hours24 % 12) || 12;
        const timeStr = hours12 + ':' + minutes + ':' + seconds + ' ' + suffix;
        const dayName = days[now.getDay()];
        const dateStr = now.getDate() + ' ' + months[now.getMonth()] + ' ' + now.getFullYear();

        const clockEl = document.getElementById('realtimeClock');
        if (clockEl) clockEl.textContent = timeStr;
        const dateEl = document.getElementById('realtimeDate');
        if (dateEl) dateEl.textContent = dayName + ', ' + dateStr;

        // Update Wow Banner elements
        const bannerDayEl = document.getElementById('bannerDay');
        const bannerDateEl = document.getElementById('bannerDate');
        const bannerTimeEl = document.getElementById('bannerTime');

        if (bannerDayEl) bannerDayEl.textContent = dayName;
        if (bannerDateEl) bannerDateEl.textContent = dateStr;
        if (bannerTimeEl) bannerTimeEl.textContent = timeStr;
    }

    function updateBannerTime() {
        updateClock();
    }


    function switchTab(event, tabId) {
        if (event) event.preventDefault();
        document.querySelectorAll('.tab-content').forEach(t => t.classList.remove('active'));
        document.querySelectorAll('.nav-item').forEach(n => n.classList.remove('active'));
        const activeTab = document.getElementById(tabId);
        const activeNav = document.getElementById('nav-' + tabId);
        if (activeTab) activeTab.classList.add('active');
        if (activeNav) activeNav.classList.add('active');

        // Sync data
        if (tabId === 'dashboard' && typeof loadDashboardData === 'function') {
            loadDashboardData();
        } else if (typeof window['loadStudent' + tabId.charAt(0).toUpperCase() + tabId.slice(1)] === 'function') {
            window['loadStudent' + tabId.charAt(0).toUpperCase() + tabId.slice(1)]();
        }
        // Update mobile bottom nav active state
        document.querySelectorAll('.nav-tab-item').forEach(el => el.classList.remove('active'));
        const mobNav = document.getElementById('mob-nav-' + tabId);
        if (mobNav) mobNav.classList.add('active');

        localStorage.setItem('studentActiveTab', tabId);
    }

    document.addEventListener('DOMContentLoaded', () => {
        initializeEmojiPicker();
        updateClock();
        updateBannerTime();
        setInterval(updateClock, 1000);
        const savedTab = localStorage.getItem('studentActiveTab') || 'dashboard';
        switchTab(null, savedTab);

        // Trigger CountUp for subjects count (PHP variable used directly)
        const subjectEl = document.getElementById('studentSubjectCount');
        if (subjectEl) {
            const subjectVal = parseInt(subjectEl.textContent) || 0;
            animateValue('studentSubjectCount', 0, subjectVal, 1500);
        }

        // Initialize Notifications
        initNotifications();
        setInterval(initNotifications, 30000); // Check every 30s
    });

    // ========== NOTIFICATION LOGIC ==========
    function toggleNotifDropdown(event) {
        if (event) event.stopPropagation();
        const dropdown = document.getElementById('notifDropdown');
        dropdown.classList.toggle('show');
    }

    document.addEventListener('click', () => {
        const dropdown = document.getElementById('notifDropdown');
        if (dropdown) dropdown.classList.remove('show');
    });

    function initNotifications() {
        fetch('../api.php?action=get_notifications')
            .then(res => res.json())
            .then(result => {
                const badge = document.getElementById('notifBadge');
                const list = document.getElementById('notifList');
                if (!result.success || !result.notifications) return;

                const unread = result.notifications.filter(n => n.is_read === 'No');
                if (unread.length > 0) {
                    badge.textContent = unread.length;
                    badge.classList.add('show');
                    // Shake bell if new unread
                    const lastCount = parseInt(localStorage.getItem('lastNotifCount') || '0');
                    if (unread.length > lastCount) {
                        document.getElementById('notifBtn').style.animation = 'bellShake 0.5s ease-in-out 3';
                        // Audio notification could be added here
                    }
                    localStorage.setItem('lastNotifCount', unread.length);
                } else {
                    badge.classList.remove('show');
                }

                if (result.notifications.length > 0) {
                    let html = '';
                    result.notifications.forEach(n => {
                        const icon = n.type === 'announcement' ? '📢' : (n.type === 'module' ? '📚' : (n.type === 'forum' ? '💬' : (n.type === 'schedule' ? '📅' : 'ℹ️')));
                        const iconClass = 'icon-' + (n.type || 'info');
                        const isUnread = n.is_read === 'No' ? 'unread' : '';

                        html += `
                            <div class="notification-item ${isUnread}" onclick="handleNotifClick(${n.id}, '${n.type}')">
                                <div class="notification-icon ${iconClass}">${icon}</div>
                                <div class="notification-info">
                                    <div class="notif-title">${n.title}</div>
                                    <div class="notif-msg">${n.message}</div>
                                    <div class="notif-time">${formatDateTime(n.created_at)}</div>
                                </div>
                            </div>
                        `;
                    });
                    list.innerHTML = html;
                } else {
                    list.innerHTML = '<p class="text-center text-muted p-4">Tiada notifikasi</p>';
                }
            });
    }

    function handleNotifClick(id, type) {
        const formData = new FormData();
        formData.append('action', 'mark_notification_read');
        formData.append('id', id);
        fetch('../api.php', { method: 'POST', body: formData }).then(() => {
            initNotifications();
            if (type === 'announcement') switchTab(null, 'announcements');
            else if (type === 'module') switchTab(null, 'modules');
            else if (type === 'forum') switchTab(null, 'forum');
            else if (type === 'schedule') switchTab(null, 'schedule');
        });
    }

    function markAllAsRead() {
        const formData = new FormData();
        formData.append('action', 'mark_notification_read');
        formData.append('id', '0'); // 0 means all for this user
        fetch('../api.php', { method: 'POST', body: formData }).then(() => initNotifications());
    }

    function deleteAllNotifications() {
        Swal.fire({
            title: 'Padam Semua Notifikasi?',
            text: 'Adakah anda pasti mahu memadam semua notifikasi? Tindakan ini tidak boleh dipadamkan.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Ya, Padam Semua',
            cancelButtonText: 'Batal',
            borderRadius: '15px',
            reverseButtons: true,
            focusCancel: true
        }).then((result) => {
            if (result.isConfirmed) {
                const formData = new FormData();
                formData.append('action', 'delete_all_notifications');
                fetch('../api.php', { method: 'POST', body: formData })
                    .then(response => response.json())
                    .then(result => {
                        if (result.success) {
                            Swal.fire({
                                title: 'Berjaya!',
                                text: 'Semua notifikasi telah dipadam',
                                icon: 'success',
                                confirmButtonColor: '#667eea',
                                borderRadius: '15px'
                            });
                            initNotifications();
                        } else {
                            Swal.fire({
                                title: 'Ralat!',
                                text: 'Gagal memadam notifikasi: ' + result.message,
                                icon: 'error',
                                confirmButtonColor: '#667eea',
                                borderRadius: '15px'
                            });
                        }
                    })
                    .catch(error => {
                        Swal.fire({
                            title: 'Ralat Sambungan!',
                            text: 'Tidak dapat menghubungi server',
                            icon: 'error',
                            confirmButtonColor: '#667eea',
                            borderRadius: '15px'
                        });
                    });
            }
        });
    }
</script>
</body>

</html>
