<?php
/**
 * Teacher Dashboard - TutorKita System
 * Location: teacher/index.php
 */

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

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

// Betulkan path database (keluar 1 folder sahaja)
$db_path = dirname(__DIR__) . '/db.php';
require_once $db_path;

// Check teacher session
if (!isset($_SESSION['user_type']) || $_SESSION['user_type'] !== 'teacher') {
    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) {
}

// Get teacher info
$teacher = [];
$portalName = 'TutorKita';
$portalTagline = 'Platform Pembelajaran Terbaik';
$portalLogo = '';
$portalFavicon = '';
$themeColor = '#667eea';

try {
    // Get admin settings for portal logo and favicon
    $stmt = $pdo->prepare("SELECT portal_logo, portal_favicon, theme_color FROM admin WHERE id = 1");
    $stmt->execute();
    $adminSettings = $stmt->fetch();
    if ($adminSettings) {
        $portalLogo = $adminSettings['portal_logo'] ?: '';
        $portalFavicon = $adminSettings['portal_favicon'] ?: '';
        $themeColor = $adminSettings['theme_color'] ?: '#667eea';
    }

    $stmt = $pdo->prepare("SELECT * FROM teachers WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $teacher = $stmt->fetch() ?: [];

    // FIXED: Properly decode teacher subjects from JSON format ["Sejarah","Perakaunan"]
    $teacherSubjectsRaw = $teacher['subjects'] ?? '';

    if (!empty($teacherSubjectsRaw)) {
        // Try to decode as JSON array
        $teacherSubjects = json_decode($teacherSubjectsRaw, true);

        // If JSON decode fails or result is not an array, try as comma-separated string
        if (json_last_error() !== JSON_ERROR_NONE || !is_array($teacherSubjects) || empty($teacherSubjects)) {
            // Try comma-separated format
            $teacherSubjects = array_map('trim', explode(',', $teacherSubjectsRaw));
        }
    } else {
        // If subjects column is empty, get subjects from subjects table
        $stmt = $pdo->query("SELECT DISTINCT subject_name FROM subjects ORDER BY subject_name");
        $allSubjects = $stmt->fetchAll(PDO::FETCH_COLUMN);
        $teacherSubjects = $allSubjects ?: [];
    }

    // Ensure teacherSubjects is always an array
    if (!is_array($teacherSubjects)) {
        $teacherSubjects = [];
    }

    $subjectsDisplay = !empty($teacherSubjects) ? implode(', ', $teacherSubjects) : 'Tiada subjek';

    // FIXED: Use students table directly for accurate count
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM students WHERE status = 'Active'");
    $stmt->execute();
    $studentCount = $stmt->fetchColumn() ?: 0;
} catch (Exception $e) {
    $teacher = [];
    $teacherSubjects = [];
    $subjectsDisplay = 'Tiada subjek';
    $studentCount = 0;
}

$teacherName = $_SESSION['full_name'] ?? 'Guru';
$teacherEmoji = $teacher['profile_emoji'] ?? '👨‍🏫';
$teacherGradeLevel = $teacher['grade_level'] ?? '';
$teacherEducationLevel = $teacher['education_level'] ?? '';
$teacherStatus = $teacher['status'] ?? 'Active';

// Check if teacher is inactive
if ($teacherStatus !== 'Active') {
    session_destroy();
    header('Location: ../index.php?error=deactivated');
    exit;
}
?>
<!DOCTYPE html>
<html lang="ms">

<head>
    <meta charset="UTF-8">
    <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="theme-color" content="<?php echo htmlspecialchars($themeColor); ?>">
    <title>Dashboard Guru - <?php echo htmlspecialchars($portalName); ?></title>

    <!-- ============================================
         CDN LINKS - BOOTSTRAP, SWEETALERT2, ANIMATE.CSS
         ============================================ -->
    <!-- Bootstrap 5 CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">

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

    <!-- SweetAlert2 Theme & Script -->
    <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>

    <!-- HTML2PDF for OPR Export -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>

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

    <!-- Custom Styles -->
    <link rel="stylesheet" href="../css/style.css">
    <!-- Mobile-First Premium UI -->
    <link rel="stylesheet" href="../css/mobile-premium.css">

    <style>
        :root {
            --primary-color:
                <?php echo $themeColor; ?>
            ;
        }

        /* ============================================
           ANIMATIONS & MICRO-INTERACTIONS
           ============================================ */

        /* Page Load Animation */
        .dashboard-layout {
            animation: fadeInUp 0.6s ease-out;
        }

        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* Sidebar Animation */
        .sidebar {
            animation: slideInLeft 0.5s ease-out;
        }

        @keyframes slideInLeft {
            from {
                opacity: 0;
                transform: translateX(-30px);
            }

            to {
                opacity: 1;
                transform: translateX(0);
            }
        }

        /* Main Content Animation */
        .main-content {
            animation: slideInRight 0.5s ease-out 0.1s both;
        }

        @keyframes slideInRight {
            from {
                opacity: 0;
                transform: translateX(30px);
            }

            to {
                opacity: 1;
                transform: translateX(0);
            }
        }

        /* Stats Cards Stagger Animation */
        .stats-grid {
            animation: fadeInUp 0.6s ease-out 0.3s both;
        }

        .stats-grid .stat-card {
            animation: scaleIn 0.5s ease-out both;
        }

        .stats-grid .stat-card:nth-child(1) {
            animation-delay: 0.4s;
        }

        .stats-grid .stat-card:nth-child(2) {
            animation-delay: 0.5s;
        }

        .stats-grid .stat-card:nth-child(3) {
            animation-delay: 0.6s;
        }

        .stats-grid .stat-card:nth-child(4) {
            animation-delay: 0.7s;
        }

        @keyframes scaleIn {
            from {
                opacity: 0;
                transform: scale(0.8);
            }

            to {
                opacity: 1;
                transform: scale(1);
            }
        }

        /* Card Hover Effects */
        .card {
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            transform: translateY(0);
        }

        .card:hover {
            transform: translateY(-4px);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
        }

        /* Button Animations */
        .btn {
            transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
            overflow: hidden;
        }

        .btn:hover {
            transform: translateY(-2px);
        }

        .btn:active {
            transform: translateY(0);
            transition-duration: 0.1s;
        }

        /* Button Ripple Effect */
        .btn::after {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            background: rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            transform: translate(-50%, -50%);
            transition: width 0.4s ease, height 0.4s ease, opacity 0.4s ease;
            opacity: 0;
        }

        .btn:active::after {
            width: 300px;
            height: 300px;
            opacity: 1;
            transition: width 0s, height 0s, opacity 0s;
        }

        /* Tab Animation */
        .tab-content {
            display: none;
            opacity: 0;
            transform: translateY(20px);
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
        }

        .tab-content.active {
            display: block;
            opacity: 1;
            transform: translateY(0);
        }

        /* Navigation Item Hover */
        .nav-item {
            transition: all 0.2s ease;
            position: relative;
            overflow: hidden;
        }

        .nav-item::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
            transition: left 0.5s ease;
        }

        .nav-item:hover::before {
            left: 100%;
        }

        .nav-item.active {
            animation: pulse 2s infinite;
        }

        @keyframes pulse {

            0%,
            100% {
                transform: scale(1);
            }

            50% {
                transform: scale(1.02);
            }
        }

        /* Table Row Animation */
        .table tbody tr {
            animation: fadeInUp 0.4s ease-out both;
        }

        .table tbody tr:nth-child(1) {
            animation-delay: 0.1s;
        }

        .table tbody tr:nth-child(2) {
            animation-delay: 0.15s;
        }

        .table tbody tr:nth-child(3) {
            animation-delay: 0.2s;
        }

        .table tbody tr:nth-child(4) {
            animation-delay: 0.25s;
        }

        .table tbody tr:nth-child(5) {
            animation-delay: 0.3s;
        }

        .table tbody tr:nth-child(6) {
            animation-delay: 0.35s;
        }

        .table tbody tr:nth-child(7) {
            animation-delay: 0.4s;
        }

        .table tbody tr:nth-child(8) {
            animation-delay: 0.45s;
        }

        .table tbody tr:nth-child(9) {
            animation-delay: 0.5s;
        }

        .table tbody tr:nth-child(10) {
            animation-delay: 0.55s;
        }

        /* Loading Animation */
        .loading-spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(102, 126, 234, 0.3);
            border-radius: 50%;
            border-top-color: var(--primary-color);
            animation: spin 1s ease-in-out infinite;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        /* Badge Animation */
        .badge {
            animation: bounceIn 0.5s ease-out;
        }

        @keyframes bounceIn {
            0% {
                opacity: 0;
                transform: scale(0.3);
            }

            50% {
                opacity: 1;
                transform: scale(1.05);
            }

            70% {
                transform: scale(0.9);
            }

            100% {
                opacity: 1;
                transform: scale(1);
            }
        }

        /* Notification Bell Animation */
        .notification-bell-btn {
            transition: all 0.3s ease;
            position: relative;
        }

        .notification-bell-btn:hover {
            transform: scale(1.1);
        }

        .notification-bell-pulse {
            position: absolute;
            top: -2px;
            right: -2px;
            width: 12px;
            height: 12px;
            background: #ff4757;
            border-radius: 50%;
            animation: pulse-red 2s infinite;
        }

        @keyframes pulse-red {

            0%,
            100% {
                transform: scale(1);
                opacity: 1;
            }

            50% {
                transform: scale(1.2);
                opacity: 0.7;
            }
        }

        /* Form Input Focus Animation */

        /* Form Input Focus Animation */
        .form-control {
            transition: all 0.3s ease;
            position: relative;
        }

        .form-control:focus {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.15);
        }

        /* Emoji Picker Animation */
        .emoji-picker {
            animation: slideInUp 0.3s ease-out;
        }

        @keyframes slideInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .emoji-option {
            transition: all 0.2s ease;
        }

        .emoji-option:hover {
            transform: scale(1.2) rotate(5deg);
        }

        .emoji-option.selected {
            animation: selectedEmoji 0.5s ease-out;
        }

        @keyframes selectedEmoji {
            0% {
                transform: scale(1);
            }

            50% {
                transform: scale(1.3) rotate(10deg);
            }

            100% {
                transform: scale(1.1) rotate(0deg);
            }
        }

        /* Progress Bar Animation */
        .progress-bar {
            animation: progressFill 1s ease-out;
        }

        @keyframes progressFill {
            from {
                width: 0%;
            }

            to {
                width: var(--progress-width);
            }
        }

        /* Floating Action Button */
        .fab {
            position: fixed;
            bottom: 30px;
            right: 30px;
            width: 60px;
            height: 60px;
            background: var(--primary-color);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
            transition: all 0.3s ease;
            z-index: 1000;
        }

        .fab:hover {
            transform: scale(1.1);
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.4);
        }

        /* Mobile Menu Animation */
        .mobile-menu-toggle {
            transition: all 0.3s ease;
        }

        .mobile-menu-toggle.active span:nth-child(1) {
            transform: rotate(45deg) translate(5px, 5px);
        }

        .mobile-menu-toggle.active span:nth-child(2) {
            opacity: 0;
        }

        .mobile-menu-toggle.active span:nth-child(3) {
            transform: rotate(-45deg) translate(7px, -6px);
        }

        .sidebar-overlay {
            animation: fadeIn 0.3s ease-out;
        }

        .sidebar.open {
            animation: slideInLeft 0.3s ease-out;
        }

        /* Quick Actions Grid Animation */
        .quick-actions-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            animation: fadeInUp 0.6s ease-out 0.8s both;
        }

        .quick-actions-grid button {
            animation: scaleIn 0.4s ease-out both;
        }

        .quick-actions-grid button:nth-child(1) {
            animation-delay: 0.9s;
        }

        .quick-actions-grid button:nth-child(2) {
            animation-delay: 1.0s;
        }

        .quick-actions-grid button:nth-child(3) {
            animation-delay: 1.1s;
        }

        .quick-actions-grid button:nth-child(4) {
            animation-delay: 1.2s;
        }

        .quick-actions-grid button:nth-child(5) {
            animation-delay: 1.3s;
        }

        /* Dashboard Info Cards Animation */
        .dashboard-info-cards .card {
            animation: slideInUp 0.5s ease-out both;
        }

        .dashboard-info-cards .card:nth-child(1) {
            animation-delay: 1.0s;
        }

        .dashboard-info-cards .card:nth-child(2) {
            animation-delay: 1.1s;
        }

        .dashboard-info-cards .card:nth-child(3) {
            animation-delay: 1.2s;
        }

        /* Real-time Clock Animation */
        .realtime-clock {
            animation: glow 2s ease-in-out infinite alternate;
        }

        @keyframes glow {
            from {
                text-shadow: 0 0 5px rgba(102, 126, 234, 0.5);
            }

            to {
                text-shadow: 0 0 20px rgba(102, 126, 234, 0.8), 0 0 30px rgba(102, 126, 234, 0.6);
            }
        }

        /* Status Toggle Animation */
        .toggle-switch {
            transition: all 0.3s ease;
        }

        .toggle-switch.active {
            background: #28a745;
        }

        .toggle-slider {
            transition: all 0.3s ease;
        }

        .toggle-knob {
            transition: all 0.3s ease;
        }

        /* Alert Animation */
        .alert {
            animation: slideInDown 0.4s ease-out;
        }

        @keyframes slideInDown {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* Search Input Animation */
        .form-control:focus {
            animation: inputFocus 0.3s ease-out;
        }

        @keyframes inputFocus {
            0% {
                transform: scale(1);
            }

            50% {
                transform: scale(1.02);
            }

            100% {
                transform: scale(1);
            }
        }

        /* Reduced Motion Support */
        @media (prefers-reduced-motion: reduce) {

            *,
            *::before,
            *::after {
                animation-duration: 0.01ms !important;
                animation-iteration-count: 1 !important;
                transition-duration: 0.01ms !important;
            }
        }

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

        .realtime-date {
            color: var(--text-secondary);
            font-size: 0.9rem;
        }

        .page-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 25px;
        }

        /* Mobile UI - Hidden by default on Desktop */
        .mobile-header,
        .sidebar-overlay,
        .mobile-bottom-nav {
            display: none !important;
        }

        /* === TABLET BREAKPOINT (1024px) === */
        /* === PREMIUM MOBILE STYLE (1024px) === */
        @media (max-width: 1024px) {
            .mobile-header {
                display: flex !important;
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                height: calc(75px + env(safe-area-inset-top, 0));
                background: rgba(255, 255, 255, 0.85);
                backdrop-filter: blur(20px);
                -webkit-backdrop-filter: blur(20px);
                border-bottom: 1px solid rgba(0, 0, 0, 0.05);
                z-index: 1001;
                align-items: center;
                justify-content: space-between;
                padding: env(safe-area-inset-top, 0) 15px 0 15px;
                box-shadow: 0 2px 10px rgba(0, 0, 0, 0.02);
            }

            .sidebar {
                position: fixed;
                left: -280px;
                top: 0;
                bottom: 0;
                width: 280px;
                z-index: 3000;
                transition: left 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            }

            .sidebar.open {
                left: 0;
            }

            .sidebar-overlay {
                display: none;
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(15, 23, 42, 0.5);
                backdrop-filter: blur(4px);
                z-index: 1999;
            }

            .sidebar-overlay.active {
                display: block;
                animation: fadeIn 0.3s ease-out;
            }

            .main-content {
                margin-left: 0 !important;
                padding: calc(30px + env(safe-area-inset-top, 0)) 15px 120px 15px !important;
            }

            .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);
                -webkit-backdrop-filter: blur(20px);
                border: 1px solid rgba(255, 255, 255, 0.3);
                border-radius: 25px;
                z-index: 1000;
                justify-content: space-around;
                align-items: center;
                padding-bottom: 0;
                box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
                transition: all 0.3s ease;
            }

            .nav-tab-item {
                display: flex;
                flex-direction: column;
                align-items: center;
                gap: 4px;
                color: #94a3b8;
                font-size: 0.7rem;
                font-weight: 600;
                transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                flex: 1;
                text-decoration: none !important;
            }

            .sidebar-header {
                padding: 15px 10px !important;
            }

            .sidebar-logo img {
                width: 60px !important;
                height: 60px !important;
            }

            .sidebar-title {
                font-size: 1.1rem !important;
            }

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

            .nav-tab-item .nav-icon {
                font-size: 1.4rem;
                transition: transform 0.3s ease;
            }

            .nav-tab-item.active .nav-icon {
                transform: scale(1.15) translateY(-2px);
            }

            .page-header {
                flex-direction: column !important;
                align-items: flex-start !important;
                gap: 15px !important;
            }
        }

        flex-wrap: wrap;
        gap: 20px;
        }
    </style>
</head>

<body>

    <!-- Sidebar Overlay -->
    <div class="sidebar-overlay" id="sidebarOverlay" onclick="toggleMobileMenuV2()"></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 Guru</p>
            </div>

            <nav class="sidebar-nav">
                <a href="#" onclick="switchTabV2(event, 'dashboard'); closeMobileMenuV2();" class="nav-item active"
                    id="nav-dashboard">
                    <span class="nav-icon">📊</span> <span class="nav-text">Dashboard</span>
                </a>
                <a href="#"
                    onclick="switchTabV2(event, 'student-management'); loadStudentManagementData(); closeMobileMenuV2();"
                    class="nav-item" id="nav-student-management">
                    <span class="nav-icon">👨‍🎓</span> <span class="nav-text">Pengurusan Pelajar</span>
                </a>
                <a href="#" onclick="switchTabV2(event, 'forum'); closeMobileMenuV2();" class="nav-item" id="nav-forum">
                    <span class="nav-icon">💬</span> <span class="nav-text">Forum</span>
                </a>
                <a href="#" onclick="switchTabV2(event, 'bilik-tutor'); closeMobileMenuV2();" class="nav-item"
                    id="nav-bilik-tutor">
                    <span class="nav-icon">🏢</span> <span class="nav-text">Bilik Tutor</span>
                </a>
                <a href="#" onclick="switchTabV2(event, 'announcements'); closeMobileMenuV2();" class="nav-item"
                    id="nav-announcements">
                    <span class="nav-icon">📢</span> <span class="nav-text">Pengumuman</span>
                </a>
                <a href="#" onclick="switchTabV2(event, 'modules'); loadModulesV2(); closeMobileMenuV2();"
                    class="nav-item" id="nav-modules">
                    <span class="nav-icon">📚</span> <span class="nav-text">Modul</span>
                </a>
                <a href="#" onclick="switchTabV2(event, 'schedule'); closeMobileMenuV2();" class="nav-item"
                    id="nav-schedule">
                    <span class="nav-icon">📅</span> <span class="nav-text">Jadual</span>
                </a>
                <a href="#" onclick="switchTabV2(event, 'classrooms'); closeMobileMenuV2();" class="nav-item"
                    id="nav-classrooms">
                    <span class="nav-icon">🏫</span> <span class="nav-text">Kelas Online</span>
                </a>
                <a href="#" onclick="switchTabV2(event, 'opr'); closeMobileMenuV2();" class="nav-item" id="nav-opr">
                    <span class="nav-icon">📄</span> <span class="nav-text">OPR</span>
                </a>
                <a href="#" onclick="switchTabV2(event, 'settings'); closeMobileMenuV2();" class="nav-item"
                    id="nav-settings">
                    <span class="nav-icon">⚙️</span> <span class="nav-text">Tetapan</span>
                </a>
            </nav>

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

        <main class="main-content">

            <div class="page-header">
                <div style="flex: 1;">
                    <h1 class="page-title">Selamat sejahtera, Cikgu
                        <?php echo htmlspecialchars(explode(' ', $teacherName)[0]); ?>!
                    </h1>
                    <p class="page-subtitle">Subjek: <?php echo htmlspecialchars($subjectsDisplay); ?></p>
                </div>

                <div style="display: flex; align-items: center; gap: 20px;">
                    <div style="text-align: right;">
                        <div id="realtimeClock" class="realtime-clock">00:00:00</div>
                        <div id="realtimeDate" class="realtime-date">Mengira...</div>
                    </div>

                    <div class="notification-bell-container" style="position: relative;">
                        <button class="notification-bell-btn" id="notificationBellBtn"
                            onclick="toggleNotificationDropdown(event)">
                            <span class="notification-bell-icon">🔔</span>
                            <span id="notificationCount" class="notification-badge" style="display: none;">0</span>
                        </button>
                        <div class="notification-dropdown" id="notificationDropdown"
                            style="display: none; position: fixed; right: 20px; top: 80px; width: 380px; min-height: 200px; max-height: 450px; background: #ffffff; border-radius: 16px; box-shadow: 0 20px 60px rgba(0,0,0,0.25); z-index: 999999; overflow: hidden;">
                            <div class="notification-dropdown-header"
                                style="padding: 18px 20px; border-bottom: 2px solid #e0e0e0; display: flex; justify-content: space-between; align-items: center; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
                                <h4
                                    style="margin: 0; font-size: 1.1rem; font-weight: 700; color: #ffffff; display: flex; align-items: center; gap: 8px; text-shadow: 0 0 10px rgba(255,255,255,0.8), 0 0 20px rgba(255,255,255,0.6), 0 0 30px rgba(255,255,255,0.4), 0 2px 4px rgba(0,0,0,0.3);">
                                    🔔 Notifikasi</h4>
                                <div class="notification-dropdown-actions" style="display: flex; gap: 10px;">
                                    <button class="notification-action-btn danger"
                                        onclick="deleteAllNotificationsV2(); event.stopPropagation();"
                                        title="Padam Semua"
                                        style="background: rgba(255,255,255,0.95); border: 2px solid #e53e3e; padding: 8px 12px; border-radius: 8px; cursor: pointer; color: #e53e3e; font-size: 1rem; transition: all 0.2s ease; box-shadow: 0 2px 4px rgba(0,0,0,0.2);">🗑️</button>
                                    <button class="notification-action-btn secondary"
                                        onclick="markAllNotificationsReadV2(); event.stopPropagation();"
                                        title="Tandakan Semua Dibaca"
                                        style="background: rgba(255,255,255,0.95); border: 2px solid #38a169; padding: 8px 12px; border-radius: 8px; cursor: pointer; color: #38a169; font-size: 1rem; font-weight: 700; transition: all 0.2s ease; box-shadow: 0 2px 4px rgba(0,0,0,0.2);">✓</button>
                                </div>
                            </div>
                            <div id="notificationList" class="notification-dropdown-body"
                                style="max-height: 350px; overflow-y: auto; padding: 10px;">
                                <div class="notification-item empty"
                                    style="text-align: center; padding: 40px 20px; color: #888;">
                                    <div class="notification-empty-icon" style="font-size: 3rem; margin-bottom: 10px;">
                                        🔔</div>
                                    <div class="notification-empty-title" style="font-weight: 600; margin-bottom: 5px;">
                                        Tiada Notifikasi</div>
                                    <div class="notification-empty-message" style="font-size: 0.85rem;">Anda akan
                                        melihat notifikasi di sini</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div
                        style="display: flex; align-items: center; gap: 15px; border-left: 2px solid #ddd; padding-left: 20px;">
                        <div style="font-size: 2.5rem;"><?php echo htmlspecialchars($teacherEmoji); ?></div>
                        <div>
                            <strong><?php echo htmlspecialchars($teacherName); ?></strong>
                            <p style="margin: 0; color: #666; font-size: 0.9rem;">
                                <?php echo htmlspecialchars($teacherEducationLevel); ?>
                            </p>
                        </div>
                    </div>
                </div>
            </div>

            <?php include __DIR__ . '/../components/teacher/tab-dashboard.php'; ?>

            <div id="students" class="tab-content">
                <!-- Students Info Card -->
                <div class="card" style="margin-bottom: 25px;">
                    <div class="card-body">
                        <div class="info-card-badge"
                            style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 20px;">
                            <div>
                                <h4 style="margin: 0 0 5px 0; color: var(--primary-color);">👨‍🎓 Pengurusan Pelajar
                                </h4>
                                <p style="margin: 0; color: #666; font-size: 0.9rem;">Urus maklumat pelajar, edit
                                    profil, dan lihat status pendaftaran.</p>
                            </div>
                            <div style="display: flex; gap: 10px;">
                                <span class="badge badge-success" style="padding: 8px 15px; font-size: 0.9rem;">✅ Aktif:
                                    <span id="activeStudentsCount">0</span></span>
                                <span class="badge badge-secondary" style="padding: 8px 15px; font-size: 0.9rem;">📚
                                    Subjek:
                                    <?php echo count($teacherSubjects); ?></span>
                            </div>
                        </div>
                    </div>
                </div>

                <?php include __DIR__ . '/../components/teacher/tab-student-management-v2.php'; ?>
            </div>

            <?php include __DIR__ . '/../components/teacher/tab-modules.php'; ?>
            <?php include __DIR__ . '/../components/teacher/tab-schedule.php'; ?>
            <?php include __DIR__ . '/../components/teacher/tab-classrooms.php'; ?>
            <?php include __DIR__ . '/../components/teacher/tab-forum.php'; ?>
            <?php include __DIR__ . '/../components/teacher/tab-announcements.php'; ?>
            <div id="opr" class="tab-content">
                <!-- OPR Info Card -->
                <div class="card" style="margin-bottom: 25px;">
                    <div class="card-body">
                        <div
                            style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 20px;">
                            <div>
                                <h4 style="margin: 0 0 5px 0; color: var(--primary-color);">📄 One Page
                                    Report (OPR)
                                </h4>
                                <p style="margin: 0; color: #666; font-size: 0.9rem;">Laporan ringkas
                                    prestasi pelajar.
                                    Rujuk dokumentasi untuk panduan pengisian.</p>
                            </div>
                            <div style="display: flex; gap: 10px;">
                                <span class="badge badge-secondary" style="padding: 8px 15px; font-size: 0.9rem;">📄
                                    Laporan Ringkasan</span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">📄 One Page Report (OPR)</h3>
                    </div>
                    <div class="card-body" id="oprContent">
                        <p class="text-center">Memuatkan...</p>
                    </div>
                </div>
            </div>

            <div id="settings" class="tab-content">
                <?php include __DIR__ . '/../components/teacher/tab-settings.php'; ?>
            </div>

            <div id="bilik-tutor" class="tab-content">
                <?php include __DIR__ . '/../components/teacher/tab-bilik-tutor.php'; ?>
            </div>

        </main>
    </div>

    <!-- Mobile Bottom Navigation (iPhone Modern App Style) -->
    <nav class="mobile-bottom-nav">
        <a href="#" onclick="switchTabV2(event, 'dashboard')" class="nav-tab-item active" id="mob-nav-dashboard">
            <span class="nav-icon">📊</span>
            <span>Dashboard</span>
        </a>
        <a href="#" onclick="switchTabV2(event, 'student-management')" class="nav-tab-item"
            id="mob-nav-student-management">
            <span class="nav-icon">👨‍🎓</span>
            <span>Pelajar</span>
        </a>
        <a href="#" onclick="switchTabV2(event, 'forum')" class="nav-tab-item" id="mob-nav-forum">
            <span class="nav-icon">💬</span>
            <span>Forum</span>
        </a>
        <a href="#" onclick="switchTabV2(event, 'bilik-tutor')" class="nav-tab-item" id="mob-nav-bilik-tutor">
            <span class="nav-icon">🏢</span>
            <span>Bilik</span>
        </a>
        <a href="#" onclick="switchTabV2(event, 'announcements')" class="nav-tab-item" id="mob-nav-announcements">
            <span class="nav-icon">📢</span>
            <span>Info</span>
        </a>
        <a href="#" onclick="switchTabV2(event, 'settings')" class="nav-tab-item" id="mob-nav-settings">
            <span class="nav-icon">⚙️</span>
            <span>Tetapan</span>
        </a>
        <a href="#" onclick="event.preventDefault(); event.stopPropagation(); toggleMobileMenuV2()"
            class="nav-tab-item">
            <span class="nav-icon">☰</span>
            <span>Menu</span>
        </a>
    </nav>

    <script src="../js/main.js"></script>
    <script>
        // API Base path
        const API_PATH = '../api.php';
        const CURRENT_USER_ID = <?php echo $_SESSION['user_id']; ?>;

        // Mobile Menu Toggle - Premium Animation
        function toggleMobileMenuV2() {
            const sidebar = document.getElementById('sidebar');
            const overlay = document.getElementById('sidebarOverlay');

            if (sidebar && overlay) {
                sidebar.classList.toggle('open');
                overlay.classList.toggle('active');

                // Prevent body scroll when menu is open
                document.body.style.overflow = sidebar.classList.contains('open') ? 'hidden' : '';
            }
        }

        // Close Mobile Menu
        function closeMobileMenuV2() {
            const sidebar = document.getElementById('sidebar');
            const overlay = document.getElementById('sidebarOverlay');

            if (sidebar && overlay) {
                sidebar.classList.remove('open');
                overlay.classList.remove('active');
                document.body.style.overflow = '';
            }
        }

        // Theme-aware notification helper function - Modern Square Style
        function showNotificationV2(message, type) {
            // Get portal theme color
            const themeColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#667eea';

            const iconMap = {
                'success': 'success',
                'error': 'error',
                'warning': 'warning',
                'info': 'info'
            };

            Swal.fire({
                title: type === 'success' ? 'Berjaya!' : type === 'error' ? 'Ralat!' : type === 'warning' ? 'Perhatian!' : 'Maklumat',
                text: message,
                icon: iconMap[type] || 'info',
                confirmButtonColor: themeColor,
                confirmButtonText: 'OK',
                customClass: {
                    popup: 'swal-modern',
                    confirmButton: 'swal-modern-btn'
                },
                showClass: {
                    popup: 'animate__animated animate__fadeInUp animate__faster'
                },
                hideClass: {
                    popup: 'animate__animated animate__fadeOutDown animate__faster'
                },
                timer: type === 'success' ? 2500 : undefined,
                timerProgressBar: type === 'success'
            });
        }

        // Theme-aware confirmation dialog
        function showConfirmV2(title, text, callback) {
            const themeColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#667eea';

            Swal.fire({
                title: title,
                text: text,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: themeColor,
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Ya',
                cancelButtonText: 'Batal',
                borderRadius: '15px',
                reverseButtons: true
            }).then((result) => {
                if (result.isConfirmed && callback) {
                    callback();
                }
            });
        }

        var studentsData = [];

        // Simple toggle for notification dropdown with animation
        function toggleNotificationDropdown(event) {
            if (event) event.stopPropagation();

            var dropdown = document.getElementById('notificationDropdown');
            if (!dropdown) {
                console.error('Dropdown not found!');
                return;
            }

            // Check current state
            var isHidden = (dropdown.style.display === 'none' || dropdown.style.display === '' ||
                window.getComputedStyle(dropdown).display === 'none');

            // Get responsive width
            var dropdownWidth = window.innerWidth < 420 ? (window.innerWidth - 20) + 'px' : '380px';
            var rightPosition = window.innerWidth < 420 ? '10px' : '20px';

            if (isHidden) {
                // Show dropdown with animation
                dropdown.style.cssText = 'display: block !important; position: fixed !important; right: ' + rightPosition + ' !important; top: 70px !important; width: ' + dropdownWidth + ' !important; max-height: 450px !important; background: #ffffff !important; border-radius: 16px !important; box-shadow: 0 20px 60px rgba(0,0,0,0.25) !important; z-index: 999999 !important; overflow: hidden !important; visibility: visible !important; opacity: 0 !important; transform: translateY(-10px) scale(0.95) !important; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;';

                // Trigger animation after a frame
                requestAnimationFrame(function () {
                    requestAnimationFrame(function () {
                        dropdown.style.opacity = '1';
                        dropdown.style.transform = 'translateY(0) scale(1)';
                    });
                });

                // Load notifications
                if (typeof loadNotificationsV2 === 'function') {
                    loadNotificationsV2();
                }
            } else {
                // Hide with animation
                dropdown.style.opacity = '0';
                dropdown.style.transform = 'translateY(-10px) scale(0.95)';
                setTimeout(function () {
                    dropdown.style.display = 'none';
                }, 300);
            }
        }

        // Close dropdown when clicking outside
        document.addEventListener('click', function (event) {
            var dropdown = document.getElementById('notificationDropdown');
            var bellBtn = document.getElementById('notificationBellBtn');
            if (dropdown && bellBtn) {
                if (!dropdown.contains(event.target) && !bellBtn.contains(event.target)) {
                    if (dropdown.style.display !== 'none' && dropdown.style.display !== '') {
                        dropdown.style.opacity = '0';
                        dropdown.style.transform = 'translateY(-10px) scale(0.95)';
                        setTimeout(function () {
                            dropdown.style.display = 'none';
                        }, 300);
                    }
                }
            }
        });

        document.addEventListener('DOMContentLoaded', function () {
            updateRealtimeClockV2();
            updateBannerTimeV2(); // Initial update for wow banner
            // Initialize notification system
            initNotificationSystemV2();
            setInterval(updateRealtimeClockV2, 1000);
            setInterval(updateBannerTimeV2, 1000); // Sync banner time

            // Auto-sync data on page load to ensure enrollments are synced
            syncDataOnLoadV2();
            loadStudentsV2();  // Load students on page load

            loadTodaySlotsV2(); // Load today's schedule slots
            initializeEmojiPicker();
            loadModulesV2();
            initializeStatusToggle(); // Initialize status toggle based on teacher status
            loadScheduleV2();
            loadClassesV2();
            loadForumV2();
            loadAnnouncementsV2();
            loadOPRV2();
            loadMaintenanceLogsV2(); // Load maintenance logs
            loadPendingPasswordStudentsV2(); // Load students pending password setup

            // Trigger CountUp for subjects taught (PHP variable used directly)
            var subjectVal = parseInt(document.getElementById('subjectCountValue').textContent) || 0;
            animateValue('subjectCountValue', 0, subjectVal, 1500);

            // Restore saved tab
            // FIXED: Always show dashboard on login, don't restore previous tab
            const savedTab = localStorage.getItem('activeTab') || 'dashboard';

            // Always show dashboard first after login
            switchTabV2(null, 'dashboard');

            // Clear saved tab so next login starts at dashboard
            localStorage.removeItem('activeTab');
        });

        // Logout function FIXED
        function logoutV2() {
            // Tunjuk status sedang proses
            const btn = document.querySelector('button[onclick="logoutV2()"]');
            if (btn) btn.innerHTML = '⏳ Keluar...';

            fetch(API_PATH + '?action=logout')
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    window.location.href = '../index.php'; // Redirect ke login
                })
                .catch(function (err) {
                    console.error('Logout error:', err);
                    window.location.href = '../index.php'; // Fallback redirect
                });
        }

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

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

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

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

            var clockEl = document.getElementById('realtimeClock');
            var dateEl = document.getElementById('realtimeDate');
            if (clockEl) clockEl.textContent = timeString;
            if (dateEl) dateEl.textContent = dayName + ', ' + dateString;

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

            if (bannerDayEl) bannerDayEl.textContent = dayName;
            if (bannerDateEl) bannerDateEl.textContent = dateString;
            if (bannerTimeEl) bannerTimeEl.textContent = timeString;
        }

        function updateBannerTimeV2() {
            updateRealtimeClockV2();
        }


        function switchTabV2(event, tabId) {
            if (event) event.preventDefault();

            // Clear Bilik Tutor interval if leaving the tab
            if (tabId !== 'bilik-tutor' && window.tutorChatInterval) {
                clearInterval(window.tutorChatInterval);
                window.tutorChatInterval = null;
            }

            // 1. Sync with mobile bottom navigation
            document.querySelectorAll('.nav-tab-item').forEach(function (el) {
                el.classList.remove('active');
            });
            var mobNav = document.getElementById('mob-nav-' + tabId);
            if (mobNav) mobNav.classList.add('active');

            // Remove active class from all nav items
            document.querySelectorAll('.nav-item').forEach(function (item) {
                item.classList.remove('active');
            });

            // Add active class to clicked nav
            var activeNav = document.getElementById('nav-' + tabId);
            if (activeNav) activeNav.classList.add('active');

            // Special handling for student-management (nested inside #students)
            var isStudentManagement = (tabId === 'student-management');

            // Hide all tab contents
            document.querySelectorAll('.tab-content').forEach(function (content) {
                content.classList.remove('active');
                // Keep #students visible if we're switching to student-management
                if (isStudentManagement && content.id === 'students') {
                    // Don't hide the parent
                } else if (content.id !== tabId) {
                    content.style.display = 'none';
                }
            });

            // Show selected tab content
            var activeTab = document.getElementById(tabId);
            if (activeTab) {
                activeTab.style.display = 'block';
                setTimeout(function () {
                    activeTab.classList.add('active');
                }, 10);

                // If student-management, also show parent #students container
                if (isStudentManagement) {
                    var studentsTab = document.getElementById('students');
                    if (studentsTab) {
                        studentsTab.style.display = 'block';
                        studentsTab.classList.add('active');
                    }
                }

                // Load data based on tabId
                switch (tabId) {
                    case 'dashboard':
                        if (typeof loadDashboardV3 === 'function') loadDashboardV3();
                        break;
                    case 'students':
                        if (typeof loadStudentsV2 === 'function') loadStudentsV2();
                        break;
                    case 'student-management':
                        if (window.loadStudentManagementDataV2) {
                            loadStudentManagementDataV2();
                        } else {
                            if (typeof loadStudentManagementData === 'function') loadStudentManagementData();
                        }
                        break;
                    case 'modules':
                        if (typeof loadModulesV3 === 'function') loadModulesV3();
                        break;
                    case 'schedule':
                        if (typeof loadScheduleV3 === 'function') loadScheduleV3();
                        break;
                    case 'classrooms':
                        if (typeof loadClassesV3 === 'function') loadClassesV3();
                        break;
                    case 'forum':
                        if (typeof loadForumV3 === 'function') loadForumV3();
                        break;
                    case 'announcements':
                        if (typeof loadAnnouncementsV3 === 'function') loadAnnouncementsV3();
                        break;
                    case 'bilik-tutor':
                        if (typeof loadTutorRoomData === 'function') {
                            loadTutorRoomData();
                        }
                        break;
                    case 'opr':
                        if (typeof loadOPRV2 === 'function') loadOPRV2();
                        break;
                    case 'settings':
                        if (typeof loadPendingPasswordStudentsV2 === 'function') loadPendingPasswordStudentsV2();
                        break;
                }

                // Save state
                localStorage.setItem('activeTab', tabId);

                // Auto close mobile menu
                closeMobileMenuV2();
            }
        }

        function loadStudentsV2() {
            // Load students from get_teacher_students API
            fetch(API_PATH + '?action=get_teacher_students')
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success) {
                        var apiStudents = result.students || [];

                        // Add enrolled_subject to each student based on their required_subjects
                        // For simplified version, use first subject from required_subjects as enrolled_subject
                        studentsData = apiStudents.map(function (student) {
                            var studentCopy = Object.assign({}, student);
                            var subjects = JSON.parse(student.required_subjects || '[]');
                            // Use the first subject as enrolled_subject for display
                            studentCopy.enrolled_subject = subjects.length > 0 ? subjects[0] : 'Lain-lain';
                            studentCopy.enrollment_status = 'Active';
                            return studentCopy;
                        });

                        // Also process students_by_subject from API response
                        window.studentsBySubject = result.students_by_subject || {};

                        displayStudentsV2(studentsData);

                        // Update student count in dashboard with animation
                        var approvedCount = result.approved_count || studentsData.length;
                        var studentObj = document.getElementById('studentCountValue');
                        var currentStudents = parseInt(studentObj.textContent) || 0;
                        animateValue('studentCountValue', currentStudents, approvedCount, 1000);

                        // Update dashboard pending enrollments count with animation
                        var pendingCount = result.pending_count || 0;
                        var pendingObj = document.getElementById('dashboardPendingEnrollments');
                        var currentPending = parseInt(pendingObj.textContent) || 0;
                        animateValue('dashboardPendingEnrollments', currentPending, pendingCount, 1000);
                        document.getElementById('menuPendingBadge').textContent = pendingCount;

                        // Update info cards
                        if (document.getElementById('infoPendingCount')) {
                            document.getElementById('infoPendingCount').textContent = pendingCount;
                        }
                        if (document.getElementById('infoApprovedCount')) {
                            document.getElementById('infoApprovedCount').textContent = approvedCount;
                        }
                    } else {
                        console.error('Failed to load students:', result.message);
                        var tbody = document.getElementById('studentsList');
                        if (tbody) tbody.innerHTML = '<tr><td colspan="7" class="text-center text-danger">Gagal memuatkan data: ' + (result.message || 'Ralat tidak diketahui') + '</td></tr>';
                    }
                })
                .catch(function (err) {
                    console.error('Error loading students:', err);
                    var tbody = document.getElementById('studentsList');
                    if (tbody) tbody.innerHTML = '<tr><td colspan="7" class="text-center text-danger">Ralat sambungan. Sila cuba lagi.</td></tr>';
                });
        }

        // Wrapper function to load all student management data
        function loadStudentManagementData() {
            loadStudentsV2(); // Loads active students and populates studentsData

            // If open pool functions exist, load them too
            if (typeof loadOpenPoolStudents === 'function') {
                loadOpenPoolStudents();
            }
            if (typeof refreshOpenPoolStats === 'function') {
                refreshOpenPoolStats();
            }
        }

        // Load today's schedule slots
        function loadTodaySlotsV2() {
            var today = new Date().toISOString().split('T')[0];
            fetch(API_PATH + '?action=get_teacher_schedule')
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success && result.schedules) {
                        // Filter schedules for today
                        var todaySchedules = result.schedules.filter(function (s) {
                            return s.schedule_date === today;
                        });
                        var slotsObj = document.getElementById('todaySlotsCount');
                        var currentSlots = parseInt(slotsObj.textContent) || 0;
                        animateValue('todaySlotsCount', currentSlots, todaySchedules.length, 1000);
                    } else {
                        animateValue('todaySlotsCount', 0, 0, 1000);
                        document.getElementById('todaySlotsCount').textContent = '0';
                    }
                })
                .catch(function (err) {
                    console.error('Error loading today slots:', err);
                    document.getElementById('todaySlotsCount').textContent = '-';
                });
        }

        // ========== SYNC DATA FUNCTION ==========
        // Call this on page load to ensure enrollments are synced
        function syncDataOnLoadV2() {
            // First sync all teacher students to ensure enrollments exist
            fetch(API_PATH + '?action=sync_all_teacher_students')
                .then(function (response) { return response.json(); })
                .then(function (syncResult) {
                    console.log('Sync result:', syncResult);
                    // Then load students and enrollments
                    loadStudentsV2();
                    loadEnrollmentsV2();
                    loadTaughtStudentsV2();
                    loadPendingPasswordStudentsV2();
                })
                .catch(function (err) {
                    console.error('Error syncing data:', err);
                    // Still try to load data even if sync fails
                    loadStudentsV2();
                    loadEnrollmentsV2();
                });
        }

        function displayStudentsV2(students) {
            // Target the NEW tab containers
            var myStudentsTbody = document.getElementById('my-students-list');
            var globalStudentsTbody = document.getElementById('global-students-list');

            // Fallback for old dashboard structure if needed
            var oldTbody = document.getElementById('studentsList');

            if (!myStudentsTbody && !globalStudentsTbody && !oldTbody) return;

            if (!students || students.length === 0) {
                var emptyHtml = '<tr><td colspan="5" class="text-center">Tiada data pelajar ditemui.</td></tr>';
                if (myStudentsTbody) myStudentsTbody.innerHTML = emptyHtml;
                if (globalStudentsTbody) globalStudentsTbody.innerHTML = emptyHtml;
                if (oldTbody) oldTbody.innerHTML = emptyHtml;
                return;
            }

            // 1. My Students (Bahagian IV)
            var myStudents = students; // For now, assume fetched students are "my students" based on API context
            // Ideally filter by teacher ID if the API returns EVERYONE, but usually 'get_teacher_students' returns assigned students.

            if (myStudentsTbody) {
                var html = '';
                if (myStudents.length === 0) {
                    html = '<tr><td colspan="4" class="text-center">Tiada pelajar berdaftar di bawah anda.</td></tr>';
                } else {
                    myStudents.forEach(function (s, i) {
                        html += '<tr>';
                        html += '<td><strong>' + (s.full_name || s.student_name || '-') + '</strong>';
                        if (s.is_manually_added == 0) html += ' <span class="badge badge-info" style="font-size: 0.7em">Auto</span>';
                        html += '</td>';
                        html += '<td><span class="badge badge-primary">' + (s.enrolled_subject || s.subject || 'Lain-lain') + '</span></td>';
                        html += '<td>' + (s.phone || '-') + '</td>';
                        html += '<td>';
                        html += '<button class="btn btn-info btn-sm me-1" onclick="viewStudentDetailsV2(' + s.id + ')">👁️</button>';
                        html += '<button class="btn btn-secondary btn-sm me-1" onclick="if(window.editStudentV2) { editStudentV2(' + s.id + '); } else { editStudent(' + s.id + '); }">✏️</button>';
                        html += '<button class="btn btn-danger btn-sm" onclick="deleteStudentV2(' + s.id + ')">🗑️</button>';
                        html += '<button class="btn btn-warning btn-sm ms-1" onclick="generateIndividualPDFV2(' + s.id + ')" title="Jana Laporan PDF">📄</button>';
                        html += '</td>';
                        html += '</tr>';
                    });
                }
                myStudentsTbody.innerHTML = html;

                // Update badge count
                var countBadge = document.getElementById('badge-my-count');
                if (countBadge) countBadge.textContent = myStudents.length;
            }

            // 2. Global Students (Bahagian III) - If the API returns them
            // Typically request filtering or a separate API. For this view, we'll duplicate 'students' or use a separate call.
            // As a quick fix, let's just populate Global with `studentsData` if it exists.
            if (globalStudentsTbody && window.studentsData) {
                var html = '';
                studentsData.forEach(function (s) {
                    html += '<tr>';
                    html += '<td>' + (s.full_name || '-') + '</td>';
                    html += '<td>' + (s.age || '-') + '</td>';
                    html += '<td>' + (s.education_level || '-') + '</td>';
                    html += '<td>' + (s.phone || '-') + '</td>';
                    html += '<td><span class="badge badge-success">Aktif</span></td>';
                    html += '</tr>';
                });
                globalStudentsTbody.innerHTML = html;
            }

            // Legacy Support (keep #studentsList populated just in case old tab is visible)
            if (oldTbody) {
                // ... (Existing logic simplified)
                var html = '';
                students.forEach(function (s, i) {
                    html += '<tr><td>' + (i + 1) + '</td><td>' + (s.full_name || '-') + '</td><td>' + (s.age || '-') + '</td><td>' + (s.education_level || '-') + '</td><td>' + (s.subject || '-') + '</td><td>Active</td><td><button onclick="viewStudentDetailsV2(' + s.id + ')">View</button></td></tr>';
                });
                oldTbody.innerHTML = html;
            }
        }

        function searchStudentsV2() {
            var searchTerm = document.getElementById('studentSearch').value.toLowerCase();
            var filtered = studentsData.filter(function (student) {
                return (student.full_name || student.student_name || '').toLowerCase().includes(searchTerm);
            });
            displayStudentsV2(filtered);
        }

        function viewStudentDetailsV2(studentId) {
            // Get student details from API and show in modal
            fetch(API_PATH + '?action=get_student_profile&student_id=' + studentId)
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success && result.profile) {
                        var s = result.profile;
                        var subjects = JSON.parse(s.required_subjects || '[]');
                        var enrollmentDate = null;

                        // Get enrollment date from studentsData
                        var studentData = studentsData.find(function (st) { return st.id === studentId; });
                        if (studentData && studentData.enrolled_at) {
                            enrollmentDate = formatDate(studentData.enrolled_at);
                        }

                        var isAutoAssigned = studentData && studentData.is_manually_added != 1;

                        document.getElementById('studentDetailName').textContent = s.full_name || '-';
                        document.getElementById('studentDetailAge').textContent = s.age || '-';
                        document.getElementById('studentDetailParent').textContent = s.parent_guardian_name || '-';
                        document.getElementById('studentDetailPhone').textContent = s.phone || '-';
                        document.getElementById('studentDetailLevel').textContent = (s.education_level || '-') + ' - ' + (s.grade_level || '-');
                        document.getElementById('studentDetailSubjects').innerHTML = subjects.map(function (sub) {
                            return '<span class="badge badge-primary" style="margin: 2px;">' + sub + '</span>';
                        }).join(' ');

                        // Add auto-assign info
                        var extraInfo = document.getElementById('studentDetailExtra');
                        if (isAutoAssigned) {
                            extraInfo.innerHTML = '<div style="margin-top: 10px; padding: 10px; background: #e8f4ff; border-radius: 8px; border-left: 4px solid #667eea;"><strong>⚡ Auto-assign oleh sistem</strong><br><small>Pelajar ini telah ditetapkan oleh sistem kerana tiada guru tersedia untuk subjek.</small></div>';
                        } else {
                            extraInfo.innerHTML = '<div style="margin-top: 10px; padding: 10px; background: #e8f4ff; border-radius: 8px; border-left: 4px solid #667eea;"><strong>✓ Didaftar oleh guru</strong><br><small>Pelajar ini didaftarkan secara manual.</small></div>';
                        }

                        // Add enrollment date
                        var dateInfo = document.getElementById('studentDetailDate');
                        if (enrollmentDate) {
                            dateInfo.innerHTML = '<div style="margin-top: 5px;"><strong>Tarikh Daftar:</strong> ' + enrollmentDate + '</div>';
                        } else {
                            dateInfo.innerHTML = '';
                        }

                        openModal('studentDetailModal');
                    } else {
                        showNotificationV2('Gagal memuatkan maklumat pelajar', 'error');
                    }
                })
                .catch(function (err) {
                    console.error('Error fetching student details:', err);
                    showNotificationV2('Ralat sambungan', 'error');
                });
        }

        function removeStudentV2(studentId) {
            var student = studentsData.find(function (s) { return s.id === studentId; });
            var studentName = student ? student.full_name : 'pelajar ini';

            // Get portal theme color
            const themeColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#667eea';

            Swal.fire({
                title: 'Padam Pelajar?',
                text: 'Adakah anda pasti ingin memadam ' + studentName + '? Pelajar akan dinyahaktifkan.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: themeColor,
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Ya, Padam',
                cancelButtonText: 'Batal',
                borderRadius: '15px',
                reverseButtons: true
            }).then((result) => {
                if (result.isConfirmed) {
                    var formData = new FormData();
                    formData.append('action', 'delete_student');
                    formData.append('id', studentId);

                    fetch(API_PATH, { method: 'POST', body: formData })
                        .then(function (response) { return response.json(); })
                        .then(function (res) {
                            if (res.success) {
                                showNotificationV2('Pelajar berjaya dipadam', 'success');
                                loadStudentsV2();
                            } else {
                                showNotificationV2(res.message, 'error');
                            }
                        })
                        .catch(function (err) {
                            showNotificationV2('Ralat sambungan', 'error');
                        });
                }
            });
        }

        function deleteStudentV2(studentId) {
            removeStudentV2(studentId);
        }

        function loadTaughtStudentsV2() {
            var container = document.getElementById('taughtStudentsList');

            fetch(API_PATH + '?action=get_teacher_enrollments&status=Approved')
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success && result.enrollments && result.enrollments.length > 0) {
                        // Group students by subject
                        var studentsBySubject = {};
                        result.enrollments.forEach(function (e) {
                            var subject = e.subject || 'Lain-lain';
                            if (!studentsBySubject[subject]) {
                                studentsBySubject[subject] = [];
                            }
                            studentsBySubject[subject].push(e);
                        });

                        var html = '';
                        Object.keys(studentsBySubject).sort().forEach(function (subject) {
                            var students = studentsBySubject[subject];
                            students.forEach(function (s) {
                                html += '<span class="badge badge-primary" style="padding: 8px 12px; font-size: 0.9rem;">';
                                html += s.student_name + ' (' + subject + ')';
                                html += '</span>';
                            });
                        });
                        container.innerHTML = html;
                    } else {
                        container.innerHTML = '<p class="text-muted">Tiada pelajar berdaftar lagi. Sila luluskan pendaftaran pelajar.</p>';
                    }
                })
                .catch(function (err) {
                    console.error('Error loading taught students:', err);
                    container.innerHTML = '<p class="text-danger">Ralat memuatkan senarai pelajar</p>';
                });
        }

        function loadOPRV2() {
            fetch(API_PATH + '?action=get_opr_settings')
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    var container = document.getElementById('oprContent');
                    if (result.success && result.opr) {
                        container.innerHTML = '<h4>' + (result.opr.title || 'One Page Report') + '</h4><p>' + (result.opr.description || '') + '</p>' + (result.opr.link ? '<a href="' + result.opr.link + '" target="_blank" class="btn btn-primary">Buka Dokumentasi OPR</a>' : '');
                    } else {
                        container.innerHTML = '<p class="text-muted">Tetapan OPR tidak tersedia</p>';
                    }
                })
                .catch(function (err) {
                    console.error('Error loading OPR:', err);
                });
        }

        function initializeEmojiPicker() {
            var emojiOptions = document.querySelectorAll('#teacherEmojiPicker .emoji-option');
            emojiOptions.forEach(function (option) {
                option.addEventListener('click', function () {
                    emojiOptions.forEach(function (o) { o.classList.remove('selected'); });
                    this.classList.add('selected');
                    document.getElementById('selectedEmoji').value = this.dataset.emoji;
                });
            });
        }

        /**
* Initialize status toggle based on teacher's current status from PHP
*/
        function initializeStatusToggle() {
            // Get teacher status from PHP - defaults to 'Active' if not set
            var teacherStatus = '<?php echo $teacher["status"] ?? "Active"; ?>';
            var isActive = teacherStatus === 'Active';

            // Set toggle state
            var toggle = document.getElementById('statusToggle');
            if (toggle) {
                toggle.checked = isActive;
            }

            // Update UI
            updateStatusUI(isActive);
        }

        function updateProfile(e) {
            e.preventDefault();
            var formData = new FormData(document.getElementById('profileForm'));
            formData.append('action', 'update_teacher_profile');
            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (res) {
                    if (res.success) {
                        showNotificationV2('Profil dikemaskini', 'success');
                        setTimeout(function () { location.reload(); }, 1500);
                    } else {
                        showNotificationV2(res.message, 'error');
                    }
                })
                .catch(function (err) {
                    showNotificationV2('Ralat sambungan', 'error');
                });
        }

        // ========== MODAL HELPER FUNCTIONS ==========
        function openModal(modalId) {
            var modal = document.getElementById(modalId);
            if (modal) {
                // Universal Kill Switch: Move modal to body to break out of any stacking context traps
                if (modal.parentNode !== document.body) {
                    document.body.appendChild(modal);
                }

                // FORCE RESET DISPLAY PROPERTY (The Fix)
                modal.style.display = '';
                modal.style.removeProperty('display');

                modal.classList.add('active');
                document.body.style.overflow = 'hidden';
            }
        }

        function closeModal(modalId) {
            var modal = document.getElementById(modalId);
            if (modal) {
                modal.classList.remove('active');
                document.body.style.overflow = '';
            }
        }

        // ========== STUDENT MANAGEMENT FUNCTIONS ==========
        var editingStudentId = null;

        function editStudent(id) {
            console.log('Editing student ID:', id);

            // Forward to V2 handler if available (Priority Fix)
            if (typeof editStudentV2 === 'function') {
                editStudentV2(id);
                return;
            }

            // 1. Try to find in local data first
            var student = null;
            if (typeof studentsData !== 'undefined' && Array.isArray(studentsData)) {
                student = studentsData.find(function (s) {
                    // Check both 'id' and 'student_id' loose equality
                    return (s.id == id) || (s.student_id == id);
                });
            }

            // 2. If found locally, populate and show
            if (student) {
                populateEditStudentModal(student);
            } else {
                // 3. If not found locally, fetch from server (Fallback)
                console.warn('Student not found locally, fetching from server...');

                // Show loading state
                Swal.fire({
                    title: 'Sedang mencari data...',
                    allowOutsideClick: false,
                    didOpen: () => { Swal.showLoading(); }
                });

                fetch(API_PATH + '?action=get_student_profile&student_id=' + id)
                    .then(function (res) { return res.json(); })
                    .then(function (result) {
                        Swal.close();
                        if (result.success && result.profile) {
                            populateEditStudentModal(result.profile);
                        } else {
                            showNotificationV2('Pelajar tidak dijumpai dalam pangkalan data.', 'error');
                        }
                    })
                    .catch(function (err) {
                        Swal.close();
                        console.error('Error fetching student:', err);
                        showNotificationV2('Ralat sambungan server.', 'error');
                    });
            }
        }

        function populateEditStudentModal(student) {
            editingStudentId = student.id || student.student_id;

            document.getElementById('studentModalTitle').textContent = '✏️ Kemaskini Pelajar';
            document.getElementById('studentId').value = editingStudentId;
            document.getElementById('studentFullName').value = student.full_name || student.student_name || '';
            document.getElementById('studentAge').value = student.age || '';
            document.getElementById('studentParent').value = student.parent_guardian_name || '';
            document.getElementById('studentPhone').value = student.phone || student.student_phone || '';

            // Set education level and update grade options
            var educationLevel = student.education_level || '';
            document.getElementById('studentEducationLevel').value = educationLevel;
            updateGradeOptions();

            // Set grade after options update
            setTimeout(function () {
                var gradeSelect = document.getElementById('studentGradeLevel');
                if (gradeSelect) gradeSelect.value = student.grade_level || student.grade || '';
            }, 100);

            // Load subjects and set checked
            if (typeof loadSubjectsForStudentForm === 'function') {
                loadSubjectsForStudentForm().then(function () {
                    var subjects = [];
                    try {
                        subjects = typeof student.required_subjects === 'string' ? JSON.parse(student.required_subjects) : (student.required_subjects || []);
                    } catch (e) { subjects = []; }

                    if (!Array.isArray(subjects)) subjects = [];

                    subjects.forEach(function (sub) {
                        var cb = document.querySelector('input[name="subjects[]"][value="' + sub + '"]');
                        if (cb) cb.checked = true;
                    });
                });
            }

            openModal('studentModal');
        }

        function deleteStudent(id) {
            // Get portal theme color
            const themeColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#667eea';

            Swal.fire({
                title: 'Padam Pelajar?',
                text: 'Pelajar ini akan dipadamkan secara kekal.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: themeColor,
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Ya, Padam',
                cancelButtonText: 'Batal',
                borderRadius: '15px',
                reverseButtons: true
            }).then((result) => {
                if (result.isConfirmed) {
                    var formData = new FormData();
                    formData.append('action', 'delete_student');
                    formData.append('id', id);

                    fetch(API_PATH, { method: 'POST', body: formData })
                        .then(function (response) { return response.json(); })
                        .then(function (res) {
                            if (res.success) {
                                showNotificationV2('Pelajar berjaya dipadam', 'success');
                                if (typeof loadStudentManagementData === "function") { loadStudentManagementData(); } else { loadStudentsV2(); }
                            } else {
                                showNotificationV2(res.message, 'error');
                            }
                        })
                        .catch(function (err) {
                            showNotificationV2('Ralat sambungan', 'error');
                        });
                }
            });
        }

        function loadSubjectsForStudentForm() {
            return fetch(API_PATH + '?action=get_subjects')
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    var container = document.getElementById('studentSubjectChecklist');
                    if (result.success && result.subjects && result.subjects.length > 0) {
                        var html = '';
                        result.subjects.forEach(function (s) {
                            html += `<label class="form-check" onclick="toggleSubject(this)" style="cursor: pointer; display: flex; align-items: center; gap: 10px; padding: 10px; border: 1px solid #eee; border-radius: 8px;">
                                <input type="checkbox" name="required_subjects[]" value="${s.subject_name}" style="transform: scale(1.2);">
                                <span class="form-check-label" style="font-weight: 500;">${s.subject_name}</span>
                            </label>`;
                        });
                        container.innerHTML = html;
                    }
                });
        }

        function toggleSubject(label) {
            // Function to handle visual selection state styling if needed
            // The actual checkbox state is handled by the input itself
            const input = label.querySelector('input[type="checkbox"]');
            if (input.checked) {
                label.style.borderColor = 'var(--primary-color)';
                label.style.background = 'rgba(102, 126, 234, 0.05)';
            } else {
                label.style.borderColor = '#eee';
                label.style.background = 'transparent';
            }
        }

        function saveStudent(event) {
            event.preventDefault();

            var formData = new FormData(document.getElementById('studentForm'));
            formData.append('action', editingStudentId ? 'update_student' : 'add_student');
            if (editingStudentId) {
                formData.append('id', editingStudentId);
            }

            var submitBtn = document.querySelector('#studentForm button[type="submit"]');
            var originalText = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '⏳ Sedang memproses...';

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success) {
                        showNotificationV2(editingStudentId ? 'Pelajar berjaya dikemaskini' : 'Pelajar berjaya ditambah', 'success');
                        closeModal('studentModal');
                        if (typeof loadStudentManagementData === 'function') {
                            loadStudentManagementData();
                        } else {
                            loadStudentsV2();
                        }
                    } else {
                        showNotificationV2(result.message, 'error');
                    }
                })
                .catch(function (err) {
                    showNotificationV2('Ralat sambungan', 'error');
                })
                .finally(function () {
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = originalText;
                });
        }

        // ========== MODULE FUNCTIONS ==========
        function showAddModuleModalV2() {
            openModal('moduleModal');
            var moduleForm = document.getElementById('moduleForm');
            var moduleId = document.getElementById('moduleId');
            if (moduleForm) moduleForm.reset();
            if (moduleId) moduleId.value = '';
        }

        // ========== SCHEDULE FUNCTIONS ==========
        function showAddScheduleModalV2() {
            openModal('scheduleModal');
            var scheduleForm = document.getElementById('scheduleForm');
            var scheduleId = document.getElementById('scheduleId');
            if (scheduleForm) scheduleForm.reset();
            if (scheduleId) scheduleId.value = '';
        }

        // ========== CLASSROOM FUNCTIONS ==========
        function showAddClassModalV2() {
            openModal('classModal');
            var classForm = document.getElementById('classForm');
            var classId = document.getElementById('classId');
            if (classForm) classForm.reset();
            if (classId) classId.value = '';
        }

        // ========== FORUM FUNCTIONS ==========
        function showAddForumModalV2() {
            openModal('forumModal');
            var forumForm = document.getElementById('forumForm');
            var forumId = document.getElementById('forumId');
            if (forumForm) forumForm.reset();
            if (forumId) forumId.value = '';
        }

        // ========== ANNOUNCEMENT FUNCTIONS ==========
        function showAddAnnouncementModalV2() {
            openModal('announcementModal');
            var announcementForm = document.getElementById('announcementForm');
            var announcementId = document.getElementById('announcementId');
            if (announcementForm) announcementForm.reset();
            if (announcementId) announcementId.value = '';
        }
    </script>

    <div class="modal-overlay" id="studentModal">
        <div class="modal" style="max-width: 700px;">
            <div class="modal-header">
                <h3 class="modal-title" id="studentModalTitle">➕ Tambah Pelajar Baru</h3>
                <button class="modal-close" onclick="closeModal('studentModal')">×</button>
            </div>
            <div class="modal-body">
                <form id="studentForm" onsubmit="saveStudent(event)">
                    <input type="hidden" name="id" id="studentId">

                    <div class="form-group">
                        <label class="form-label">Nama Penuh <span class="required">*</span></label>
                        <input type="text" class="form-control" id="studentFullName" name="full_name" required
                            placeholder="cth: Ali Bin Abu">
                    </div>

                    <div class="form-row" style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                        <div class="form-group">
                            <label class="form-label">Umur <span class="required">*</span></label>
                            <input type="number" class="form-control" id="studentAge" name="age" required min="5"
                                max="25" placeholder="cth: 12">
                        </div>

                        <div class="form-group">
                            <label class="form-label">No. Telefon <span class="required">*</span></label>
                            <input type="tel" class="form-control" id="studentPhone" name="phone" required
                                placeholder="cth: 012-3456789">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Nama Penjaga <span class="required">*</span></label>
                        <input type="text" class="form-control" id="studentParent" name="parent_guardian_name" required
                            placeholder="cth: Abu Bin Said">
                    </div>

                    <div class="form-row" style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                        <div class="form-group">
                            <label class="form-label">Tahap Pendidikan <span class="required">*</span></label>
                            <select class="form-control form-select" id="studentEducationLevel" name="education_level"
                                required onchange="updateGradeOptions()">
                                <option value="">Pilih Tahap</option>
                                <option value="Sekolah Rendah">Sekolah Rendah</option>
                                <option value="Sekolah Menengah">Sekolah Menengah</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label class="form-label">Tahun/Tingkatan <span class="required">*</span></label>
                            <select class="form-control form-select" id="studentGradeLevel" name="grade_level" required>
                                <option value="">Pilih Tahap Dahulu</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Subjek Diperlukan <span class="required">*</span></label>
                        <p class="text-muted" style="margin-bottom: 10px; font-size: 0.9rem;">Pilih satu atau lebih
                            subjek</p>
                        <div id="studentSubjectChecklist" class="subject-checklist">
                            <p class="text-muted">Memuatkan subjek...</p>
                        </div>
                    </div>

                    <div style="margin-top: 25px; display: flex; gap: 10px;">
                        <button type="button" class="btn btn-secondary" style="flex: 1;"
                            onclick="closeModal('studentModal')">Batal</button>
                        <button type="submit" class="btn btn-primary" style="flex: 1;">💾 Simpan Pelajar</button>
                    </div>
                </form>
            </div>
        </div>
    </div>


    <!-- Reject Modal -->
    <div class="modal-overlay" id="rejectModal">
        <div class="modal" style="max-width: 500px;">
            <div class="modal-header">
                <h3 class="modal-title">❌ Tolak Pendaftaran</h3>
                <button class="modal-close" onclick="closeModal('rejectModal')">×</button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="rejectEnrollmentId" value="">

                <div class="form-group">
                    <label class="form-label">Sebab Penolakan <span class="required">*</span></label>
                    <textarea class="form-control" id="rejectReason" rows="4"
                        placeholder="Nyatakan sebab pelajar ini ditolak..."></textarea>
                </div>

                <div style="margin-top: 20px; display: flex; gap: 10px;">
                    <button type="button" class="btn btn-secondary" style="flex: 1;"
                        onclick="closeModal('rejectModal')">Batal</button>
                    <button type="button" class="btn btn-danger" style="flex: 1;" onclick="confirmReject()">❌
                        Tolak</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Student Detail Modal -->
    <div class="modal-overlay" id="studentDetailModal">
        <div class="modal" style="max-width: 500px;">
            <div class="modal-header">
                <h3 class="modal-title">👨‍🎓 Maklumat Pelajar</h3>
                <button class="modal-close" onclick="closeModal('studentDetailModal')">×</button>
            </div>
            <div class="modal-body">
                <div style="text-align: center; margin-bottom: 20px;">
                    <div style="font-size: 3rem; margin-bottom: 10px;">👨‍🎓</div>
                    <h4 id="studentDetailName" style="margin: 0;">-</h4>
                </div>

                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                    <div class="form-group">
                        <label class="form-label">Umur</label>
                        <p id="studentDetailAge" style="margin: 0; font-weight: bold;">-</p>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Tahap</label>
                        <p id="studentDetailLevel" style="margin: 0; font-weight: bold;">-</p>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Nama Penjaga</label>
                        <p id="studentDetailParent" style="margin: 0; font-weight: bold;">-</p>
                    </div>

                    <div class="form-group">
                        <label class="form-label">No. Telefon</label>
                        <p id="studentDetailPhone" style="margin: 0; font-weight: bold;">-</p>
                    </div>
                </div>

                <div class="form-group" style="margin-top: 15px;">
                    <label class="form-label">Subjek Diperlukan</label>
                    <div id="studentDetailSubjects"></div>
                </div>

                <!-- Auto-assign info -->
                <div id="studentDetailExtra"></div>

                <!-- Enrollment date -->
                <div id="studentDetailDate"></div>

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

    <!-- Module Detail Modal -->


    <!-- Setup Password Modal -->
    <div class="modal-overlay" id="setupPasswordModal">
        <div class="modal" style="max-width: 500px;">
            <div class="modal-header">
                <h3 class="modal-title">🔑 Tetapkan Kata Laluan Pelajar</h3>
                <button class="modal-close" onclick="closeModal('setupPasswordModal')">×</button>
            </div>
            <div class="modal-body">
                <p>Pelajar: <strong id="passwordSetupStudentName">-</strong></p>
                <input type="hidden" id="passwordSetupStudentId" value="">
                <input type="hidden" id="pendingEnrollmentId" value="">

                <form id="setupPasswordForm" onsubmit="saveStudentPassword(event)">
                    <div class="form-group">
                        <label class="form-label">Kata Laluan Baru <span class="required">*</span></label>
                        <input type="password" class="form-control" id="studentNewPassword" required
                            placeholder="Minima 6 aksara" minlength="6">
                    </div>

                    <div class="form-group">
                        <label class="form-label">Sahkan Kata Laluan <span class="required">*</span></label>
                        <input type="password" class="form-control" id="studentConfirmPassword" required
                            placeholder="Ulang kata laluan">
                    </div>

                    <div style="margin-top: 20px; display: flex; gap: 10px;">
                        <button type="button" class="btn btn-secondary" style="flex: 1;"
                            onclick="closeModal('setupPasswordModal')">Batal</button>
                        <button type="submit" class="btn btn-primary" style="flex: 1;">🔑 Tetapkan</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Manual Assignment Modal -->
    <div class="modal-overlay" id="assignStudentModal">
        <div class="modal" style="max-width: 600px;">
            <div class="modal-header">
                <h3 class="modal-title">👨‍🎓 Assign Pelajar Secara Manual</h3>
                <button class="modal-close" onclick="closeModal('assignStudentModal')">×</button>
            </div>
            <div class="modal-body">
                <div style="margin-bottom: 20px;">
                    <input type="text" class="form-control" id="searchUnassignedStudent"
                        placeholder="🔍 Cari nama pelajar..." oninput="loadUnassignedStudents()">
                </div>

                <div style="max-height: 300px; overflow-y: auto; border: 1px solid #ddd; border-radius: 8px;">
                    <table class="table">
                        <thead style="position: sticky; top: 0; background: white;">
                            <tr>
                                <th>Nama Pelajar</th>
                                <th>Subjek</th>
                                <th>Status</th>
                                <th>Tindakan</th>
                            </tr>
                        </thead>
                        <tbody id="unassignedStudentsList">
                            <tr>
                                <td colspan="4" class="text-center">Memuatkan...</td>
                            </tr>
                        </tbody>
                    </table>
                </div>

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

    <!-- Quick Assign Modal -->
    <div class="modal-overlay" id="quickAssignModal">
        <div class="modal" style="max-width: 500px;">
            <div class="modal-header">
                <h3 class="modal-title">📝 Assign Pelajar</h3>
                <button class="modal-close" onclick="closeModal('quickAssignModal')">×</button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="quickAssignStudentId" value="">
                <input type="hidden" id="quickAssignSubject" value="">

                <p>Pelajar: <strong id="quickAssignStudentName">-</strong></p>
                <p>Subjek: <span class="badge badge-primary" id="quickAssignSubjectName">-</span></p>

                <div class="form-group" style="margin-top: 20px;">
                    <label class="form-label">Assign kepada:</label>
                    <select class="form-control form-select" id="quickAssignTeacher">
                        <option value="">-- Pilih Guru --</option>
                    </select>
                </div>

                <div style="margin-top: 20px; display: flex; gap: 10px;">
                    <button type="button" class="btn btn-secondary" style="flex: 1;"
                        onclick="closeModal('quickAssignModal')">Batal</button>
                    <button type="button" class="btn btn-primary" style="flex: 1;" onclick="confirmQuickAssign()">✅
                        Assign</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit Enrollment Modal -->
    <div class="modal-overlay" id="editEnrollmentModal">
        <div class="modal" style="max-width: 500px;">
            <div class="modal-header">
                <h3 class="modal-title" id="editEnrollmentTitle">✏️ Edit Pendaftaran</h3>
                <button class="modal-close" onclick="closeModal('editEnrollmentModal')">×</button>
            </div>
            <div class="modal-body">
                <form id="editEnrollmentForm" onsubmit="saveEnrollmentEdit(event)">
                    <input type="hidden" id="editEnrollmentId" value="">

                    <div class="form-group">
                        <label class="form-label">Nama Pelajar</label>
                        <input type="text" class="form-control" id="editEnrollmentName" placeholder="Nama pelajar">
                    </div>

                    <div class="form-group">
                        <label class="form-label">No. Telefon</label>
                        <input type="text" class="form-control" id="editEnrollmentPhone" placeholder="No. telefon">
                    </div>

                    <div class="form-group">
                        <label class="form-label">Subjek</label>
                        <select class="form-control form-select" id="editEnrollmentSubject">
                            <?php foreach ($teacherSubjects as $subject): ?>
                                <option value="<?php echo htmlspecialchars($subject); ?>">
                                    <?php echo htmlspecialchars($subject); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <p class="text-muted"
                        style="font-size: 0.9rem; background: #f8f9fa; padding: 10px; border-radius: 8px;">
                        <strong>Nota:</strong> Untuk mengedit maklumat penuh pelajar, sila edit dari tab "Pelajar Saya".
                    </p>

                    <div style="margin-top: 20px; display: flex; gap: 10px;">
                        <button type="button" class="btn btn-secondary" style="flex: 1;"
                            onclick="closeModal('editEnrollmentModal')">Batal</button>
                        <button type="submit" class="btn btn-primary" style="flex: 1;">💾 Simpan</button>
                    </div>
                </form>
            </div>
        </div>
    </div>



    <script>
        // Update grade level options based on education level
        function updateGradeOptions() {
            var educationLevel = document.getElementById('studentEducationLevel').value;
            var gradeLevel = document.getElementById('studentGradeLevel');
            var options = '<option value="">Pilih Tahun/Tingkatan</option>';

            if (educationLevel === 'Sekolah Rendah') {
                for (var i = 1; i <= 6; i++) {
                    options += '<option value="Tahun ' + i + '">Tahun ' + i + '</option>';
                }
            } else if (educationLevel === 'Sekolah Menengah') {
                options += '<option value="Peralihan">Peralihan</option>';
                for (var i = 1; i <= 5; i++) {
                    options += '<option value="Tingkatan ' + i + '">Tingkatan ' + i + '</option>';
                }
            }

            gradeLevel.innerHTML = options;
        }

        function showAddStudentModalV2() {
            editingStudentId = null; // CRITICAL: Reset editing ID
            openModal('studentModal');
            var studentForm = document.getElementById('studentForm');
            var studentId = document.getElementById('studentId');
            var studentModalTitle = document.getElementById('studentModalTitle');
            if (studentForm) studentForm.reset();
            if (studentId) studentId.value = '';
            if (studentModalTitle) studentModalTitle.textContent = '➕ Tambah Pelajar Baru';

            // Fix: Reset grade options based on empty education level
            document.getElementById('studentEducationLevel').value = '';
            updateGradeOptions();

            // Load subjects
            if (typeof loadSubjectsForStudentForm === 'function') {
                loadSubjectsForStudentForm().catch(function (err) {
                    console.error("Error loading subjects:", err);
                });
            }
        }

        // Module save function

        // ========== STUDENT SELECTION FUNCTIONS ==========
        // Store available students for selection
        var availableStudentsForSelection = {};

        // Toggle student selection visibility
        function toggleStudentSelection(type) {
            var selectionDiv = document.getElementById(type + 'StudentSelection');
            var accessType = document.getElementById(type + 'AccessType');

            if (type === 'forum') {
                // Forum has additional target_audience check
                var targetAudience = document.getElementById('forumTarget').value;
                var studentSelectionContainer = document.getElementById('forumStudentSelectionContainer');

                if (targetAudience === 'specific') {
                    studentSelectionContainer.style.display = 'block';
                    var forumAccessType = document.getElementById('forumAccessType').value;
                    selectionDiv.style.display = forumAccessType === 'specific_students' ? 'block' : 'none';
                } else {
                    studentSelectionContainer.style.display = 'none';
                    selectionDiv.style.display = 'none';
                }
            } else if (accessType) {
                selectionDiv.style.display = accessType.value === 'specific' ? 'block' : 'none';
            }
        }

        // Load students for selection based on subject
        function loadStudentsV2ForSelection(type) {
            var subjectSelect = document.getElementById(type + 'Subject');
            var studentList = document.getElementById(type + 'StudentList');
            var subject = subjectSelect ? subjectSelect.value : '';

            if (!subject) {
                studentList.innerHTML = '<p class="text-muted text-center">Sila pilih subjek terlebih dahulu</p>';
                return;
            }

            // Get students for this teacher and subject
            fetch(API_PATH + '?action=get_teacher_enrollments&status=Approved')
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success && result.enrollments) {
                        // Filter students by subject
                        var students = result.enrollments.filter(function (e) { return e.subject === subject; });

                        if (students.length > 0) {
                            // Store for later use
                            availableStudentsForSelection[type] = students;

                            var html = '';
                            students.forEach(function (s) {
                                html += '<label class="form-check" style="display: block; padding: 8px; border-bottom: 1px solid #eee;">';
                                html += '<input type="checkbox" name="' + type + '_selected_students[]" value="' + s.student_id + '" style="margin-right: 10px;">';
                                html += '<span>' + s.student_name + '</span>';
                                if (s.student_phone) {
                                    html += ' <small style="color: #666;">(' + s.student_phone + ')</small>';
                                }
                                html += '</label>';
                            });
                            studentList.innerHTML = html;
                        } else {
                            studentList.innerHTML = '<p class="text-muted text-center">Tiada pelajar untuk subjek ini</p>';
                            availableStudentsForSelection[type] = [];
                        }
                    } else {
                        studentList.innerHTML = '<p class="text-muted text-center">Tiada pelajar berdaftar</p>';
                        availableStudentsForSelection[type] = [];
                    }
                })
                .catch(function (err) {
                    console.error('Error loading students for selection:', err);
                    studentList.innerHTML = '<p class="text-danger text-center">Ralat memuatkan pelajar</p>';
                });
        }

        // Select all students for a type
        function selectAllStudents(type) {
            var checkboxes = document.querySelectorAll('#' + type + 'StudentList input[type="checkbox"]');
            checkboxes.forEach(function (cb) {
                cb.checked = true;
            });
        }

        // Deselect all students for a type
        function deselectAllStudents(type) {
            var checkboxes = document.querySelectorAll('#' + type + 'StudentList input[type="checkbox"]');
            checkboxes.forEach(function (cb) {
                cb.checked = false;
            });
        }

        // Schedule save function
        // ========== NOTIFICATION FUNCTIONS ==========
        // Toggle notification dropdown
        function toggleNotifications(event) {
            if (event) event.stopPropagation();
            var dropdown = document.getElementById('notificationDropdown');
            if (dropdown) {
                dropdown.classList.toggle('show');
                // Load notifications if dropdown is opened
                if (dropdown.classList.contains('show')) {
                    loadNotificationsV2();
                }
            }
        }

        // ========== NOTIFICATION SYSTEM WITH BELL ANIMATION ==========
        var lastNotificationCount = 0;
        var notificationCheckInterval = null;
        var bellAnimationInterval = null;

        var notificationSystemInitialized = false;

        // Initialize notification system with bell animation
        function initNotificationSystemV2() {
            // Prevent multiple initialization
            if (notificationSystemInitialized) {
                console.log('Notification system already initialized');
                return;
            }
            notificationSystemInitialized = true;

            // First load of notifications
            fetchNotificationsWithAnimation();

            // Clear any existing intervals first
            if (notificationCheckInterval) {
                clearInterval(notificationCheckInterval);
            }

            // Check for new notifications every 10 seconds
            notificationCheckInterval = setInterval(function () {
                fetchNotificationsWithAnimation();
            }, 10000);

            // Check for announcements/forums every 30 seconds
            setInterval(function () {
                checkNewAnnouncementsAndForums();
            }, 30000);

            console.log('Notification system initialized successfully');
        }

        // Fetch notifications and animate bell if new notifications
        function fetchNotificationsWithAnimation() {
            var formData = new FormData();
            formData.append('action', 'get_notifications');

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success && result.notifications) {
                        var currentCount = result.notifications.filter(function (n) {
                            return n.is_read === 'No';
                        }).length;

                        // Animate bell if new notifications
                        if (currentCount > lastNotificationCount && lastNotificationCount > 0) {
                            triggerBellAnimation();
                            playNotificationSound();
                        }

                        lastNotificationCount = currentCount;
                        updateNotificationBadgeCount(result.notifications);

                        // Update dropdown content
                        displayNotificationsInDropdown(result.notifications);
                    }
                })
                .catch(function (err) {
                    console.error('Error fetching notifications:', err);
                });
        }

        // Trigger bell animation
        function triggerBellAnimation() {
            var bellBtn = document.querySelector('.notification-bell-btn');
            if (bellBtn) {
                // Add shake animation
                bellBtn.style.animation = 'none';
                bellBtn.offsetHeight; // Trigger reflow
                bellBtn.style.animation = 'bellShake 0.5s ease-in-out 3';

                // Add pulsing badge
                var badge = document.getElementById('notificationCount');
                if (badge) {
                    badge.style.animation = 'none';
                    badge.offsetHeight;
                    badge.style.animation = 'badgePulse 0.5s ease-in-out 3';
                }

                // Show toast notification
                showNewNotificationToast();
            }
        }

        // Show toast for new notification
        function showNewNotificationToast() {
            var toast = document.createElement('div');
            toast.className = 'new-notification-toast';
            toast.innerHTML = '🔔 Ada notifikasi baharu!';
            toast.style.cssText = 'position: fixed; top: 20px; right: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 15px 25px; border-radius: 10px; box-shadow: 0 4px 15px rgba(0,0,0,0.2); z-index: 10000; animation: slideInRight 0.5s ease-out; font-weight: 600; display: flex; align-items: center; gap: 10px;';
            document.body.appendChild(toast);

            setTimeout(function () {
                toast.style.animation = 'fadeOut 0.5s ease-out forwards';
                setTimeout(function () {
                    if (toast.parentNode) {
                        toast.parentNode.removeChild(toast);
                    }
                }, 500);
            }, 3000);
        }

        // Display notifications in dropdown (called by fetchNotificationsWithAnimation)
        function displayNotificationsInDropdown(notifications) {
            var container = document.getElementById('notificationList');
            if (!container) return;

            if (notifications && notifications.length > 0) {
                var html = '';
                notifications.forEach(function (notif) {
                    var icon = getNotificationIcon(notif.type);
                    var isUnread = notif.is_read === 'No' ? 'unread' : '';
                    html += '<div class="notification-item ' + isUnread + '" onclick="markNotificationRead(' + notif.id + ')">';
                    html += '<div class="notification-icon-wrapper ' + (notif.type || 'info') + '">' + icon + '</div>';
                    html += '<div class="notification-content">';
                    html += '<div class="notification-title">' + (notif.title || 'Notifikasi') + '</div>';
                    html += '<div class="notification-message">' + (notif.message || '') + '</div>';
                    html += '<div class="notification-time">' + formatTimeAgo(notif.created_at) + '</div>';
                    html += '</div>';
                    html += '<button class="notification-delete-btn" onclick="deleteNotification(event, ' + notif.id + ')">×</button>';
                    html += '</div>';
                });
                container.innerHTML = html;
            } else {
                container.innerHTML = '<div class="notification-item empty">' +
                    '<div class="notification-empty-icon">🔔</div>' +
                    '<div class="notification-empty-title">Tiada Notifikasi</div>' +
                    '<div class="notification-empty-message">Anda akan melihat notifikasi di sini</div>' +
                    '</div>';
            }
        }

        // Play notification sound
        function playNotificationSound() {
            try {
                var audioContext = new (window.AudioContext || window.webkitAudioContext)();
                var oscillator = audioContext.createOscillator();
                var gainNode = audioContext.createGain();

                oscillator.connect(gainNode);
                gainNode.connect(audioContext.destination);

                oscillator.type = 'sine';
                oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
                oscillator.frequency.exponentialRampToValueAtTime(400, audioContext.currentTime + 0.3);

                gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
                gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.3);

                oscillator.start(audioContext.currentTime);
                oscillator.stop(audioContext.currentTime + 0.3);
            } catch (e) {
                console.log('Audio not supported');
            }
        }

        // Check for new announcements and forums
        function checkNewAnnouncementsAndForums() {
            // Check for new announcements
            var formData = new FormData();
            formData.append('action', 'get_latest_announcement');

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success && result.announcement) {
                        var lastAnnouncementTime = localStorage.getItem('lastAnnouncementTime');
                        var announcementTime = new Date(result.announcement.created_at).getTime();

                        if (!lastAnnouncementTime || announcementTime > parseInt(lastAnnouncementTime)) {
                            if (lastAnnouncementTime) {
                                // New announcement!
                                triggerBellAnimation();
                                showNewAnnouncementAlert(result.announcement);
                                localStorage.setItem('lastAnnouncementTime', announcementTime);
                            } else {
                                localStorage.setItem('lastAnnouncementTime', announcementTime);
                            }
                        }
                    }
                })
                .catch(function (err) { });

            // Check for new forums
            var formData2 = new FormData();
            formData2.append('action', 'get_teacher_forums');

            fetch(API_PATH, { method: 'POST', body: formData2 })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success && result.forums && result.forums.length > 0) {
                        var lastForumTime = localStorage.getItem('lastForumTime');
                        var latestForumTime = Math.max.apply(null, result.forums.map(function (f) {
                            return new Date(f.created_at).getTime();
                        }));

                        if (!lastForumTime || latestForumTime > parseInt(lastForumTime)) {
                            if (lastForumTime) {
                                // New forum!
                                triggerBellAnimation();
                                showNewForumAlert();
                            }
                            localStorage.setItem('lastForumTime', latestForumTime);
                        }
                    }
                })
                .catch(function (err) { });
        }

        // Show new announcement alert
        function showNewAnnouncementAlert(announcement) {
            var themeColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#667eea';

            var alertDiv = document.createElement('div');
            alertDiv.className = 'new-announcement-alert';
            alertDiv.innerHTML = '<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; border-radius: 15px; box-shadow: 0 10px 30px rgba(0,0,0,0.3); max-width: 400px; animation: slideInUp 0.5s ease-out;">' +
                '<div style="display: flex; align-items: center; gap: 15px; margin-bottom: 15px;">' +
                '<div style="font-size: 2.5rem;">📢</div>' +
                '<div><h3 style="margin: 0; font-size: 1.2rem;">Pengumuman Baharu!</h3>' +
                '<small>' + formatTimeAgo(announcement.created_at) + '</small></div></div>' +
                '<h4 style="margin: 0 0 10px 0;">' + announcement.title + '</h4>' +
                '<p style="margin: 0 0 15px 0; opacity: 0.9;">' + (announcement.content.length > 100 ? announcement.content.substring(0, 100) + '...' : announcement.content) + '</p>' +
                '<button onclick="this.parentElement.parentElement.remove(); switchTabV2(event, \'announcements\'); loadAnnouncementsV2();" style="background: white; color: #667eea; border: none; padding: 10px 20px; border-radius: 8px; cursor: pointer; font-weight: 600; width: 100%;">Lihat Pengumuman</button></div>';
            alertDiv.style.cssText = 'position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 10000;';
            document.body.appendChild(alertDiv);

            setTimeout(function () {
                alertDiv.style.animation = 'fadeOut 0.5s ease-out forwards';
                setTimeout(function () {
                    if (alertDiv.parentNode) alertDiv.parentNode.removeChild(alertDiv);
                }, 500);
            }, 8000);
        }

        // Show new forum alert
        function showNewForumAlert() {
            var themeColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#667eea';

            var alertDiv = document.createElement('div');
            alertDiv.className = 'new-forum-alert';
            alertDiv.innerHTML = '<div style="background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); color: white; padding: 20px; border-radius: 15px; box-shadow: 0 10px 30px rgba(0,0,0,0.3); max-width: 400px; animation: slideInUp 0.5s ease-out;">' +
                '<div style="display: flex; align-items: center; gap: 15px; margin-bottom: 15px;">' +
                '<div style="font-size: 2.5rem;">💬</div>' +
                '<div><h3 style="margin: 0; font-size: 1.2rem;">Forum Baharu!</h3>' +
                '<small>Ada perbincangan baharu</small></div></div>' +
                '<p style="margin: 0 0 15px 0;">Sila semak forum untuk maklumat lanjut.</p>' +
                '<button onclick="this.parentElement.parentElement.remove(); switchTabV2(event, \'forums\'); loadForumV2s();" style="background: white; color: #11998e; border: none; padding: 10px 20px; border-radius: 8px; cursor: pointer; font-weight: 600; width: 100%;">Lihat Forum</button></div>';
            alertDiv.style.cssText = 'position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 10000;';
            document.body.appendChild(alertDiv);

            setTimeout(function () {
                alertDiv.style.animation = 'fadeOut 0.5s ease-out forwards';
                setTimeout(function () {
                    if (alertDiv.parentNode) alertDiv.parentNode.removeChild(alertDiv);
                }, 500);
            }, 8000);
        }

        // Format time ago
        function formatTimeAgo(dateString) {
            if (!dateString) return '';
            var date = new Date(dateString);
            var now = new Date();
            var diff = now - date;

            if (diff < 60000) return 'Baru sahaja';
            if (diff < 3600000) return Math.floor(diff / 60000) + ' minit lalu';
            if (diff < 86400000) return Math.floor(diff / 3600000) + ' jam lalu';
            return Math.floor(diff / 86400000) + ' hari lalu';
        }

        // Load and display notifications
        function loadNotificationsV2() {
            console.log('loadNotificationsV2 called');
            console.log('API_PATH:', API_PATH);

            var container = document.getElementById('notificationList');
            if (!container) {
                console.error('Container notificationList not found!');
                return;
            }

            // Show loading state
            container.innerHTML = '<div class="notification-item empty"><div class="notification-empty-icon">⏳</div><div class="notification-empty-title">Memuatkan...</div></div>';

            // Use POST method with FormData
            var formData = new FormData();
            formData.append('action', 'get_notifications');

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) {
                    console.log('Response status:', response.status);
                    return response.json();
                })
                .then(function (result) {
                    console.log('Notifications result:', result);

                    if (result.success) {
                        if (result.notifications && result.notifications.length > 0) {
                            var html = '';
                            result.notifications.forEach(function (notif) {
                                var icon = getNotificationIcon(notif.type);
                                var isUnread = notif.is_read === 'No' ? 'unread' : '';
                                html += '<div class="notification-item ' + isUnread + '" onclick="markNotificationRead(' + notif.id + ')">';
                                html += '<div class="notification-icon-wrapper ' + (notif.type || 'info') + '">' + icon + '</div>';
                                html += '<div class="notification-content">';
                                html += '<div class="notification-title">' + (notif.title || 'Notifikasi') + '</div>';
                                html += '<div class="notification-message">' + (notif.message || '') + '</div>';
                                html += '<div class="notification-time">' + formatDateTime(notif.created_at) + '</div>';
                                html += '</div>';
                                html += '<button class="notification-delete-btn" onclick="deleteNotification(event, ' + notif.id + ')">×</button>';
                                html += '</div>';
                            });
                            container.innerHTML = html;
                        } else {
                            container.innerHTML = '<div class="notification-item empty">' +
                                '<div class="notification-empty-icon">🔔</div>' +
                                '<div class="notification-empty-title">Tiada Notifikasi</div>' +
                                '<div class="notification-empty-message">Anda akan melihat notifikasi di sini</div>' +
                                '</div>';
                        }
                        updateNotificationBadgeCount(result.notifications || []);
                    } else {
                        console.error('API returned error:', result.message);
                        container.innerHTML = '<div class="notification-item empty">' +
                            '<div class="notification-empty-icon">❌</div>' +
                            '<div class="notification-empty-title">Ralat</div>' +
                            '<div class="notification-empty-message">' + (result.message || 'Gagal memuatkan notifikasi') + '</div>' +
                            '</div>';
                    }
                })
                .catch(function (err) {
                    console.error('Error loading notifications:', err);
                    container.innerHTML = '<div class="notification-item empty">' +
                        '<div class="notification-empty-icon">❌</div>' +
                        '<div class="notification-empty-title">Ralat Sambungan</div>' +
                        '<div class="notification-empty-message">Sila cuba lagi</div>' +
                        '</div>';
                });
        }

        // Get notification icon based on type
        function getNotificationIcon(type) {
            var icons = {
                'success': '✅',
                'error': '❌',
                'warning': '⚠️',
                'info': 'ℹ️',
                'enrollment': '📝',
                'announcement': '📢',
                'forum': '💬',
                'assignment': '📚',
                'reminder': '⏰'
            };
            return icons[type] || '🔔';
        }

        // Update notification badge count
        function updateNotificationBadgeCount(notifications) {
            var badge = document.getElementById('notificationCount');
            if (badge && notifications) {
                var unreadCount = notifications.filter(function (n) { return n.is_read === 'No'; }).length;
                if (unreadCount > 0) {
                    badge.textContent = unreadCount > 99 ? '99+' : unreadCount;
                    badge.style.display = 'flex';
                } else {
                    badge.style.display = 'none';
                }
            }
        }

        // Mark notification as read
        function markNotificationRead(id) {
            var formData = new FormData();
            formData.append('action', 'mark_notification_read');
            formData.append('id', id);

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success) {
                        loadNotificationsV2(); // Reload to update UI
                    }
                })
                .catch(function (err) {
                    console.error('Error marking notification as read:', err);
                });
        }

        // Mark all notifications as read
        function markAllNotificationsReadV2() {
            var formData = new FormData();
            formData.append('action', 'mark_notification_read');
            formData.append('id', 0); // 0 means mark all as read

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success) {
                        showNotificationV2('Semua notifikasi telah dibaca', 'success');
                        loadNotificationsV2();
                    }
                })
                .catch(function (err) {
                    console.error('Error marking all notifications as read:', err);
                });
        }

        // Delete single notification
        function deleteNotification(event, id) {
            if (event) event.stopPropagation();

            var formData = new FormData();
            formData.append('action', 'delete_notification');
            formData.append('id', id);

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success) {
                        loadNotificationsV2();
                    }
                })
                .catch(function (err) {
                    console.error('Error deleting notification:', err);
                });
        }

        // Delete all notifications
        function deleteAllNotificationsV2() {
            if (confirm('Adakah anda pasti mahu memadam semua notifikasi?')) {
                var formData = new FormData();
                formData.append('action', 'delete_all_notifications');

                fetch(API_PATH, { method: 'POST', body: formData })
                    .then(function (response) { return response.json(); })
                    .then(function (result) {
                        if (result.success) {
                            showNotificationV2('Semua notifikasi telah dipadam', 'success');
                            loadNotificationsV2();
                        }
                    })
                    .catch(function (err) {
                        console.error('Error deleting all notifications:', err);
                    });
            }
        }

        // Toggle notification sound
        var notificationSoundEnabled = true;
        function toggleNotificationSound() {
            notificationSoundEnabled = !notificationSoundEnabled;
            var toggle = document.getElementById('soundToggle');
            if (toggle) {
                toggle.textContent = notificationSoundEnabled ? '🔊' : '🔇';
                toggle.classList.toggle('active', notificationSoundEnabled);
            }
            showNotificationV2(notificationSoundEnabled ? 'Bunyi notifikasi diaktifkan' : 'Bunyi notifikasi dinyahaktifkan', 'info');
        }

        // Toggle auto-refresh for notifications
        var notificationAutoRefresh = true;
        function toggleAutoRefresh(element) {
            notificationAutoRefresh = !notificationAutoRefresh;
            element.classList.toggle('active', notificationAutoRefresh);
            showNotificationV2(notificationAutoRefresh ? 'Auto-refresh diaktifkan' : 'Auto-refresh dinyahaktifkan', 'info');
        }

        // Add event listener to close notification dropdown when clicking outside
        document.addEventListener('click', function (event) {
            var dropdown = document.getElementById('notificationDropdown');
            var bell = document.querySelector('.notification-bell-container');
            if (dropdown && dropdown.classList.contains('show')) {
                if (bell && !bell.contains(event.target)) {
                    dropdown.classList.remove('show');
                }
            }
        });

        // ========== STATUS MANAGEMENT FUNCTIONS ==========

        /**
         * Update teacher status (Active/Inactive)
         * Called when the toggle switch is clicked in Settings
         */
        function updateMyStatus(isActive) {
            var status = isActive ? 'Active' : 'Inactive';
            var statusText = isActive ? 'Aktif' : 'Tidak Aktif';

            // Show confirmation if switching to inactive
            if (!isActive) {
                const themeColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#667eea';

                Swal.fire({
                    title: 'Tukar ke Tidak Aktif?',
                    html: 'Adakah anda pasti ingin menukar status kepada <strong>Tidak Aktif</strong>?<br><br>' +
                        '<div style="background: #fff3cd; padding: 10px; border-radius: 8px; border-left: 4px solid #ffc107;">' +
                        '<strong>⚠️ Peringatan:</strong><br>' +
                        '• Anda tidak akan menerima pelajar baharu<br>' +
                        '• Pelajar sedia ada tidak akan terjejas<br>' +
                        '• Anda masih boleh log masuk dan mengurus pelajar sedia ada' +
                        '</div>',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: themeColor,
                    cancelButtonColor: '#6c757d',
                    confirmButtonText: 'Ya, Tukar',
                    cancelButtonText: 'Batal',
                    borderRadius: '15px',
                    reverseButtons: true
                }).then((result) => {
                    if (result.isConfirmed) {
                        // Proceed with status update
                        sendStatusUpdate(status);
                    } else {
                        // Revert toggle to active
                        document.getElementById('statusToggle').checked = true;
                        updateStatusUI(true);
                    }
                });
            } else {
                // Switching to active - no confirmation needed
                sendStatusUpdate(status);
            }
        }

        /**
         * Send status update to API
         */
        function sendStatusUpdate(status) {
            var formData = new FormData();
            formData.append('action', 'update_teacher_status');
            formData.append('status', status);

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success) {
                        // Update UI based on response
                        var isActive = result.status === 'Active';
                        updateStatusUI(isActive);
                        showNotificationV2(result.message, 'success');
                    } else {
                        // Revert toggle on error
                        var toggle = document.getElementById('statusToggle');
                        toggle.checked = !toggle.checked;
                        updateStatusUI(toggle.checked);
                        showNotificationV2(result.message, 'error');
                    }
                })
                .catch(function (err) {
                    console.error('Error updating status:', err);
                    // Revert toggle on error
                    var toggle = document.getElementById('statusToggle');
                    toggle.checked = !toggle.checked;
                    updateStatusUI(toggle.checked);
                    showNotificationV2('Ralat sambungan', 'error');
                });
        }

        /**
         * Update the status UI elements
         */
        function updateStatusUI(isActive) {
            var statusIcon = document.getElementById('currentStatusIcon');
            var statusText = document.getElementById('currentStatusText');
            var statusDescription = document.getElementById('statusDescription');
            var statusWarning = document.getElementById('statusWarning');
            var toggleSlider = document.querySelector('#statusToggle + .toggle-slider');
            var toggleKnob = document.querySelector('#statusToggle + .toggle-slider .toggle-knob');

            if (isActive) {
                statusIcon.textContent = '🟢';
                statusText.textContent = 'Aktif';
                statusDescription.textContent = 'Boleh menerima pelajar baharu';
                statusWarning.style.display = 'none';

                // Update toggle colors
                if (toggleSlider) {
                    toggleSlider.style.backgroundColor = '#28a745';
                }
                if (toggleKnob) {
                    toggleKnob.style.transform = 'translateX(30px)';
                }
            } else {
                statusIcon.textContent = '⚪';
                statusText.textContent = 'Tidak Aktif';
                statusDescription.textContent = 'Tidak menerima pelajar baharu (cuti/luang)';
                statusWarning.style.display = 'block';

                // Update toggle colors
                if (toggleSlider) {
                    toggleSlider.style.backgroundColor = '#6c757d';
                }
                if (toggleKnob) {
                    toggleKnob.style.transform = 'translateX(0)';
                }
            }
        }

        // ========== ENROLLMENT FUNCTIONS ==========

        // Sync student data to fix missing enrollments
        function syncStudentData() {
            const themeColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#667eea';

            Swal.fire({
                title: '🔄 Sync Data Pelajar',
                text: 'Ini akan menyelaraskan semua data pelajar dan enrollment. Adakah anda ingin teruskan?',
                icon: 'info',
                showCancelButton: true,
                confirmButtonColor: themeColor,
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Ya, Sync Sekarang',
                cancelButtonText: 'Batal',
                borderRadius: '15px',
                reverseButtons: true
            }).then((result) => {
                if (result.isConfirmed) {
                    // Show loading state
                    Swal.fire({
                        title: '⏳ Sedang Menyelaraskan...',
                        text: 'Sila tunggu sebentar',
                        allowOutsideClick: false,
                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });

                    // First, sync all teacher students
                    fetch(API_PATH + '?action=sync_all_teacher_students')
                        .then(function (response) { return response.json(); })
                        .then(function (syncResult) {
                            // Then reload all data
                            loadStudentsV2();
                            loadEnrollmentsV2();
                            loadTaughtStudentsV2();
                            return syncResult;
                        })
                        .then(function (syncResult) {
                            Swal.close();

                            if (syncResult.success) {
                                Swal.fire({
                                    title: '✅ Berjaya Diselaraskan!',
                                    html: syncResult.message + '<br><br><strong>' + (syncResult.synced_count || 0) + '</strong> pelajar telah diselaraskan.',
                                    icon: 'success',
                                    confirmButtonColor: themeColor,
                                    confirmButtonText: 'OK',
                                    borderRadius: '15px'
                                });
                            } else {
                                showNotificationV2(syncResult.message || 'Ralat semasa penyelarasan', 'error');
                            }
                        })
                        .catch(function (err) {
                            Swal.close();
                            console.error('Error syncing student data:', err);
                            showNotificationV2('Ralat sambungan semasa sync', 'error');
                        });
                }
            });
        }

        function loadEnrollmentsV2() {
            var filterEl = document.getElementById('enrollmentFilter');
            var status = filterEl ? filterEl.value : 'Pending';
            fetch(API_PATH + '?action=get_teacher_enrollments&status=' + status)
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success) {
                        displayEnrollments(result.enrollments);
                        var pendingCountEl = document.getElementById('pendingCount');
                        var approvedCountEl = document.getElementById('approvedCount');
                        var rejectedCountEl = document.getElementById('rejectedCount');

                        // NEW Realtime WoW: Show Toast if new applications arrived
                        var oldPending = parseInt(pendingCountEl ? pendingCountEl.textContent : 0) || 0;
                        var newPending = result.stats.pending || 0;

                        if (newPending > oldPending && typeof Swal !== 'undefined') {
                            const Toast = Swal.mixin({
                                toast: true,
                                position: 'top-end',
                                showConfirmButton: false,
                                timer: 3000,
                                timerProgressBar: true
                            });
                            Toast.fire({
                                icon: 'info',
                                title: '🔔 Permohonan Baru Diterima!',
                                text: 'Terdapat ' + (newPending - oldPending) + ' permohonan baru pelajar.'
                            });
                        }

                        if (pendingCountEl) pendingCountEl.textContent = newPending;
                        if (approvedCountEl) approvedCountEl.textContent = result.stats.approved || 0;
                        if (rejectedCountEl) rejectedCountEl.textContent = result.stats.rejected || 0;

                        // Update dashboard stat too
                        var dashPending = document.getElementById('dashboardPendingEnrollments');
                        if (dashPending) dashPending.textContent = newPending;

                        // Update badge
                        var badge = document.getElementById('pendingBadge');
                        if (badge) {
                            if (result.stats.pending > 0) {
                                badge.textContent = result.stats.pending;
                                badge.style.display = 'inline-block';
                            } else {
                                badge.style.display = 'none';
                            }
                        }
                    }
                })
                .catch(function (err) {
                    console.error('Error loading enrollments:', err);
                    var enrollmentsListEl = document.getElementById('enrollmentsList');
                    if (enrollmentsListEl) {
                        enrollmentsListEl.innerHTML = '<tr><td colspan="7" class="text-center text-danger">Ralat memuatkan</td></tr>';
                    }
                });
        }

        function displayEnrollments(enrollments) {
            var tbody = document.getElementById('enrollmentsList');
            if (!tbody) return; // Skip if element doesn't exist
            if (enrollments && enrollments.length > 0) {
                var html = '';
                enrollments.forEach(function (e, i) {
                    var statusClass = '';
                    var statusBadge = '';
                    if (e.status === 'Pending') {
                        statusClass = 'warning';
                        statusBadge = '⏳ Menunggu';
                    } else if (e.status === 'Approved') {
                        statusClass = 'success';
                        statusBadge = '✅ Diluluskan';
                    } else {
                        statusClass = 'danger';
                        statusBadge = '❌ Ditolak';
                    }

                    var actionButtons = '';
                    if (e.status === 'Pending') {
                        actionButtons = '<button class="btn btn-success btn-sm btn-icon" onclick="approveEnrollment(' + e.id + ')" title="Luluskan">✅</button> ' +
                            '<button class="btn btn-secondary btn-sm btn-icon" onclick="editEnrollment(' + e.id + ', \'' + (e.student_name || '').replace(/'/g, "\\'") + '\', \'' + (e.student_phone || '').replace(/'/g, "\\'") + '\', \'' + (e.subject || '').replace(/'/g, "\\'") + '\')" title="Edit">✏️</button> ' +
                            '<button class="btn btn-danger btn-sm btn-icon" onclick="showRejectModal(' + e.id + ')" title="Tolak">❌</button>';
                    } else {
                        actionButtons = '<button class="btn btn-secondary btn-sm btn-icon" onclick="editEnrollment(' + e.id + ', \'' + (e.student_name || '').replace(/'/g, "\\'") + '\', \'' + (e.student_phone || '').replace(/'/g, "\\'") + '\', \'' + (e.subject || '').replace(/'/g, "\\'") + '\')" title="Edit">✏️</button>';
                    }

                    html += '<tr><td>' + (i + 1) + '</td><td><strong>' + e.student_name + '</strong><br><small>' + (e.parent_guardian_name || '') + '</small></td><td><span class="badge badge-primary">' + e.subject + '</span></td><td>' + (e.student_phone || '-') + '</td><td><span class="badge badge-' + statusClass + '">' + statusBadge + '</span></td><td>' + (e.enrolled_at ? formatDate(e.enrolled_at) : '-') + '</td><td>' + actionButtons + '</td></tr>';
                });
                tbody.innerHTML = html;
            } else {
                tbody.innerHTML = '<tr><td colspan="7" class="text-center">Tiada pendaftaran</td></tr>';
            }
        }

        // Edit enrollment function
        var editingEnrollmentId = null;
        var editingEnrollmentData = null;

        function editEnrollment(id, name, phone, subject) {
            editingEnrollmentId = id;
            editingEnrollmentData = { name: name, phone: phone, subject: subject };

            document.getElementById('editEnrollmentTitle').textContent = '✏️ Edit Pendaftaran: ' + name;
            document.getElementById('editEnrollmentName').value = name;
            document.getElementById('editEnrollmentPhone').value = phone;
            document.getElementById('editEnrollmentSubject').value = subject;

            openModal('editEnrollmentModal');
        }

        function saveEnrollmentEdit(event) {
            event.preventDefault();

            var enrollmentId = editingEnrollmentId;
            var newName = document.getElementById('editEnrollmentName').value;
            var newPhone = document.getElementById('editEnrollmentPhone').value;
            var newSubject = document.getElementById('editEnrollmentSubject').value;

            var formData = new FormData();
            formData.append('action', 'update_enrollment');
            formData.append('enrollment_id', enrollmentId);
            formData.append('student_name', newName);
            formData.append('student_phone', newPhone);
            formData.append('subject', newSubject);

            var btn = document.querySelector('#editEnrollmentForm button[type="submit"]');
            var originalText = btn.innerHTML;
            btn.disabled = true;
            btn.innerHTML = '⏳ Sedang memproses...';

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success) {
                        showNotificationV2('Maklumat pendaftaran berjaya dikemaskini!', 'success');
                        closeModal('editEnrollmentModal');
                        loadEnrollmentsV2(); // Reload enrollments list
                    } else {
                        showNotificationV2(result.message, 'error');
                    }
                })
                .catch(function (err) {
                    console.error('Error updating enrollment:', err);
                    showNotificationV2('Ralat sambungan', 'error');
                })
                .finally(function () {
                    btn.disabled = false;
                    btn.innerHTML = originalText;
                });
        }

        function approveEnrollment(id) {
            // Get portal theme color
            const themeColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#667eea';

            // First, check if student needs password setup
            fetch(API_PATH + '?action=get_teacher_enrollments&status=Pending')
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success && result.enrollments) {
                        var enrollment = result.enrollments.find(function (e) { return e.id === id; });
                        if (enrollment) {
                            // Show dialog: Choose to setup password first or approve directly
                            Swal.fire({
                                title: 'Luluskan Pendaftaran',
                                html: '<p>Pelajar: <strong>' + enrollment.student_name + '</strong></p>' +
                                    '<p>Subjek: <span class="badge badge-primary">' + enrollment.subject + '</span></p>' +
                                    '<div style="background: #fff3cd; padding: 15px; border-radius: 8px; margin-top: 15px; border-left: 4px solid #ffc107;">' +
                                    '<p style="margin: 0;"><strong>⚠️ PENTING:</strong> Guru WAJIB tetapkan kata laluan baharu untuk pelajar sebelum diluluskan.</p>' +
                                    '</div>',
                                icon: 'warning',
                                showCancelButton: true,
                                confirmButtonColor: themeColor,
                                cancelButtonColor: '#6c757d',
                                confirmButtonText: '🔑 Tetap Kata Laluan & Luluskan',
                                cancelButtonText: 'Batal',
                                borderRadius: '15px',
                                reverseButtons: true
                            }).then((result) => {
                                if (result.isConfirmed) {
                                    // Open password setup modal first, then approve after password is set
                                    setupStudentPasswordAndApprove(enrollment.student_id, enrollment.student_name, id);
                                }
                            });
                        }
                    }
                })
                .catch(function (err) {
                    console.error('Error checking enrollment:', err);
                    // Fallback: Just approve directly
                    Swal.fire({
                        title: 'Luluskan Pendaftaran?',
                        text: 'Pelajar ini akan diluluskan untuk menyertai kelas anda.',
                        icon: 'question',
                        showCancelButton: true,
                        confirmButtonColor: themeColor,
                        cancelButtonColor: '#6c757d',
                        confirmButtonText: 'Ya, Lulus',
                        cancelButtonText: 'Batal',
                        borderRadius: '15px',
                        reverseButtons: true
                    }).then((result) => {
                        if (result.isConfirmed) {
                            var formData = new FormData();
                            formData.append('action', 'approve_student');
                            formData.append('enrollment_id', id);

                            fetch(API_PATH, { method: 'POST', body: formData })
                                .then(function (response) { return response.json(); })
                                .then(function (res) {
                                    if (res.success) {
                                        showNotificationV2('Pelajar berjaya diluluskan', 'success');
                                        loadEnrollmentsV2();
                                        loadStudentsV2();
                                    } else {
                                        showNotificationV2(res.message, 'error');
                                    }
                                })
                                .catch(function (err) {
                                    showNotificationV2('Ralat sambungan', 'error');
                                });
                        }
                    });
                });
        }

        // Setup password and then approve enrollment
        function setupStudentPasswordAndApprove(studentId, studentName, enrollmentId) {
            document.getElementById('passwordSetupStudentId').value = studentId;
            document.getElementById('passwordSetupStudentName').textContent = studentName;
            document.getElementById('pendingEnrollmentId').value = enrollmentId;

            openModal('setupPasswordModal');
        }

        // Override saveStudentPassword to also approve enrollment
        var originalSaveStudentPassword = null;

        document.addEventListener('DOMContentLoaded', function () {
            // Store original function and extend it
            originalSaveStudentPassword = saveStudentPassword;
            saveStudentPassword = function (event) {
                event.preventDefault();

                var newPassword = document.getElementById('studentNewPassword').value;
                var confirmPassword = document.getElementById('studentConfirmPassword').value;
                var studentId = document.getElementById('passwordSetupStudentId').value;
                var pendingEnrollmentId = document.getElementById('pendingEnrollmentId').value;

                if (newPassword !== confirmPassword) {
                    showNotificationV2('Kata laluan tidak sepadan!', 'error');
                    return;
                }

                if (newPassword.length < 6) {
                    showNotificationV2('Kata laluan minima 6 aksara!', 'error');
                    return;
                }

                var formData = new FormData();
                formData.append('action', 'setup_student_password');
                formData.append('student_id', studentId);
                formData.append('new_password', newPassword);

                var btn = document.querySelector('#setupPasswordForm button[type="submit"]');
                var originalText = btn.innerHTML;
                btn.disabled = true;
                btn.innerHTML = '⏳ Sedang memproses...';

                fetch(API_PATH, { method: 'POST', body: formData })
                    .then(function (response) { return response.json(); })
                    .then(function (result) {
                        if (result.success) {
                            showNotificationV2('Kata laluan pelajar berjaya ditetapkan!', 'success');
                            closeModal('setupPasswordModal');
                            document.getElementById('setupPasswordForm').reset();
                            document.getElementById('pendingEnrollmentId').value = '';

                            // If there's a pending enrollment, approve it
                            if (pendingEnrollmentId) {
                                approveEnrollmentAfterPassword(pendingEnrollmentId);
                            }
                        } else {
                            showNotificationV2(result.message, 'error');
                        }
                    })
                    .catch(function (err) {
                        showNotificationV2('Ralat sambungan', 'error');
                    })
                    .finally(function () {
                        btn.disabled = false;
                        btn.innerHTML = originalText;
                    });
            };
        });

        function approveEnrollmentAfterPassword(enrollmentId) {
            const themeColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#667eea';

            Swal.fire({
                title: 'Kata Laluan Ditetapkan!',
                text: 'Seterusnya, inginkah anda meluluskan pendaftaran pelajar ini?',
                icon: 'success',
                showCancelButton: true,
                confirmButtonColor: themeColor,
                cancelButtonColor: '#6c757d',
                confirmButtonText: '✅ Ya, Luluskan',
                cancelButtonText: 'Tidak, Tunggu',
                borderRadius: '15px'
            }).then((result) => {
                if (result.isConfirmed) {
                    var formData = new FormData();
                    formData.append('action', 'approve_student');
                    formData.append('enrollment_id', enrollmentId);

                    fetch(API_PATH, { method: 'POST', body: formData })
                        .then(function (response) { return response.json(); })
                        .then(function (res) {
                            if (res.success) {
                                showNotificationV2('Pelajar berjaya diluluskan! 🎉', 'success');
                                loadEnrollmentsV2();
                                loadStudentsV2();
                                loadPendingPasswordStudentsV2();
                            } else {
                                showNotificationV2(res.message, 'error');
                            }
                        })
                        .catch(function (err) {
                            showNotificationV2('Ralat sambungan', 'error');
                        });
                }
            });
        }

        function showRejectModal(id) {
            document.getElementById('rejectEnrollmentId').value = id;
            document.getElementById('rejectReason').value = '';
            openModal('rejectModal');
        }

        function confirmReject() {
            var id = document.getElementById('rejectEnrollmentId').value;
            var reason = document.getElementById('rejectReason').value;

            // Show confirmation dialog with option for manual assignment
            const themeColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#667eea';

            Swal.fire({
                title: 'Tolak Pendaftaran?',
                html: 'Pelajar ini akan ditolak. Apakah tindakan yang ingin anda buat?<br><br>' +
                    '<div style="display: flex; gap: 10px;">' +
                    '<button type="button" id="btnRejectOnly" class="btn btn-danger" style="flex: 1; padding: 10px;">❌ Tolak Sahaja</button>' +
                    '<button type="button" id="btnRejectAndAssign" class="btn btn-primary" style="flex: 1; padding: 10px;">👤 Tolak & Assign Manual</button>' +
                    '</div>',
                icon: 'warning',
                showCancelButton: true,
                showConfirmV2Button: false,
                cancelButtonText: 'Batal',
                cancelButtonColor: '#6c757d',
                borderRadius: '15px',
                didOpen: function () {
                    // Handle reject only button
                    var btnRejectOnly = document.getElementById('btnRejectOnly');
                    if (btnRejectOnly) {
                        btnRejectOnly.onclick = function () {
                            performReject(id, reason, false);
                        };
                    }

                    // Handle reject and assign button
                    var btnRejectAndAssign = document.getElementById('btnRejectAndAssign');
                    if (btnRejectAndAssign) {
                        btnRejectAndAssign.onclick = function () {
                            performReject(id, reason, true);
                        };
                    }
                }
            });
        }

        function performReject(id, reason, openAssignModal) {
            const themeColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#667eea';

            var formData = new FormData();
            formData.append('action', 'reject_student');
            formData.append('enrollment_id', id);
            formData.append('reason', reason);

            closeModal('rejectModal');

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success) {
                        if (openAssignModal) {
                            // Show assign student modal
                            loadUnassignedStudents();
                            openModal('assignStudentModal');
                        } else {
                            // Just show rejection result
                            Swal.fire({
                                title: 'Ditolak',
                                text: result.message,
                                icon: 'warning',
                                confirmButtonColor: themeColor,
                                confirmButtonText: 'OK',
                                borderRadius: '15px'
                            });
                        }
                        if (typeof loadStudentManagementData === "function") { loadStudentManagementData(); } else { loadEnrollmentsV2(); }
                    } else {
                        showNotificationV2(result.message, 'error');
                    }
                })
                .catch(function (err) {
                    showNotificationV2('Ralat sambungan', 'error');
                });
        }

        // ========== MANUAL ASSIGNMENT FUNCTIONS ==========
        function showAssignStudentModal() {
            loadUnassignedStudents();
            openModal('assignStudentModal');
        }

        function loadUnassignedStudents() {
            var searchTerm = document.getElementById('searchUnassignedStudent').value.toLowerCase();
            var tbody = document.getElementById('unassignedStudentsList');

            // Get subject requests (students waiting for teachers)
            fetch(API_PATH + '?action=get_subject_requests')
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success && result.requests) {
                        var requests = result.requests;

                        // Filter by search term
                        if (searchTerm) {
                            requests = requests.filter(function (r) {
                                return (r.student_name || '').toLowerCase().includes(searchTerm);
                            });
                        }

                        if (requests.length > 0) {
                            var html = '';
                            requests.forEach(function (r) {
                                html += '<tr>';
                                html += '<td><strong>' + r.student_name + '</strong>';
                                if (r.student_phone) {
                                    html += '<br><small>' + r.student_phone + '</small>';
                                }
                                html += '</td>';
                                html += '<td><span class="badge badge-primary">' + r.requested_subject + '</span></td>';
                                html += '<td><span class="badge badge-warning">Menunggu</span></td>';
                                html += '<td><button class="btn btn-primary btn-sm" onclick="quickAssignStudent(' + r.student_id + ', \'' + (r.student_name || '').replace(/'/g, "\\'") + '\', \'' + (r.requested_subject || '').replace(/'/g, "\\'") + '\')">👤 Assign</button></td>';
                                html += '</tr>';
                            });
                            tbody.innerHTML = html;
                        } else {
                            tbody.innerHTML = '<tr><td colspan="4" class="text-center">' +
                                (searchTerm ? 'Tiada pelajar yang sepadan' : 'Tiada pelajar menunggu assignment') +
                                '</td></tr>';
                        }
                    } else {
                        tbody.innerHTML = '<tr><td colspan="4" class="text-center">Tiada pelajar menunggu assignment</td></tr>';
                    }
                })
                .catch(function (err) {
                    console.error('Error loading unassigned students:', err);
                    tbody.innerHTML = '<tr><td colspan="4" class="text-center text-danger">Ralat memuatkan</td></tr>';
                });
        }

        function quickAssignStudent(studentId, studentName, subject) {
            document.getElementById('quickAssignStudentId').value = studentId;
            document.getElementById('quickAssignStudentName').textContent = studentName;
            document.getElementById('quickAssignSubject').value = subject;
            document.getElementById('quickAssignSubjectName').textContent = subject;

            // Load available teachers for this subject
            fetch(API_PATH + '?action=get_available_teachers&subject=' + encodeURIComponent(subject))
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    var select = document.getElementById('quickAssignTeacher');
                    var options = '<option value="">-- Pilih Guru --</option>';

                    if (result.success && result.teachers && result.teachers.length > 0) {
                        result.teachers.forEach(function (t) {
                            var capacityInfo = t.current_students + '/' + t.max_students;
                            options += '<option value="' + t.id + '">' + t.full_name + ' (' + capacityInfo + ')</option>';
                        });
                    } else {
                        options += '<option value="">Tiada guru tersedia</option>';
                    }
                    select.innerHTML = options;
                })
                .catch(function (err) {
                    console.error('Error loading teachers:', err);
                    document.getElementById('quickAssignTeacher').innerHTML = '<option value="">Ralat memuatkan</option>';
                });

            openModal('quickAssignModal');
        }

        function confirmQuickAssign() {
            var studentId = document.getElementById('quickAssignStudentId').value;
            var subject = document.getElementById('quickAssignSubject').value;
            var teacherId = document.getElementById('quickAssignTeacher').value;

            if (!teacherId) {
                showNotificationV2('Sila pilih guru', 'warning');
                return;
            }

            // Create manual enrollment
            var formData = new FormData();
            formData.append('action', 'teacher_register_student');
            formData.append('student_id', studentId);
            formData.append('subject', subject);
            formData.append('teacher_id', teacherId);

            var btn = document.querySelector('#quickAssignModal .btn-primary');
            var originalText = btn.innerHTML;
            btn.disabled = true;
            btn.innerHTML = '⏳ Sedang memproses...';

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success) {
                        showNotificationV2('Pelajar berjaya diassign!', 'success');
                        closeModal('quickAssignModal');
                        loadUnassignedStudents();
                        loadEnrollmentsV2();
                    } else {
                        showNotificationV2(result.message, 'error');
                    }
                })
                .catch(function (err) {
                    showNotificationV2('Ralat sambungan', 'error');
                })
                .finally(function () {
                    btn.disabled = false;
                    btn.innerHTML = originalText;
                });
        }

        function formatDate(dateString) {
            if (!dateString) return '-';
            var date = new Date(dateString);
            var months = ['Jan', 'Feb', 'Mac', 'Apr', 'Mei', 'Jun', 'Jul', 'Ogos', 'Sep', 'Okt', 'Nov', 'Dis'];
            return date.getDate() + ' ' + months[date.getMonth()] + ' ' + date.getFullYear();
        }

        // ========== NOTIFICATION FUNCTIONS ==========
        var notificationsData = [];
        var notificationInterval = null;
        var notificationSoundEnabled = true;
        var autoRefreshEnabled = true;
        var lastNotificationCount = 0;

        // Notification sound effect
        function playNotificationSound() {
            if (notificationSoundEnabled && 'AudioContext' in window) {
                try {
                    var audioContext = new AudioContext();
                    var oscillator = audioContext.createOscillator();
                    var gainNode = audioContext.createGain();

                    oscillator.connect(gainNode);
                    gainNode.connect(audioContext.destination);

                    oscillator.frequency.value = 800;
                    oscillator.type = 'sine';
                    gainNode.gain.setValueAtTime(0.1, audioContext.currentTime);
                    gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.3);

                    oscillator.start(audioContext.currentTime);
                    oscillator.stop(audioContext.currentTime + 0.3);
                } catch (e) {
                    console.log('Notification sound not supported');
                }
            }
        }

        // Load notifications from server
        function loadNotificationsV2() {
            fetch(API_PATH + '?action=get_teacher_notifications')
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success && result.notifications) {
                        notificationsData = result.notifications;
                        var count = notificationsData.filter(function (n) { return !n.is_read; }).length;

                        var badge = document.getElementById('notificationCount');
                        if (count > 0) {
                            badge.textContent = count;
                            badge.style.display = 'inline-block';
                            if (count > lastNotificationCount) {
                                playNotificationSound();
                            }
                        } else {
                            badge.style.display = 'none';
                        }
                        lastNotificationCount = count;
                        displayNotifications();
                    }
                })
                .catch(function (err) {
                    console.error('Error loading notifications:', err);
                });
        }

        // Display notifications in dropdown
        function displayNotifications() {
            var container = document.getElementById('notificationList');

            if (notificationsData.length === 0) {
                container.innerHTML = '<div class="notification-item empty"><div class="notification-empty-icon">🔔</div><div class="notification-empty-title">Tiada Notifikasi</div><div class="notification-empty-message">Anda akan melihat notifikasi di sini</div></div>';
                return;
            }

            var html = '';
            notificationsData.slice(0, 10).forEach(function (n) {
                var icon = n.type === 'enrollment' ? '📝' : (n.type === 'forum' ? '💬' : (n.type === 'announcement' ? '📢' : '🔔'));
                var readClass = n.is_read ? '' : 'unread';

                html += '<div class="notification-item ' + readClass + '" onclick="markNotificationRead(' + n.id + ')">';
                html += '<div class="notification-icon">' + icon + '</div>';
                html += '<div class="notification-content">';
                html += '<div class="notification-title">' + n.title + '</div>';
                html += '<div class="notification-message">' + n.message + '</div>';
                html += '<div class="notification-time">' + formatDate(n.created_at) + '</div>';
                html += '</div></div>';
            });

            container.innerHTML = html;
        }

        // Mark notification as read
        function markNotificationRead(id) {
            var formData = new FormData();
            formData.append('action', 'mark_notification_read');
            formData.append('id', id);

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success) {
                        loadNotificationsV2();
                    }
                })
                .catch(function (err) {
                    console.error('Error marking notification read:', err);
                });
        }

        // Mark all notifications as read
        function markAllNotificationsReadV2() {
            var formData = new FormData();
            formData.append('action', 'mark_all_notifications_read');

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success) {
                        showNotificationV2('Semua notifikasi telah dibaca', 'success');
                        loadNotificationsV2();
                    }
                })
                .catch(function (err) {
                    console.error('Error marking all notifications read:', err);
                });
        }

        // Delete all notifications
        function deleteAllNotificationsV2() {
            // Get portal theme color
            const themeColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#667eea';

            Swal.fire({
                title: 'Padam Semua Notifikasi?',
                text: 'Semua notifikasi akan dipadamkan secara kekal. Tindakan ini tidak boleh dibatalkan.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#dc3545',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Ya, Padam Semua',
                cancelButtonText: 'Batal',
                borderRadius: '15px',
                reverseButtons: true
            }).then((result) => {
                if (result.isConfirmed) {
                    var formData = new FormData();
                    formData.append('action', 'delete_all_notifications');

                    fetch(API_PATH, { method: 'POST', body: formData })
                        .then(function (response) { return response.json(); })
                        .then(function (result) {
                            if (result.success) {
                                showNotificationV2('Semua notifikasi telah dipadam', 'success');
                                loadNotificationsV2();
                            } else {
                                showNotificationV2(result.message, 'error');
                            }
                        })
                        .catch(function (err) {
                            console.error('Error deleting all notifications:', err);
                            showNotificationV2('Ralat sambungan', 'error');
                        });
                }
            });
        }

        function toggleNotifications() {
            const dropdown = document.getElementById('notificationDropdown');
            if (dropdown) {
                dropdown.classList.toggle('show');
                dropdown.classList.toggle('active');

                // Close dropdown when clicking outside
                if (dropdown.classList.contains('show')) {
                    setTimeout(() => {
                        document.addEventListener('click', closeNotificationsOutside);
                    }, 10);
                }
            }
        }
        function closeNotificationsOutside(event) {
            const dropdown = document.getElementById('notificationDropdown');
            const bell = document.querySelector('.notification-bell-btn');
            if (dropdown && bell && !dropdown.contains(event.target) && !bell.contains(event.target)) {
                dropdown.classList.remove('show');
                dropdown.classList.remove('active');
                document.removeEventListener('click', closeNotificationsOutside);
            }
        }

        // Close dropdown when clicking close button or on a notification
        function closeNotificationDropdown() {
            const dropdown = document.getElementById('notificationDropdown');
            if (dropdown) {
                dropdown.classList.remove('show');
                dropdown.classList.remove('active');
            }
        }
        // Toggle notification sound
        function toggleNotificationSound() {
            notificationSoundEnabled = !notificationSoundEnabled;
            var toggle = document.getElementById('soundToggle');
            toggle.textContent = notificationSoundEnabled ? '🔊' : '🔇';
            toggle.classList.toggle('active', notificationSoundEnabled);
            localStorage.setItem('notificationSound', notificationSoundEnabled ? 'enabled' : 'disabled');
        }

        // Toggle auto-refresh
        function toggleAutoRefresh(element) {
            autoRefreshEnabled = !autoRefreshEnabled;
            element.classList.toggle('active', autoRefreshEnabled);

            if (autoRefreshEnabled) {
                notificationInterval = setInterval(loadNotificationsV2, 30000);
            } else {
                if (notificationInterval) {
                    clearInterval(notificationInterval);
                    notificationInterval = null;
                }
            }

            localStorage.setItem('autoRefresh', autoRefreshEnabled ? 'enabled' : 'disabled');
        }

        // Load maintenance logs
        function loadMaintenanceLogsV2() {
            fetch(API_PATH + '?action=get_maintenance_logs')
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    var tbody = document.getElementById('maintenanceLogsList');
                    if (result.success && result.logs && result.logs.length > 0) {
                        var html = '';
                        result.logs.forEach(function (log, i) {
                            var statusBadge = log.status === 'Completed' ? 'badge-success' : (log.status === 'In Progress' ? 'badge-warning' : 'badge-danger');
                            html += '<tr><td>' + (i + 1) + '</td><td>' + (log.activity || '-') + '</td><td><span class="badge ' + statusBadge + '">' + (log.status || '-') + '</span></td><td>' + formatDate(log.created_at) + '</td></tr>';
                        });
                        tbody.innerHTML = html;
                    } else {
                        tbody.innerHTML = '<tr><td colspan="4" class="text-center">Tiada log penyelenggaraan</td></tr>';
                    }
                })
                .catch(function (err) {
                    console.error('Error loading maintenance logs:', err);
                    document.getElementById('maintenanceLogsList').innerHTML = '<tr><td colspan="4" class="text-center text-danger">Ralat memuatkan log</td></tr>';
                });
        }

        // Load pending password students
        function loadPendingPasswordStudentsV2() {
            fetch(API_PATH + '?action=get_pending_password_students')
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    var tbody = document.getElementById('pendingPasswordList');
                    if (result.success && result.students && result.students.length > 0) {
                        var html = '';
                        result.students.forEach(function (s, i) {
                            html += '<tr><td>' + (i + 1) + '</td><td><strong>' + s.full_name + '</strong></td><td>' + (s.phone || '-') + '</td><td><span class="badge badge-primary">' + (s.subjects || '-') + '</span></td><td><button class="btn btn-primary btn-sm" onclick="setupStudentPassword(' + s.id + ', \'' + (s.full_name || '').replace(/'/g, "\\'") + '\')">🔑 Tetapkan</button></td></tr>';
                        });
                        tbody.innerHTML = html;
                    } else {
                        tbody.innerHTML = '<tr><td colspan="5" class="text-center">Tiada pelajar menunggu kata laluan</td></tr>';
                    }
                })
                .catch(function (err) {
                    console.error('Error loading pending password students:', err);
                    document.getElementById('pendingPasswordList').innerHTML = '<tr><td colspan="5" class="text-center text-danger">Ralat memuatkan</td></tr>';
                });
        }

        function setupStudentPassword(studentId, studentName) {
            document.getElementById('passwordSetupStudentId').value = studentId;
            document.getElementById('passwordSetupStudentName').textContent = studentName;
            document.getElementById('pendingEnrollmentId').value = '';
            openModal('setupPasswordModal');
        }

        // Save student password
        function saveStudentPassword(event) {
            event.preventDefault();

            var newPassword = document.getElementById('studentNewPassword').value;
            var confirmPassword = document.getElementById('studentConfirmPassword').value;
            var studentId = document.getElementById('passwordSetupStudentId').value;

            if (newPassword !== confirmPassword) {
                showNotificationV2('Kata laluan tidak sepadan!', 'error');
                return;
            }

            if (newPassword.length < 6) {
                showNotificationV2('Kata laluan minima 6 aksara!', 'error');
                return;
            }

            var formData = new FormData();
            formData.append('action', 'setup_student_password');
            formData.append('student_id', studentId);
            formData.append('new_password', newPassword);

            var btn = document.querySelector('#setupPasswordForm button[type="submit"]');
            var originalText = btn.innerHTML;
            btn.disabled = true;
            btn.innerHTML = '⏳ Sedang memproses...';

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success) {
                        showNotificationV2('Kata laluan pelajar berjaya ditetapkan!', 'success');
                        closeModal('setupPasswordModal');
                        document.getElementById('setupPasswordForm').reset();
                        loadPendingPasswordStudentsV2();
                    } else {
                        showNotificationV2(result.message, 'error');
                    }
                })
                .catch(function (err) {
                    showNotificationV2('Ralat sambungan', 'error');
                })
                .finally(function () {
                    btn.disabled = false;
                    btn.innerHTML = originalText;
                });
        }

        // Close modals when clicking outside
        document.addEventListener('click', function (event) {
            var modals = document.querySelectorAll('.modal-overlay');
            modals.forEach(function (modal) {
                if (event.target === modal) {
                    closeModal(modal.id);
                }
            });
        });

        // Keyboard shortcuts
        document.addEventListener('keydown', function (event) {
            if (event.key === 'Escape') {
                var openModals = document.querySelectorAll('.modal-overlay.active');
                openModals.forEach(function (modal) {
                    closeModal(modal.id);
                });
            }
        });







        // Load notifications from server
        function loadNotificationsV2() {
            if (!autoRefreshEnabled) return;

            fetch(API_PATH + '?action=get_teacher_notifications')
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success && result.notifications) {
                        notificationsData = result.notifications;
                        var count = notificationsData.filter(function (n) { return !n.is_read; }).length;

                        // Update badge
                        var badge = document.getElementById('notificationCount');
                        if (count > 0) {
                            badge.textContent = count;
                            badge.style.display = 'inline-block';

                            // Play sound if count increased
                            if (count > lastNotificationCount) {
                                playNotificationSound();
                            }
                        } else {
                            badge.style.display = 'none';
                        }
                        lastNotificationCount = count;

                        // Update dropdown list
                        displayNotifications();

                        // Update forum badge
                        var forumBadge = document.getElementById('forumBadge');
                        var unreadForum = notificationsData.filter(function (n) { return n.type === 'forum' && !n.is_read; }).length;
                        if (unreadForum > 0) {
                            forumBadge.textContent = unreadForum;
                            forumBadge.style.display = 'inline-block';
                        } else {
                            forumBadge.style.display = 'none';
                        }

                        // Update announcements badge
                        var announcementsBadge = document.getElementById('announcementsBadge');
                        var unreadAnnouncements = notificationsData.filter(function (n) { return n.type === 'announcement' && !n.is_read; }).length;
                        if (unreadAnnouncements > 0) {
                            announcementsBadge.textContent = unreadAnnouncements;
                            announcementsBadge.style.display = 'inline-block';
                        } else {
                            announcementsBadge.style.display = 'none';
                        }
                    }
                })
                .catch(function (err) {
                    console.error('Error loading notifications:', err);
                });
        }

        // Display notifications in dropdown
        function displayNotifications() {
            var container = document.getElementById('notificationList');

            if (notificationsData.length === 0) {
                container.innerHTML = '<div class="notification-item empty"><div class="notification-empty-icon">🔔</div><div class="notification-empty-title">Tiada Notifikasi</div><div class="notification-empty-message">Anda akan melihat notifikasi di sini</div></div>';
                return;
            }

            var html = '';
            notificationsData.slice(0, 10).forEach(function (n) {
                var icon = n.type === 'enrollment' ? '📝' : (n.type === 'forum' ? '💬' : (n.type === 'announcement' ? '📢' : '🔔'));
                var readClass = n.is_read ? '' : 'unread';

                html += '<div class="notification-item ' + readClass + '" onclick="markNotificationRead(' + n.id + ')">';
                html += '<div class="notification-icon">' + icon + '</div>';
                html += '<div class="notification-content">';
                html += '<div class="notification-title">' + n.title + '</div>';
                html += '<div class="notification-message">' + n.message + '</div>';
                html += '<div class="notification-time">' + formatDate(n.created_at) + '</div>';
                html += '</div></div>';
            });

            container.innerHTML = html;
        }

        // Mark notification as read
        function markNotificationRead(id) {
            var formData = new FormData();
            formData.append('action', 'mark_notification_read');
            formData.append('id', id);

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success) {
                        loadNotificationsV2();
                    }
                })
                .catch(function (err) {
                    console.error('Error marking notification read:', err);
                });
        }

        // Mark all notifications as read
        function markAllNotificationsReadV2() {
            var formData = new FormData();
            formData.append('action', 'mark_all_notifications_read');

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success) {
                        showNotificationV2('Semua notifikasi telah dibaca', 'success');
                        loadNotificationsV2();
                    }
                })
                .catch(function (err) {
                    console.error('Error marking all notifications read:', err);
                });
        }

        // Toggle notification dropdown
        function toggleNotifications() {
            var dropdown = document.getElementById('notificationDropdown');
            dropdown.classList.toggle('show');

            // Load notifications when dropdown opens
            if (dropdown.classList.contains('show')) {
                loadNotificationsV2();
            }
        }

        // Toggle notification sound
        function toggleNotificationSound() {
            notificationSoundEnabled = !notificationSoundEnabled;
            var toggle = document.getElementById('soundToggle');
            toggle.textContent = notificationSoundEnabled ? '🔊' : '🔇';
            toggle.classList.toggle('active', notificationSoundEnabled);

            // Save preference
            localStorage.setItem('notificationSound', notificationSoundEnabled ? 'enabled' : 'disabled');
        }

        // Toggle auto-refresh
        function toggleAutoRefresh(element) {
            autoRefreshEnabled = !autoRefreshEnabled;
            element.classList.toggle('active', autoRefreshEnabled);

            if (autoRefreshEnabled) {
                // Start auto-refresh
                notificationInterval = setInterval(loadNotificationsV2, 30000);
            } else {
                // Stop auto-refresh
                if (notificationInterval) {
                    clearInterval(notificationInterval);
                    notificationInterval = null;
                }
            }

            // Save preference
            localStorage.setItem('autoRefresh', autoRefreshEnabled ? 'enabled' : 'disabled');
        }

        // ========== MAINTENANCE LOGS FUNCTIONS ==========
        function loadMaintenanceLogsV2() {
            fetch(API_PATH + '?action=get_maintenance_logs')
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    var tbody = document.getElementById('maintenanceLogsList');
                    if (result.success && result.logs && result.logs.length > 0) {
                        var html = '';
                        result.logs.forEach(function (log, i) {
                            var statusBadge = log.status === 'Completed' ? 'badge-success' : (log.status === 'In Progress' ? 'badge-warning' : 'badge-danger');
                            html += '<tr><td>' + (i + 1) + '</td><td>' + (log.activity || '-') + '</td><td><span class="badge ' + statusBadge + '">' + (log.status || '-') + '</span></td><td>' + formatDate(log.created_at) + '</td></tr>';
                        });
                        tbody.innerHTML = html;
                    } else {
                        tbody.innerHTML = '<tr><td colspan="4" class="text-center">Tiada log penyelenggaraan</td></tr>';
                    }
                })
                .catch(function (err) {
                    console.error('Error loading maintenance logs:', err);
                    document.getElementById('maintenanceLogsList').innerHTML = '<tr><td colspan="4" class="text-center text-danger">Ralat memuatkan log</td></tr>';
                });
        }



        // Save student password
        function saveStudentPassword(event) {
            event.preventDefault();

            var newPassword = document.getElementById('studentNewPassword').value;
            var confirmPassword = document.getElementById('studentConfirmPassword').value;
            var studentId = document.getElementById('passwordSetupStudentId').value;

            if (newPassword !== confirmPassword) {
                showNotificationV2('Kata laluan tidak sepadan!', 'error');
                return;
            }

            if (newPassword.length < 6) {
                showNotificationV2('Kata laluan minima 6 aksara!', 'error');
                return;
            }

            var formData = new FormData();
            formData.append('action', 'setup_student_password');
            formData.append('student_id', studentId);
            formData.append('new_password', newPassword);

            var btn = document.querySelector('#setupPasswordForm button[type="submit"]');
            var originalText = btn.innerHTML;
            btn.disabled = true;
            btn.innerHTML = '⏳ Sedang memproses...';

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success) {
                        showNotificationV2('Kata laluan pelajar berjaya ditetapkan!', 'success');
                        closeModal('setupPasswordModal');
                        document.getElementById('setupPasswordForm').reset();
                        loadPendingPasswordStudentsV2();
                    } else {
                        showNotificationV2(result.message, 'error');
                    }
                })
                .catch(function (err) {
                    showNotificationV2('Ralat sambungan', 'error');
                })
                .finally(function () {
                    btn.disabled = false;
                    btn.innerHTML = originalText;
                });
        }

        // Close modals when clicking outside
        document.addEventListener('click', function (event) {
            var modals = document.querySelectorAll('.modal-overlay');
            modals.forEach(function (modal) {
                if (event.target === modal) {
                    closeModal(modal.id);
                }
            });
        });

        // Keyboard shortcuts
        document.addEventListener('keydown', function (event) {
            // Escape to close modals
            if (event.key === 'Escape') {
                var openModals = document.querySelectorAll('.modal-overlay.active');
                openModals.forEach(function (modal) {
                    closeModal(modal.id);
                });
            }
        });







        // Toggle notification sound
        function toggleNotificationSound() {
            notificationSoundEnabled = !notificationSoundEnabled;
            var toggle = document.getElementById('soundToggle');
            if (notificationSoundEnabled) {
                toggle.classList.add('active');
                toggle.innerHTML = '🔊';
                localStorage.setItem('notificationSound', 'true');
            } else {
                toggle.classList.remove('active');
                toggle.innerHTML = '🔇';
                localStorage.setItem('notificationSound', 'false');
            }
        }

        // Toggle auto-refresh
        function toggleAutoRefresh(element) {
            autoRefreshEnabled = !autoRefreshEnabled;
            element.classList.toggle('active');

            if (autoRefreshEnabled) {
                notificationInterval = setInterval(loadNotificationsV2, 30000);
            } else {
                clearInterval(notificationInterval);
            }
        }

        // Load notifications
        function loadNotificationsV2() {
            fetch(API_PATH + '?action=get_teacher_enrollments&status=Pending')
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success && result.stats) {
                        var pendingCount = result.stats.pending || 0;
                        var badge = document.getElementById('notificationCount');
                        var bellBtn = document.getElementById('notificationBellBtn');

                        if (pendingCount > 0) {
                            badge.textContent = pendingCount;
                            badge.style.display = 'flex';

                            // Play sound if count increased
                            if (pendingCount > lastNotificationCount && lastNotificationCount > 0) {
                                playNotificationSound();
                            }
                            lastNotificationCount = pendingCount;

                            // Update badge color
                            bellBtn.classList.add('has-notifications');
                        } else {
                            badge.style.display = 'none';
                            bellBtn.classList.remove('has-notifications');
                        }
                    }
                })
                .catch(function (err) {
                    console.error('Error loading notifications:', err);
                });
        }
        function togglePasswordFields() {
            var checkbox = document.getElementById('useDefaultPassword');
            var passField = document.getElementById('openPoolStudentPassword');
            var confirmField = document.getElementById('openPoolStudentConfirmPassword');

            if (checkbox && passField && confirmField) {
                if (checkbox.checked) {
                    passField.value = 'student123';
                    confirmField.value = 'student123';
                    passField.disabled = true;
                    confirmField.disabled = true;
                } else {
                    passField.value = '';
                    confirmField.value = '';
                    passField.disabled = false;
                    confirmField.disabled = false;
                }
            }
        }


        // Toggle notifications dropdown
        function toggleNotifications() {
            var dropdown = document.getElementById('notificationDropdown');
            dropdown.classList.toggle('show');
            loadNotificationsV2();
        }

        // Mark all notifications as read
        function markAllNotificationsReadV2() {
            lastNotificationCount = 0;
            document.getElementById('notificationCount').style.display = 'none';
            document.getElementById('notificationBellBtn').classList.remove('has-notifications');
            showNotificationV2('Semua notifikasi telah dibaca', 'success');
        }

        // Close dropdown when clicking outside
        document.addEventListener('click', function (event) {
            var dropdown = document.getElementById('notificationDropdown');
            var bell = document.querySelector('.notification-bell-container');
            if (dropdown && bell && !bell.contains(event.target)) {
                dropdown.classList.remove('show');
            }
        });

        // ========== MAINTENANCE LOGS FUNCTIONS ==========
        function loadMaintenanceLogsV2() {
            fetch(API_PATH + '?action=get_maintenance_logs')
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    var tbody = document.getElementById('maintenanceLogsList');
                    if (result.success && result.logs && result.logs.length > 0) {
                        var html = '';
                        result.logs.forEach(function (log, i) {
                            var statusBadge = log.status === 'Active' ?
                                '<span class="badge badge-success">Aktif</span>' :
                                '<span class="badge badge-secondary">' + log.status + '</span>';

                            html += '<tr><td>' + (i + 1) + '</td><td>' + log.activity + '</td><td>' + statusBadge + '</td><td>' + formatDate(log.created_at) + '</td></tr>';
                        });
                        tbody.innerHTML = html;
                    } else {
                        tbody.innerHTML = '<tr><td colspan="4" class="text-center">Tiada log penyelenggaraan</td></tr>';
                    }
                })
                .catch(function (err) {
                    console.error('Error loading maintenance logs:', err);
                    document.getElementById('maintenanceLogsList').innerHTML = '<tr><td colspan="4" class="text-center text-danger">Ralat memuatkan</td></tr>';
                });
        }

        // ========== PENDING PASSWORD STUDENTS FUNCTIONS ==========
        function loadPendingPasswordStudentsV2() {
            fetch(API_PATH + '?action=get_pending_password_students')
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    var tbody = document.getElementById('pendingPasswordList');
                    if (result.success && result.students && result.students.length > 0) {
                        var html = '';
                        result.students.forEach(function (s, i) {
                            html += '<tr>';
                            html += '<td>' + (i + 1) + '</td>';
                            html += '<td><strong>' + s.full_name + '</strong>';
                            if (s.phone) {
                                html += '<br><small>' + s.phone + '</small>';
                            }
                            html += '</td>';
                            html += '<td>' + (s.phone || '-') + '</td>';
                            html += '<td><span class="badge badge-primary">' + (s.subject || 'Lain-lain') + '</span></td>';
                            html += '<td><button class="btn btn-primary btn-sm" onclick="setupPasswordForStudent(' + s.id + ', \'' + (s.full_name || '').replace(/'/g, "\\'") + '\')">🔑 Tetapkan</button></td>';
                            html += '</tr>';
                        });
                        tbody.innerHTML = html;
                    } else {
                        tbody.innerHTML = '<tr><td colspan="5" class="text-center">Tiada pelajar menunggu kata laluan</td></tr>';
                    }
                })
                .catch(function (err) {
                    console.error('Error loading pending password students:', err);
                    document.getElementById('pendingPasswordList').innerHTML = '<tr><td colspan="5" class="text-center text-danger">Ralat memuatkan</td></tr>';
                });
        }

        function setupPasswordForStudent(studentId, studentName) {
            var setupIdEl = document.getElementById('passwordSetupStudentId');
            var setupNameEl = document.getElementById('passwordSetupStudentName');
            var pendingEl = document.getElementById('pendingEnrollmentId');

            if (setupIdEl) setupIdEl.value = studentId;
            if (setupNameEl) setupNameEl.textContent = studentName;
            if (pendingEl) pendingEl.value = '';

            openModal('setupPasswordModal');
        }

        function saveStudentPassword(event) {
            event.preventDefault();

            var newPassword El = document.getElementById('studentNewPassword');
            var confirmPasswordEl = document.getElementById('studentConfirmPassword');
            var studentIdEl = document.getElementById('passwordSetupStudentId');
            var pendingEnrollmentIdEl = document.getElementById('pendingEnrollmentId');

            var newPassword = newPasswordEl ? newPasswordEl.value : '';
            var confirmPassword = confirmPasswordEl ? confirmPasswordEl.value : '';
            var studentId = studentIdEl ? studentIdEl.value : '';
            var pendingEnrollmentId = pendingEnrollmentIdEl ? pendingEnrollmentIdEl.value : '';

            if (newPassword !== confirmPassword) {
                showNotificationV2('Kata laluan tidak sepadan!', 'error');
                return;
            }

            if (newPassword.length < 6) {
                showNotificationV2('Kata laluan minima 6 aksara!', 'error');
                return;
            }

            var formData = new FormData();
            formData.append('action', 'setup_student_password');
            formData.append('student_id', studentId);
            formData.append('new_password', newPassword);

            var btn = document.querySelector('#setupPasswordForm button[type="submit"]');
            var originalText = btn.innerHTML;
            btn.disabled = true;
            btn.innerHTML = '⏳ Sedang memproses...';

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success) {
                        showNotificationV2('Kata laluan pelajar berjaya ditetapkan!', 'success');
                        closeModal('setupPasswordModal');
                        var setupForm = document.getElementById('setupPasswordForm');
                        var pendingEl = document.getElementById('pendingEnrollmentId');
                        if (setupForm) setupForm.reset();
                        if (pendingEl) pendingEl.value = '';

                        // If there's a pending enrollment, approve it
                        if (pendingEnrollmentId) {
                            approveEnrollmentAfterPassword(pendingEnrollmentId);
                        } else {
                            // Reload pending password students list
                            loadPendingPasswordStudentsV2();
                        }
                    } else {
                        showNotificationV2(result.message, 'error');
                    }
                })
                .catch(function (err) {
                    showNotificationV2('Ralat sambungan', 'error');
                })
                .finally(function () {
                    btn.disabled = false;
                    btn.innerHTML = originalText;
                });
        }

        // Close modals on escape key
        document.addEventListener('keydown', function (event) {
            if (event.key === 'Escape') {
                document.querySelectorAll('.modal-overlay.active').forEach(function (modal) {
                    var modalId = modal.id;
                    closeModal(modalId);
                });
            }
        });

        // Close modals when clicking on overlay
        document.addEventListener('click', function (event) {
            if (event.target.classList.contains('modal-overlay')) {
                var modalId = event.target.id;
                closeModal(modalId);
            }
        });

        clearInterval(notificationInterval);


        localStorage.setItem('notificationAutoRefresh', autoRefreshEnabled.toString());


        document.addEventListener('DOMContentLoaded', function () {
            // Load saved settings
            var savedSound = localStorage.getItem('notificationSound');
            var savedAutoRefresh = localStorage.getItem('notificationAutoRefresh');

            if (savedSound === 'false') {
                notificationSoundEnabled = false;
                var soundToggle = document.getElementById('soundToggle');
                if (soundToggle) {
                    soundToggle.classList.remove('active');
                    soundToggle.innerHTML = '🔇';
                }
            }

            if (savedAutoRefresh === 'false') {
                autoRefreshEnabled = false;
            }

            // Load notifications on start
            loadNotificationsV2();

            // Check for new notifications every 30 seconds
            if (autoRefreshEnabled) {
                notificationInterval = setInterval(loadNotificationsV2, 30000);
            }

            // Close notification dropdown when clicking outside
            document.addEventListener('click', function (e) {
                var dropdown = document.getElementById('notificationDropdown');
                var bellBtn = document.getElementById('notificationBellBtn');
                if (dropdown && !dropdown.contains(e.target) && (!bellBtn || !bellBtn.contains(e.target))) {
                    dropdown.classList.remove('show');
                }
            });
        });

        function loadNotificationsV2() {
            fetch(API_PATH + '?action=get_notifications')
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success && result.notifications) {
                        var newCount = result.notifications.filter(function (n) { return n.is_read !== 'Yes'; }).length;

                        // Play sound if new notifications arrived
                        if (notificationSoundEnabled && newCount > lastNotificationCount && lastNotificationCount > 0) {
                            playNotificationSound();
                        }
                        lastNotificationCount = newCount;

                        notificationsData = result.notifications;
                        displayNotifications();

                        // Update badge count
                        var badge = document.getElementById('notificationCount');
                        var bellBtn = document.getElementById('notificationBellBtn');

                        if (newCount > 0) {
                            badge.textContent = newCount > 99 ? '99+' : newCount;
                            badge.style.display = 'flex';
                            badge.classList.add('pulse');
                            bellBtn.classList.add('has-unread');
                        } else {
                            badge.style.display = 'none';
                            badge.classList.remove('pulse');
                            bellBtn.classList.remove('has-unread');
                        }
                    }
                })
                .catch(function (err) {
                    console.error('Error loading notifications:', err);
                });
        }

        function displayNotifications() {
            var container = document.getElementById('notificationList');

            if (notificationsData && notificationsData.length > 0) {
                var html = '';
                notificationsData.slice(0, 10).forEach(function (n) {
                    var isRead = n.is_read === 'Yes' ? '' : 'unread';
                    var iconClass = getNotificationClass(n.type);
                    var icon = getNotificationIcon(n.type);

                    html += '<div class="notification-item ' + isRead + '" onclick="handleNotificationClick(' + n.id + ', \'' + n.type + '\')">';
                    html += '<div class="notification-icon-wrapper ' + iconClass + '">' + icon + '</div>';
                    html += '<div class="notification-content">';
                    html += '<div class="notification-title">' + n.title + '</div>';
                    html += '<div class="notification-message">' + n.message + '</div>';
                    html += '<div class="notification-time">⏰ ' + formatDateTime(n.created_at) + '</div>';
                    html += '</div>';
                    html += '<button class="notification-delete-btn" onclick="event.stopPropagation(); deleteNotification(' + n.id + ')" title="Padam">✕</button>';
                    html += '</div>';
                });
                container.innerHTML = html;
            } else {
                container.innerHTML = '<div class="notification-item empty">' +
                    '<div class="notification-empty-icon">🔔</div>' +
                    '<div class="notification-empty-title">Tiada Notifikasi</div>' +
                    '<div class="notification-empty-message">Anda akan melihat notifikasi di sini</div>' +
                    '</div>';
            }
        }

        function getNotificationClass(type) {
            switch (type) {
                case 'success': return 'success';
                case 'error': return 'error';
                case 'warning': return 'warning';
                case 'announcement':
                case 'forum':
                case 'student':
                case 'enrollment': return 'info';
                default: return 'default';
            }
        }

        function handleNotificationClick(id, type) {
            markNotificationRead(id, type);
        }

        function deleteNotification(id) {
            // Get portal theme color
            const themeColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#667eea';

            Swal.fire({
                title: 'Padam Notifikasi?',
                text: "Notifikasi ini akan dipadamkan secara kekal.",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: themeColor,
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Ya, Padam',
                cancelButtonText: 'Batal',
                borderRadius: '15px',
                reverseButtons: true,
                focusCancel: true
            }).then((result) => {
                if (result.isConfirmed) {
                    var formData = new FormData();
                    formData.append('action', 'delete_notification');
                    formData.append('id', id);

                    fetch(API_PATH, { method: 'POST', body: formData })
                        .then(function (response) { return response.json(); })
                        .then(function (result) {
                            if (result.success) {
                                Swal.fire({
                                    title: '✅ Berjaya!',
                                    text: 'Notifikasi telah dipadam.',
                                    icon: 'success',
                                    confirmButtonColor: themeColor,
                                    borderRadius: '15px'
                                });
                                loadNotificationsV2();
                            } else {
                                Swal.fire({
                                    title: 'Ralat!',
                                    text: result.message,
                                    icon: 'error',
                                    confirmButtonColor: themeColor,
                                    borderRadius: '15px'
                                });
                            }
                        })
                        .catch(function (err) {
                            Swal.fire({
                                title: 'Ralat Sambungan!',
                                text: 'Sila cuba lagi.',
                                icon: 'error',
                                confirmButtonColor: themeColor,
                                borderRadius: '15px'
                            });
                        });
                }
            });
        }

        function getNotificationIcon(type) {
            switch (type) {
                case 'success': return '✅';
                case 'error': return '❌';
                case 'warning': return '⚠️';
                case 'announcement': return '📢';
                case 'forum': return '💬';
                case 'student': return '👨‍🎓';
                case 'enrollment': return '📝';
                default: return '🔔';
            }
        }

        function formatDateTime(dateString) {
            if (!dateString) return '';
            var date = new Date(dateString);
            var now = new Date();
            var diff = now - date;

            // Less than 1 hour
            if (diff < 3600000) {
                var mins = Math.floor(diff / 60000);
                return mins + ' minit lalu';
            }
            // Less than 24 hours
            if (diff < 86400000) {
                var hours = Math.floor(diff / 3600000);
                return hours + ' jam lalu';
            }
            // Otherwise
            var days = ['Ahad', 'Isnin', 'Selasa', 'Rabu', 'Khamis', 'Jumaat', 'Sabtu'];
            var months = ['Jan', 'Feb', 'Mac', 'Apr', 'Mei', 'Jun', 'Jul', 'Ogos', 'Sep', 'Okt', 'Nov', 'Dis'];
            return days[date.getDay()] + ', ' + date.getDate() + ' ' + months[date.getMonth()] + ' ' + date.getFullYear() + ' ' +
                String(date.getHours()).padStart(2, '0') + ':' + String(date.getMinutes()).padStart(2, '0');
        }

        function toggleNotifications() {
            var dropdown = document.getElementById('notificationDropdown');
            console.log('toggleNotifications called, dropdown:', dropdown);
            if (dropdown) {
                dropdown.classList.toggle('show');
                console.log('Dropdown show class:', dropdown.classList.contains('show'));
                if (dropdown.classList.contains('show')) {
                    loadNotificationsV2();
                }
            } else {
                console.error('Notification dropdown not found!');
            }
        }

        function markNotificationRead(id, type) {
            var formData = new FormData();
            formData.append('action', 'mark_notification_read');
            formData.append('id', id);

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    loadNotificationsV2();
                    // Handle specific notification actions
                    if (type === 'announcement') {
                        switchTabV2(null, 'announcements');
                    } else if (type === 'forum') {
                        switchTabV2(null, 'forum');
                    } else if (type === 'enrollment' || type === 'student') {
                        switchTabV2(null, 'enrollments');
                    }
                    document.getElementById('notificationDropdown').classList.remove('show');
                });
        }

        function markAllNotificationsReadV2() {
            var formData = new FormData();
            formData.append('action', 'mark_notification_read');
            formData.append('id', 0); // 0 means mark all as read

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    loadNotificationsV2();
                    showToast('success', 'Berjaya!', 'Semua notifikasi telah dibaca');
                });
        }

        // Toast Notification Function
        function showToast(type, title, message, duration) {
            if (!duration) duration = 4000;
            var container = document.getElementById('toastContainer');
            if (!container) {
                container = document.createElement('div');
                container.id = 'toastContainer';
                container.className = 'toast-container';
                document.body.appendChild(container);
            }

            var iconMap = {
                "success": "✓",
                "error": "✕",
                "warning": "⚠",
                "info": "ℹ"
            };

            var toastId = 'toast_' + Date.now();
            var toastHtml = '<div id="' + toastId + '" class="toast-notification ' + type + '">' +
                '<div class="toast-icon">' + iconMap[type] + '</div>' +
                '<div class="toast-content">' +
                '<div class="toast-title">' + title + '</div>' +
                '<div class="toast-message">' + message + '</div>' +
                '</div>' +
                '<button class="toast-close" onclick="closeToast(\'' + toastId + '\')">✕</button>' +
                '<div class="toast-progress" style="animation-duration: ' + duration + 'ms;"></div>' +
                '</div>';

            container.insertAdjacentHTML('beforeend', toastHtml);

            setTimeout(function () {
                var toast = document.getElementById(toastId);
                if (toast) {
                    toast.classList.add('show');
                }
            }, 10);

            setTimeout(function () {
                closeToast(toastId);
            }, duration);
        }

        function closeToast(toastId) {
            var toast = document.getElementById(toastId);
            if (toast) {
                toast.classList.remove('show');
                setTimeout(function () {
                    toast.remove();
                }, 400);
            }
        }

        // Alert for student password setup
        function showPasswordSetupAlert(studentName, username) {
            Swal.fire({
                title: '📝 Pelajar Baru',
                html: '<p>Pelajar <strong>' + studentName + '</strong> telah berjaya didaftarkan!</p>' +
                    '<p style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-top: 15px;">' +
                    '<strong>Username:</strong> ' + username + '<br>' +
                    '<strong>Password Sementara:</strong> student123<br><br>' +
                    '<em>Sila maklumkan kepada penjaga untuk menukar kata laluan.</em></p>',
                icon: 'success',
                confirmButtonText: 'OK'
            });
        }


        // ========== MAINTENANCE LOG FUNCTIONS ==========
        // View only for teachers - no add/edit/delete functionality
        function loadMaintenanceLogsV2() {
            fetch(API_PATH + '?action=get_maintenance_logs')
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    var tbody = document.getElementById('maintenanceLogsList');
                    if (result.success && result.logs && result.logs.length > 0) {
                        var html = '';
                        result.logs.forEach(function (log, i) {
                            var statusBadge = log.status === 'Aktif' ? 'badge-success' : 'badge-secondary';
                            html += '<tr><td>' + (i + 1) + '</td><td>' + log.activity + '</td><td><span class="badge ' + statusBadge + '">' + log.status + '</span></td><td>' + formatDate(log.created_at) + '</td></tr>';
                        });
                        tbody.innerHTML = html;
                    } else {
                        tbody.innerHTML = '<tr><td colspan="4" class="text-center">Tiada log penyelenggaraan</td></tr>';
                    }
                })
                .catch(function (err) {
                    console.error('Error loading maintenance logs:', err);
                    document.getElementById('maintenanceLogsList').innerHTML = '<tr><td colspan="4" class="text-center text-danger">Ralat memuatkan</td></tr>';
                });
        }


        // ========== PENDING PASSWORD SETUP ==========
        function loadPendingPasswordStudentsV2() {
            // Get approved enrollments and check which students haven't set passwords
            fetch(API_PATH + '?action=get_teacher_enrollments&status=Approved')
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    var tbody = document.getElementById('pendingPasswordList');
                    var badge = document.getElementById('settingsBadge');

                    if (result.success && result.enrollments && result.enrollments.length > 0) {
                        // Check for students who haven't set passwords (optional: check if password is still default)
                        var pendingStudents = result.enrollments.filter(function (e) {
                            return e.status === 'Approved';
                        });

                        var html = '';
                        if (pendingStudents.length > 0) {
                            pendingStudents.forEach(function (enrollment, i) {
                                html += '<tr><td>' + (i + 1) + '</td><td><strong>' + enrollment.student_name + '</strong></td><td>' + (enrollment.student_phone || '-') + '</td><td><span class="badge badge-primary">' + enrollment.subject + '</span></td><td><button class="btn btn-primary btn-sm" onclick="setupStudentPassword(' + enrollment.student_id + ', \'' + enrollment.student_name.replace(/'/g, "\\'") + '\')">🔑 Tetap Kata Laluan</button></td></tr>';
                            });

                            // Show warning badge on settings tab
                            if (badge) {
                                badge.textContent = pendingStudents.length;
                                badge.style.display = 'inline-block';
                            }
                        } else {
                            html = '<tr><td colspan="5" class="text-center">Tiada pelajar menunggu tetapan kata laluan</td></tr>';
                            if (badge) badge.style.display = 'none';
                        }
                        tbody.innerHTML = html;
                    } else {
                        tbody.innerHTML = '<tr><td colspan="5" class="text-center">Tiada pelajar menunggu tetapan kata laluan</td></tr>';
                        if (badge) badge.style.display = 'none';
                    }
                })
                .catch(function (err) {
                    console.error('Error loading pending password students:', err);
                    document.getElementById('pendingPasswordList').innerHTML = '<tr><td colspan="5" class="text-center text-danger">Ralat memuatkan</td></tr>';
                });
        }

        function setupStudentPassword(studentId, studentName) {
            document.getElementById('passwordSetupStudentId').value = studentId;
            document.getElementById('passwordSetupStudentName').textContent = studentName;
            openModal('setupPasswordModal');
        }

        function saveStudentPassword(event) {
            event.preventDefault();

            var newPassword = document.getElementById('studentNewPassword').value;
            var confirmPassword = document.getElementById('studentConfirmPassword').value;
            var studentId = document.getElementById('passwordSetupStudentId').value;

            if (newPassword !== confirmPassword) {
                showNotificationV2('Kata laluan tidak sepadan!', 'error');
                return;
            }

            if (newPassword.length < 6) {
                showNotificationV2('Kata laluan minima 6 aksara!', 'error');
                return;
            }

            var formData = new FormData();
            formData.append('action', 'setup_student_password');
            formData.append('student_id', studentId);
            formData.append('new_password', newPassword);

            var btn = document.querySelector('#setupPasswordForm button[type="submit"]');
            var originalText = btn.innerHTML;
            btn.disabled = true;
            btn.innerHTML = '⏳ Sedang memproses...';

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success) {
                        showNotificationV2('Kata laluan pelajar berjaya ditetapkan!', 'success');
                        closeModal('setupPasswordModal');
                        document.getElementById('setupPasswordForm').reset();
                    } else {
                        showNotificationV2(result.message, 'error');
                    }
                })
                .catch(function (err) {
                    showNotificationV2('Ralat sambungan', 'error');
                })
                .finally(function () {
                    btn.disabled = false;
                    btn.innerHTML = originalText;
                });
        }
    </script>
</body>

</html>