<?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;
            }
        }

        /* Modal Animation */
        .modal-overlay {
            animation: fadeIn 0.3s ease-out;
        }

        .modal {
            animation: modalSlideIn 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
        }

        @keyframes modalSlideIn {
            from {
                opacity: 0;
                transform: translateY(-50px) scale(0.9);
            }

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

        /* 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="toggleMobileMenu()"></div>

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

            <nav class="sidebar-nav">
                <a href="#" onclick="switchTab(event, 'dashboard'); closeMobileMenu();" class="nav-item active"
                    id="nav-dashboard">
                    <span class="nav-icon">📊</span> <span class="nav-text">Dashboard</span>
                </a>
                <a href="#"
                    onclick="switchTab(event, 'student-management'); loadStudentManagementData(); closeMobileMenu();"
                    class="nav-item" id="nav-student-management">
                    <span class="nav-icon">👨‍🎓</span> <span class="nav-text">Pengurusan Pelajar</span>
                </a>
                <a href="#" onclick="switchTab(event, 'forum'); closeMobileMenu();" class="nav-item" id="nav-forum">
                    <span class="nav-icon">💬</span> <span class="nav-text">Forum</span>
                </a>
                <a href="#" onclick="switchTab(event, 'bilik-tutor'); closeMobileMenu();" class="nav-item"
                    id="nav-bilik-tutor">
                    <span class="nav-icon">🏢</span> <span class="nav-text">Bilik Tutor</span>
                </a>
                <a href="#" onclick="switchTab(event, 'announcements'); closeMobileMenu();" class="nav-item"
                    id="nav-announcements">
                    <span class="nav-icon">📢</span> <span class="nav-text">Pengumuman</span>
                </a>
                <a href="#" onclick="switchTab(event, 'modules'); loadModules(); closeMobileMenu();" class="nav-item"
                    id="nav-modules">
                    <span class="nav-icon">📚</span> <span class="nav-text">Modul</span>
                </a>
                <a href="#" onclick="switchTab(event, 'schedule'); closeMobileMenu();" class="nav-item"
                    id="nav-schedule">
                    <span class="nav-icon">📅</span> <span class="nav-text">Jadual</span>
                </a>
                <a href="#" onclick="switchTab(event, 'classrooms'); closeMobileMenu();" class="nav-item"
                    id="nav-classrooms">
                    <span class="nav-icon">🏫</span> <span class="nav-text">Kelas Online</span>
                </a>
                <a href="#" onclick="switchTab(event, 'opr'); closeMobileMenu();" class="nav-item" id="nav-opr">
                    <span class="nav-icon">📄</span> <span class="nav-text">OPR</span>
                </a>
                <a href="#" onclick="switchTab(event, 'settings'); closeMobileMenu();" 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="logout()">
                    <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="deleteAllNotifications(); 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="markAllNotificationsRead(); 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>

            <div id="dashboard" class="tab-content active">
                <!-- Animated Welcome Banner -->
                <div class="welcome-banner premium-gradient animate__animated animate__fadeIn"
                    style="position: relative; overflow: hidden; padding: 40px; border-radius: var(--radius-xl); margin-bottom: 30px; color: white;">
                    <div class="floating-bubbles">
                        <div class="bubble"
                            style="width: 40px; height: 40px; left: 10%; bottom: -10%; animation-delay: 0s;"></div>
                        <div class="bubble"
                            style="width: 20px; height: 20px; left: 30%; bottom: -10%; animation-delay: 2s;"></div>
                        <div class="bubble"
                            style="width: 60px; height: 60px; left: 50%; bottom: -10%; animation-delay: 4s;"></div>
                        <div class="bubble"
                            style="width: 30px; height: 30px; left: 70%; bottom: -10%; animation-delay: 1s;"></div>
                        <div class="bubble"
                            style="width: 50px; height: 50px; left: 90%; bottom: -10%; animation-delay: 3s;"></div>
                    </div>
                    <div class="reveal-up" style="position: relative; z-index: 2;">
                        <h1 style="color: white; margin-bottom: 15px; font-size: 2.5rem;">Selamat Sejahtera, Guru
                            <?php echo htmlspecialchars(explode(' ', $teacherName)[0]); ?>! 🍎
                        </h1>
                        <p style="font-size: 1.2rem; opacity: 0.9;">Semoga sesi pengajaran anda hari ini membawa impak
                            positif kepada semua pelajar!</p>
                        <div
                            style="margin-top: 25px; font-weight: 500; background: rgba(255,255,255,0.15); padding: 10px 20px; border-radius: 30px; display: inline-block; backdrop-filter: blur(5px);">
                            <span id="bannerDay">...</span>, <span id="bannerDate">...</span> | <span
                                id="bannerTime">00:00:00</span>
                        </div>
                    </div>
                </div>

                <!-- Premium Stats Grid with Animations -->
                <div class="stats-grid"
                    style="display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 20px; margin-bottom: 30px;">
                    <div class="stat-card"
                        style="background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); border-radius: 16px; padding: 25px; color: white; position: relative; overflow: hidden; cursor: pointer; transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1); animation: fadeInUp 0.6s ease-out 0.1s both;"
                        onmouseover="this.style.transform='translateY(-8px) scale(1.02)'; this.style.boxShadow='0 20px 40px rgba(17,153,142,0.4)';"
                        onmouseout="this.style.transform='translateY(0) scale(1)'; this.style.boxShadow='0 10px 30px rgba(0,0,0,0.1)';">
                        <div style="position: absolute; top: -20px; right: -20px; font-size: 5rem; opacity: 0.2;">👨‍🎓
                        </div>
                        <div style="position: relative; z-index: 1;">
                            <div style="font-size: 3rem; font-weight: 800; text-shadow: 0 2px 10px rgba(0,0,0,0.2);"
                                id="studentCountValue"><?php echo $studentCount; ?></div>
                            <div style="font-size: 0.95rem; opacity: 0.95; font-weight: 500;">Pelajar Aktif</div>
                        </div>
                        <div
                            style="position: absolute; bottom: 10px; right: 15px; background: rgba(255,255,255,0.2); padding: 5px 12px; border-radius: 20px; font-size: 0.75rem;">
                            📈 Aktif</div>
                    </div>

                    <div class="stat-card"
                        style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 16px; padding: 25px; color: white; position: relative; overflow: hidden; cursor: pointer; transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1); animation: fadeInUp 0.6s ease-out 0.2s both;"
                        onmouseover="this.style.transform='translateY(-8px) scale(1.02)'; this.style.boxShadow='0 20px 40px rgba(102,126,234,0.4)';"
                        onmouseout="this.style.transform='translateY(0) scale(1)'; this.style.boxShadow='0 10px 30px rgba(0,0,0,0.1)';">
                        <div style="position: absolute; top: -20px; right: -20px; font-size: 5rem; opacity: 0.2;">📚
                        </div>
                        <div style="position: relative; z-index: 1;">
                            <div style="font-size: 3rem; font-weight: 800; text-shadow: 0 2px 10px rgba(0,0,0,0.2);">
                                <?php echo count($teacherSubjects); ?>
                            </div>
                            <div style="font-size: 0.95rem; opacity: 0.95; font-weight: 500;">Subjek Diajar</div>
                        </div>
                        <div
                            style="position: absolute; bottom: 10px; right: 15px; background: rgba(255,255,255,0.2); padding: 5px 12px; border-radius: 20px; font-size: 0.75rem;">
                            📖 Subjek</div>
                    </div>

                    <div class="stat-card"
                        style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); border-radius: 16px; padding: 25px; color: white; position: relative; overflow: hidden; cursor: pointer; transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1); animation: fadeInUp 0.6s ease-out 0.3s both;"
                        onmouseover="this.style.transform='translateY(-8px) scale(1.02)'; this.style.boxShadow='0 20px 40px rgba(240,147,251,0.4)';"
                        onmouseout="this.style.transform='translateY(0) scale(1)'; this.style.boxShadow='0 10px 30px rgba(0,0,0,0.1)';">
                        <div style="position: absolute; top: -20px; right: -20px; font-size: 5rem; opacity: 0.2;">📅
                        </div>
                        <div style="position: relative; z-index: 1;">
                            <div style="font-size: 3rem; font-weight: 800; text-shadow: 0 2px 10px rgba(0,0,0,0.2);"
                                id="todaySlotsCount">-</div>
                            <div style="font-size: 0.95rem; opacity: 0.95; font-weight: 500;">Slot Hari Ini</div>
                        </div>
                        <div
                            style="position: absolute; bottom: 10px; right: 15px; background: rgba(255,255,255,0.2); padding: 5px 12px; border-radius: 20px; font-size: 0.75rem;">
                            ⏰ Jadual</div>
                    </div>

                    <div class="stat-card"
                        style="background: linear-gradient(135deg, #FF6B6B 0%, #FFE66D 100%); border-radius: 16px; padding: 25px; color: white; position: relative; overflow: hidden; cursor: pointer; transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1); animation: fadeInUp 0.6s ease-out 0.4s both;"
                        onmouseover="this.style.transform='translateY(-8px) scale(1.02)'; this.style.boxShadow='0 20px 40px rgba(255,107,107,0.4)';"
                        onmouseout="this.style.transform='translateY(0) scale(1)'; this.style.boxShadow='0 10px 30px rgba(0,0,0,0.1)';">
                        <div style="position: absolute; top: -20px; right: -20px; font-size: 5rem; opacity: 0.2;">⏳
                        </div>
                        <div style="position: relative; z-index: 1;">
                            <div style="font-size: 3rem; font-weight: 800; text-shadow: 0 2px 10px rgba(0,0,0,0.2);"
                                id="dashboardPendingEnrollments">0</div>
                            <div style="font-size: 0.95rem; opacity: 0.95; font-weight: 500;">Menunggu Kelulusan</div>
                        </div>
                        <div
                            style="position: absolute; bottom: 10px; right: 15px; background: rgba(255,255,255,0.2); padding: 5px 12px; border-radius: 20px; font-size: 0.75rem;">
                            ⚡ Pending</div>
                    </div>
                </div>

                <!-- Modern Quick Actions -->
                <div class="card animate__animated animate__fadeInUp"
                    style="margin-bottom: 30px; border-radius: var(--radius-xl); overflow: hidden; box-shadow: var(--shadow-lg);">
                    <div class="card-header" style="background: var(--gradient-dark); padding: 25px; border: none;">
                        <h3 class="card-title"
                            style="color: white; margin: 0; font-size: 1.4rem; display: flex; align-items: center; gap: 12px;">
                            <span>🚀</span> Tindakan Pantas Guru
                        </h3>
                    </div>
                    <div class="card-body" style="padding: 30px;">
                        <div
                            style="display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 20px;">
                            <button class="btn lift-on-hover premium-gradient-success"
                                onclick="switchTab(event, 'student-management'); showAddStudentModal();"
                                style="flex-direction: column; padding: 25px; border-radius: 20px; color: white; border: none; gap: 12px;">
                                <span style="font-size: 2.5rem;">👨‍🎓</span>
                                <span style="font-weight: 700;">Tambah Pelajar</span>
                            </button>
                            <button class="btn lift-on-hover premium-gradient" onclick="switchTab(event, 'modules');"
                                style="flex-direction: column; padding: 25px; border-radius: 20px; color: white; border: none; gap: 12px;">
                                <span style="font-size: 2.5rem;">📚</span>
                                <span style="font-weight: 700;">Urus Modul</span>
                            </button>
                            <button class="btn lift-on-hover premium-gradient-warning"
                                onclick="switchTab(event, 'schedule');"
                                style="flex-direction: column; padding: 25px; border-radius: 20px; color: white; border: none; gap: 12px;">
                                <span style="font-size: 2.5rem;">📅</span>
                                <span style="font-weight: 700;">Jadual Waktu</span>
                            </button>
                            <button class="btn lift-on-hover premium-gradient-info"
                                onclick="switchTab(event, 'classrooms');"
                                style="flex-direction: column; padding: 25px; border-radius: 20px; color: white; border: none; gap: 12px;">
                                <span style="font-size: 2.5rem;">🏫</span>
                                <span style="font-weight: 700;">Bilik Darjah</span>
                            </button>
                            <button class="btn lift-on-hover premium-gradient-danger"
                                onclick="switchTab(event, 'announcements');"
                                style="flex-direction: column; padding: 25px; border-radius: 20px; color: white; border: none; gap: 12px;">
                                <span style="font-size: 2.5rem;">📢</span>
                                <span style="font-weight: 700;">Pengumuman</span>
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Info Cards Grid -->
                <div class="dashboard-info-cards"
                    style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px;">
                    <div class="card"
                        style="border-radius: 20px; overflow: hidden; animation: fadeInUp 0.8s ease-out 0.6s both; box-shadow: 0 10px 40px rgba(0,0,0,0.08); border: none;">
                        <div style="height: 6px; background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);"></div>
                        <div class="card-body" style="padding: 25px;">
                            <h4
                                style="margin: 0 0 20px 0; color: #1a1a2e; font-size: 1.1rem; display: flex; align-items: center; gap: 10px;">
                                <span
                                    style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 10px; border-radius: 12px; font-size: 1.2rem;">📊</span>
                                Ringkasan Dashboard
                            </h4>
                            <div style="font-size: 0.95rem; color: #555;">
                                <p
                                    style="margin: 12px 0; padding: 12px 15px; background: #f8f9ff; border-radius: 10px; display: flex; align-items: center; gap: 10px;">
                                    <span>📅</span> <strong>Hari:</strong> <span id="dashboardDayName"
                                        style="margin-left: auto; color: #667eea; font-weight: 600;">-</span>
                                </p>
                                <p
                                    style="margin: 12px 0; padding: 12px 15px; background: #f8f9ff; border-radius: 10px; display: flex; align-items: center; gap: 10px;">
                                    <span>📆</span> <strong>Tarikh:</strong> <span id="dashboardDate"
                                        style="margin-left: auto; color: #667eea; font-weight: 600;">-</span>
                                </p>
                                <p
                                    style="margin: 12px 0; padding: 12px 15px; background: #f8f9ff; border-radius: 10px; display: flex; align-items: center; gap: 10px;">
                                    <span>⏰</span> <strong>Masa:</strong> <span id="dashboardTime"
                                        style="margin-left: auto; color: #667eea; font-weight: 600;">-</span>
                                </p>
                                <p
                                    style="margin: 12px 0; padding: 12px 15px; background: linear-gradient(135deg, #667eea15 0%, #764ba215 100%); border-radius: 10px; display: flex; align-items: center; gap: 10px;">
                                    <span>👨‍🏫</span> <strong>Guru:</strong> <span
                                        style="margin-left: auto; color: #764ba2; font-weight: 600;"><?php echo htmlspecialchars($teacherName); ?></span>
                                </p>
                            </div>
                        </div>
                    </div>

                    <div class="card"
                        style="border-radius: 20px; overflow: hidden; animation: fadeInUp 0.8s ease-out 0.7s both; box-shadow: 0 10px 40px rgba(0,0,0,0.08); border: none;">
                        <div style="height: 6px; background: linear-gradient(90deg, #11998e 0%, #38ef7d 100%);"></div>
                        <div class="card-body" style="padding: 25px;">
                            <h4
                                style="margin: 0 0 20px 0; color: #1a1a2e; font-size: 1.1rem; display: flex; align-items: center; gap: 10px;">
                                <span
                                    style="background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); padding: 10px; border-radius: 12px; font-size: 1.2rem;">💡</span>
                                Panduan Penggunaan
                            </h4>
                            <div style="font-size: 0.95rem; color: #555;">
                                <p style="margin: 10px 0; padding: 10px 0; border-bottom: 1px solid #eee;"><span
                                        style="color: #11998e;">✅</span> <strong>Pendaftaran:</strong> Luluskan
                                    pendaftaran pelajar baru</p>
                                <p style="margin: 10px 0; padding: 10px 0; border-bottom: 1px solid #eee;"><span
                                        style="color: #667eea;">📚</span> <strong>Modul:</strong> Cipta nota dan bahan
                                    pembelajaran</p>
                                <p style="margin: 10px 0; padding: 10px 0; border-bottom: 1px solid #eee;"><span
                                        style="color: #f093fb;">📅</span> <strong>Jadual:</strong> Urus jadual mengajar
                                    anda</p>
                                <p style="margin: 10px 0; padding: 10px 0; border-bottom: 1px solid #eee;"><span
                                        style="color: #4facfe;">🏫</span> <strong>Kelas Online:</strong> Sesi
                                    pembelajaran secara online</p>
                                <p style="margin: 10px 0; padding: 10px 0;"><span style="color: #fa709a;">💬</span>
                                    <strong>Forum:</strong> Perbincangan dengan pelajar
                                </p>
                            </div>
                        </div>
                    </div>

                    <div class="card"
                        style="border-radius: 20px; overflow: hidden; animation: fadeInUp 0.8s ease-out 0.8s both; box-shadow: 0 10px 40px rgba(0,0,0,0.08); border: none;">
                        <div style="height: 6px; background: linear-gradient(90deg, #f093fb 0%, #f5576c 100%);"></div>
                        <div class="card-body" style="padding: 25px;">
                            <h4
                                style="margin: 0 0 20px 0; color: #1a1a2e; font-size: 1.1rem; display: flex; align-items: center; gap: 10px;">
                                <span
                                    style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); padding: 10px; border-radius: 12px; font-size: 1.2rem;">📋</span>
                                Menu Pintas
                            </h4>
                            <div style="display: flex; flex-direction: column; gap: 10px;">
                                <button class="btn"
                                    style="text-align: left; background: #f8f9ff; border: 2px solid transparent; padding: 15px; border-radius: 12px; transition: all 0.3s ease; display: flex; align-items: center; gap: 12px;"
                                    onclick="switchTab(event, 'student-management'); if(window.loadStudentManagementDataV2) loadStudentManagementDataV2();"
                                    onmouseover="this.style.borderColor='#667eea'; this.style.background='linear-gradient(135deg, #667eea15 0%, #764ba215 100%)';"
                                    onmouseout="this.style.borderColor='transparent'; this.style.background='#f8f9ff';">
                                    <span style="font-size: 1.3rem;">👨‍🎓</span>
                                    <span style="flex: 1;">Pengurusan Pelajar</span>
                                    <span class="badge" id="badge-new-count-dashboard"
                                        style="background: linear-gradient(135deg, #FF6B6B 0%, #FFE66D 100%); color: white; padding: 5px 12px; border-radius: 20px; font-weight: 600;">0</span>
                                </button>
                                <button class="btn"
                                    style="text-align: left; background: #f8f9ff; border: 2px solid transparent; padding: 15px; border-radius: 12px; transition: all 0.3s ease; display: flex; align-items: center; gap: 12px;"
                                    onclick="switchTab(event, 'modules'); loadModules();"
                                    onmouseover="this.style.borderColor='#11998e'; this.style.background='linear-gradient(135deg, #11998e15 0%, #38ef7d15 100%)';"
                                    onmouseout="this.style.borderColor='transparent'; this.style.background='#f8f9ff';">
                                    <span style="font-size: 1.3rem;">📚</span>
                                    <span>Modul Pembelajaran</span>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <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>

            <div id="modules" class="tab-content">
                <!-- Modules 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);">📚 Modul
                                    Pembelajaran</h4>
                                <p style="margin: 0; color: #666; font-size: 0.9rem;">Cipta dan urus
                                    nota pembelajaran,
                                    bahan教学, dan pautan untuk pelajar anda.</p>
                            </div>
                            <div style="display: flex; gap: 10px;">
                                <span class="badge badge-info" style="padding: 8px 15px; font-size: 0.9rem;">📖 subjek
                                    diajar: <?php echo htmlspecialchars($subjectsDisplay); ?></span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">📚 Modul Pembelajaran</h3>
                        <div style="display: flex; gap: 10px; align-items: center;">
                            <select class="form-control form-select" id="moduleSubjectFilter"
                                onchange="filterModulesBySubject()" style="width: auto;">
                                <option value="all">Semua Subjek</option>
                                <?php foreach ($teacherSubjects as $subject): ?>
                                    <option value="<?php echo htmlspecialchars($subject); ?>">
                                        <?php echo htmlspecialchars($subject); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <button class="btn btn-primary btn-sm" onclick="showAddModuleModal()">
                                <span>➕</span> Tambah Modul
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div id="modulesBySubject" style="display: flex; flex-direction: column; gap: 30px;">
                            <p class="text-center text-muted">Memuatkan modul...</p>
                        </div>
                    </div>
                </div>

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

            <div id="schedule" class="tab-content">
                <!-- Schedule 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);">📅 Jadual
                                    Kuliah</h4>
                                <p style="margin: 0; color: #666; font-size: 0.9rem;">Urus jadual
                                    mengajar anda. Anda
                                    boleh melihat jadual sendiri atau guru lain.</p>
                            </div>
                            <div style="display: flex; gap: 10px;">
                                <span class="badge badge-info" style="padding: 8px 15px; font-size: 0.9rem;">📅 Hari
                                    Ini: <span id="todayScheduleCount">0</span> slot</span>
                                <span class="badge badge-secondary" style="padding: 8px 15px; font-size: 0.9rem;">👨‍🏫
                                    Subjek: <?php echo count($teacherSubjects); ?></span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">📅 Jadual Kuliah</h3>
                        <div style="display: flex; gap: 10px; align-items: center;">
                            <select class="form-control form-select" id="scheduleViewMode"
                                onchange="changeScheduleView()" style="width: auto;">
                                <option value="mine">Jadual Saya</option>
                                <option value="all">Semua Guru</option>
                            </select>
                            <input type="text" class="form-control" id="teacherSearch"
                                placeholder="🔍 Cari nama guru..." oninput="searchTeacherSchedule()"
                                style="width: 200px; display: none;">
                            <button class="btn btn-primary btn-sm" onclick="showAddScheduleModal()">
                                <span>➕</span> Tambah Jadual
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="table-container">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>Hari/Tarikh</th>
                                        <th>Masa</th>
                                        <th>Subjek</th>
                                        <th>Guru</th>
                                        <th>Penerangan</th>
                                        <th>Tindakan</th>
                                    </tr>
                                </thead>
                                <tbody id="scheduleList">
                                    <tr>
                                        <td colspan="6" class="text-center">Memuatkan...</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <div id="classrooms" class="tab-content">
                <!-- Classrooms 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);">🏫 Kelas
                                    Online</h4>
                                <p style="margin: 0; color: #666; font-size: 0.9rem;">Cipta dan urus
                                    kelas online.
                                    Pelajar boleh menyertai kelas melalui pautan yang disediakan.</p>
                            </div>
                            <div style="display: flex; gap: 10px;">
                                <span class="badge badge-primary" style="padding: 8px 15px; font-size: 0.9rem;">🏫
                                    Pelajar Diajar: <span id="taughtStudentsCount">0</span></span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">🏫 Kelas Online</h3>
                        <div style="display: flex; gap: 10px; align-items: center; flex-wrap: wrap;">
                            <!-- Penapis Carian -->
                            <input type="text" class="form-control" id="classStudentSearch"
                                placeholder="🔍 Cari nama pelajar..." oninput="filterClassesByStudent()"
                                style="width: 200px;">
                            <select class="form-control form-select" id="classSubjectFilter"
                                onchange="filterClassesByStudent()" style="width: auto;">
                                <option value="all">Semua Subjek</option>
                                <?php foreach ($teacherSubjects as $subject): ?>
                                    <option value="<?php echo htmlspecialchars($subject); ?>">
                                        <?php echo htmlspecialchars($subject); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <button class="btn btn-primary btn-sm" onclick="showAddClassModal()">
                                <span>➕</span> Buat Kelas
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <!-- Senarai Pelajar yang Diajar -->
                        <div id="taughtStudentsSection"
                            style="margin-bottom: 20px; padding: 15px; background: #f8f9fa; border-radius: 8px;">
                            <h5 style="margin: 0 0 10px 0;">👨‍🎓 Pelajar yang Diajar</h5>
                            <div id="taughtStudentsList" style="display: flex; flex-wrap: wrap; gap: 8px;">
                                <p class="text-muted" style="width: 100%;">Memuatkan...</p>
                            </div>
                        </div>

                        <div id="classesGrid"
                            style="display: grid; grid-template-columns: repeat(auto-fill, minmax(350px, 1fr)); gap: 20px;">
                            <p class="text-center text-muted">Memuatkan kelas...</p>
                        </div>
                    </div>
                </div>
            </div>

            <div id="forum" class="tab-content">
                <!-- Forum 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);">💬 Forum
                                    Perbincangan</h4>
                                <p style="margin: 0; color: #666; font-size: 0.9rem;">Buat forum
                                    perbincangan untuk
                                    pelajar. Anda boleh berkongsi soalan, nota, dan pautan pembelajaran.
                                </p>
                            </div>
                            <div style="display: flex; gap: 10px;">
                                <span class="badge badge-info" style="padding: 8px 15px; font-size: 0.9rem;">💬 Sasaran:
                                    Pelajar & Guru</span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">💬 Forum Perbincangan</h3>
                        <button class="btn btn-primary btn-sm" onclick="showAddForumModal()">
                            <span>➕</span> Buat Forum
                        </button>
                    </div>
                    <div class="card-body">
                        <div id="forumList" style="display: flex; flex-direction: column; gap: 15px;">
                            <p class="text-center text-muted">Memuatkan forum...</p>
                        </div>
                    </div>
                </div>
            </div>

            <div id="announcements" class="tab-content">
                <!-- Announcements 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);">📢
                                    Pengumuman</h4>
                                <p style="margin: 0; color: #666; font-size: 0.9rem;">Buat pengumuman
                                    untuk pelajar atau
                                    guru lain. Gunakan kategori untuk memudahkan pengurusan.</p>
                            </div>
                            <div style="display: flex; gap: 10px;">
                                <span class="badge badge-warning" style="padding: 8px 15px; font-size: 0.9rem;">📢
                                    Prioriti: Normal/Penting/Urgent</span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">📢 Pengumuman</h3>
                        <button class="btn btn-primary btn-sm" onclick="showAddAnnouncementModal()">
                            <span>➕</span> Buat Pengumuman
                        </button>
                    </div>
                    <div class="card-body">
                        <div id="announcementsList" style="display: flex; flex-direction: column; gap: 15px;">
                            <p class="text-center text-muted">Memuatkan pengumuman...</p>
                        </div>
                    </div>
                </div>
            </div>

            <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="switchTab(event, 'dashboard')" class="nav-tab-item active" id="mob-nav-dashboard">
            <span class="nav-icon">📊</span>
            <span>Dashboard</span>
        </a>
        <a href="#" onclick="switchTab(event, 'student-management')" class="nav-tab-item"
            id="mob-nav-student-management">
            <span class="nav-icon">👨‍🎓</span>
            <span>Pelajar</span>
        </a>
        <a href="#" onclick="switchTab(event, 'forum')" class="nav-tab-item" id="mob-nav-forum">
            <span class="nav-icon">💬</span>
            <span>Forum</span>
        </a>
        <a href="#" onclick="switchTab(event, 'bilik-tutor')" class="nav-tab-item" id="mob-nav-bilik-tutor">
            <span class="nav-icon">🏢</span>
            <span>Bilik</span>
        </a>
        <a href="#" onclick="switchTab(event, 'announcements')" class="nav-tab-item" id="mob-nav-announcements">
            <span class="nav-icon">📢</span>
            <span>Info</span>
        </a>
        <a href="#" onclick="switchTab(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(); toggleMobileMenu()" 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 toggleMobileMenu() {
            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 closeMobileMenu() {
            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 showNotification(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 showConfirm(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 loadNotifications === 'function') {
                    loadNotifications();
                }
            } 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 () {
            updateRealtimeClock();
            updateBannerTime(); // Initial update for wow banner
            // Initialize notification system
            initNotificationSystem();
            setInterval(updateRealtimeClock, 1000);
            setInterval(updateBannerTime, 1000); // Sync banner time

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

            loadTodaySlots(); // Load today's schedule slots
            initializeEmojiPicker();
            loadModules();
            initializeStatusToggle(); // Initialize status toggle based on teacher status
            loadSchedule();
            loadClasses();
            loadForum();
            loadAnnouncements();
            loadOPR();
            loadMaintenanceLogs(); // Load maintenance logs
            loadPendingPasswordStudents(); // 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
            switchTab(null, 'dashboard');

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

        // Logout function FIXED
        function logout() {
            // Tunjuk status sedang proses
            const btn = document.querySelector('button[onclick="logout()"]');
            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 updateRealtimeClock() {
            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 hours = String(now.getHours()).padStart(2, '0');
            var minutes = String(now.getMinutes()).padStart(2, '0');
            var seconds = String(now.getSeconds()).padStart(2, '0');

            var timeString = hours + ':' + minutes + ':' + seconds;
            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 updateBannerTime() {
            updateRealtimeClock();
        }


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

            // 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':
                        loadStudents();
                        loadTodaySlots();
                        loadAnnouncements();
                        break;
                    case 'students':
                        loadStudents();
                        break;
                    case 'student-management':
                        if (window.loadStudentManagementDataV2) {
                            loadStudentManagementDataV2();
                        } else {
                            loadStudentManagementData();
                        }
                        break;
                    case 'modules':
                        loadModules();
                        break;
                    case 'schedule':
                        loadSchedule();
                        break;
                    case 'classrooms':
                        loadClasses();
                        break;
                    case 'forum':
                        loadForum();
                        break;
                    case 'bilik-tutor':
                        loadTutorRoomData();
                        break;
                    case 'announcements':
                        loadAnnouncements();
                        break;
                    case 'opr':
                        loadOPR();
                        break;
                    case 'settings':
                        loadPendingPasswordStudents();
                        break;
                }

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

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

        function loadStudents() {
            // 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 || {};

                        displayStudents(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() {
            loadStudents(); // 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 loadTodaySlots() {
            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 syncDataOnLoad() {
            // 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
                    loadStudents();
                    loadEnrollments();
                    loadTaughtStudents();
                    loadPendingPasswordStudents();
                })
                .catch(function (err) {
                    console.error('Error syncing data:', err);
                    // Still try to load data even if sync fails
                    loadStudents();
                    loadEnrollments();
                });
        }

        function displayStudents(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="viewStudentDetails(' + 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="if(window.deleteStudentV2) { deleteStudentV2(' + s.id + '); } else { removeStudent(' + s.id + '); }">🗑️</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="viewStudentDetails(' + s.id + ')">View</button></td></tr>';
                });
                oldTbody.innerHTML = html;
            }
        }

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

        function viewStudentDetails(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 {
                        showNotification('Gagal memuatkan maklumat pelajar', 'error');
                    }
                })
                .catch(function (err) {
                    console.error('Error fetching student details:', err);
                    showNotification('Ralat sambungan', 'error');
                });
        }

        function removeStudent(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) {
                                showNotification('Pelajar berjaya dipadam', 'success');
                                loadStudents();
                            } else {
                                showNotification(res.message, 'error');
                            }
                        })
                        .catch(function (err) {
                            showNotification('Ralat sambungan', 'error');
                        });
                }
            });
        }


        function loadModules() {
            fetch(API_PATH + '?action=get_teacher_modules')
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    var container = document.getElementById('modulesBySubject');
                    if (result.success && result.modules && result.modules.length > 0) {
                        // Group modules by subject
                        var modulesBySubject = {};
                        result.modules.forEach(function (module) {
                            var subject = module.subject || 'Lain-lain';
                            if (!modulesBySubject[subject]) {
                                modulesBySubject[subject] = [];
                            }
                            modulesBySubject[subject].push(module);
                        });

                        var html = '';
                        Object.keys(modulesBySubject).sort().forEach(function (subject) {
                            html += '<div><h4 style="color: var(--primary-color); margin-bottom: 15px;">📚 ' + subject + '</h4>';
                            html += '<div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 15px;">';

                            modulesBySubject[subject].forEach(function (module) {
                                var links = JSON.parse(module.links || '[]');
                                html += '<div class="card"><div class="card-body">';
                                html += '<div style="display: flex; justify-content: space-between; align-items: start;">';
                                html += '<h5 style="margin: 0 0 10px 0;">' + module.title + '</h5>';
                                html += '<span class="badge badge-info">' + subject + '</span></div>';
                                html += '<p class="text-muted" style="margin-bottom: 10px;">' + (module.description || '') + '</p>';
                                html += '<div style="font-size: 0.9rem;">';
                                html += '<span>📎 ' + links.length + ' pautan</span>';
                                html += '<span style="margin-left: 15px;">📅 ' + formatDate(module.created_at) + '</span></div>';
                                html += '<div style="margin-top: 15px; display: flex; gap: 10px;">';
                                html += '<button class="btn btn-secondary btn-sm" onclick="viewModuleDetails(' + module.id + ')">👁️</button>';
                                html += '<button class="btn btn-danger btn-sm" onclick="deleteModule(' + module.id + ')">🗑️</button>';
                                html += '</div></div></div>';
                            });

                            html += '</div></div>';
                        });
                        container.innerHTML = html;
                    } else {
                        container.innerHTML = '<div style="text-align: center;"><p class="text-muted">Tiada modul dicipta</p><button class="btn btn-primary" onclick="showAddModuleModal()">Tambah Modul Pertama</button></div>';
                    }
                })
                .catch(function (err) {
                    console.error('Error loading modules:', err);
                });
        }

        function filterModulesBySubject() {
            loadModules();
        }

        function viewModuleDetails(moduleId) {
            fetch(API_PATH + '?action=get_teacher_modules')
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success && result.modules) {
                        var module = result.modules.find(function (m) { return parseInt(m.id) === parseInt(moduleId); });
                        if (module) {
                            var links = JSON.parse(module.links || '[]');
                            document.getElementById('moduleDetailTitle').textContent = module.title;
                            document.getElementById('moduleDetailSubject').textContent = module.subject;
                            document.getElementById('moduleDetailDescription').textContent = module.description || 'Tiada penerangan';
                            document.getElementById('moduleDetailContent').textContent = module.content || 'Tiada kandungan';

                            var linksHtml = '';
                            if (links.length > 0) {
                                links.forEach(function (link) {
                                    linksHtml += '<a href="' + link + '" target="_blank" class="btn btn-outline-primary btn-sm" style="margin: 3px;">🔗 ' + link.substring(0, 30) + '...</a>';
                                });
                            } else {
                                linksHtml = '<p class="text-muted">Tiada pautan</p>';
                            }
                            document.getElementById('moduleDetailLinks').innerHTML = linksHtml;
                            openModal('moduleDetailModal');
                        }
                        else {
                            showNotification('Modul tidak dijumpai', 'error');
                        }
                    } else {
                        showNotification(result.message || 'Gagal memuatkan modul', 'error');
                    }
                })
                .catch(function (error) {
                    console.error('Error viewing module:', error);
                    showNotification('Ralat sambungan', 'error');
                });
        }

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

            Swal.fire({
                title: 'Padam Modul?',
                text: 'Modul 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_module');
                    formData.append('id', id);

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

        var allSchedulesData = [];
        var allTeachersData = [];

        function loadSchedule() {
            var viewMode = document.getElementById('scheduleViewMode').value;
            var searchTerm = document.getElementById('teacherSearch').value.toLowerCase();

            // Load all teachers for searching
            fetch(API_PATH + '?action=get_all_teachers')
                .then(function (response) { return response.json(); })
                .then(function (tResult) {
                    if (tResult.success) {
                        allTeachersData = tResult.teachers || [];
                    }

                    // Load schedules based on view mode
                    if (viewMode === 'mine') {
                        fetch(API_PATH + '?action=get_teacher_schedule')
                            .then(function (response) { return response.json(); })
                            .then(function (result) {
                                displaySchedule(result.schedules || [], viewMode);
                            });
                    } else {
                        fetch(API_PATH + '?action=get_all_schedules')
                            .then(function (response) { return response.json(); })
                            .then(function (result) {
                                allSchedulesData = result.schedules || [];
                                if (searchTerm) {
                                    allSchedulesData = allSchedulesData.filter(function (s) {
                                        return (s.teacher_name || '').toLowerCase().includes(searchTerm);
                                    });
                                }
                                displaySchedule(allSchedulesData, viewMode);
                            });
                    }
                });
        }

        function displaySchedule(schedules, viewMode) {
            var tbody = document.getElementById('scheduleList');
            if (schedules && schedules.length > 0) {
                var html = '';
                schedules.forEach(function (s) {
                    var showTeacher = viewMode === 'all' || s.teacher_id != <?php echo $_SESSION['user_id']; ?>;
                    var actionBtns = s.teacher_id == <?php echo $_SESSION['user_id']; ?> ?
                        '<button class="btn btn-danger btn-sm btn-icon" onclick="deleteSchedule(' + s.id + ')">🗑️</button>' :
                        '<span class="text-muted">-</span>';

                    html += '<tr><td>' + (s.day_of_week || formatDate(s.schedule_date)) + '</td><td>' + s.start_time + (s.end_time ? ' - ' + s.end_time : '') + '</td><td>' + s.subject + '</td>' +
                        (showTeacher ? '<td><span class="badge badge-secondary">' + (s.teacher_name || 'Guru') + '</span></td>' : '<td></td>') +
                        '<td>' + (s.description || '-') + '</td><td>' + actionBtns + '</td></tr>';
                });
                tbody.innerHTML = html;
            } else {
                tbody.innerHTML = '<tr><td colspan="6" class="text-center">' + (viewMode === 'all' ? 'Tiada jadual dari guru lain' : 'Tiada jadual ditetapkan') + '</td></tr>';
            }
        }

        function changeScheduleView() {
            var viewMode = document.getElementById('scheduleViewMode').value;
            var searchBox = document.getElementById('teacherSearch');

            if (viewMode === 'all') {
                searchBox.style.display = 'block';
            } else {
                searchBox.style.display = 'none';
            }
            loadSchedule();
        }

        function searchTeacherSchedule() {
            loadSchedule();
        }

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

            Swal.fire({
                title: 'Padam Jadual?',
                text: 'Jadual 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_schedule');
                    formData.append('id', id);

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

        function loadClasses() {
            var subjectFilter = document.getElementById('classSubjectFilter') ? document.getElementById('classSubjectFilter').value : 'all';

            // First, load and display taught students
            loadTaughtStudents();

            fetch(API_PATH + '?action=get_teacher_classes')
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    var container = document.getElementById('classesGrid');
                    if (result.success && result.classes && result.classes.length > 0) {
                        // Filter by subject if needed
                        var classes = result.classes;
                        if (subjectFilter !== 'all') {
                            classes = classes.filter(function (c) { return c.subject === subjectFilter; });
                        }

                        if (classes.length > 0) {
                            var html = '';
                            classes.forEach(function (c) {
                                html += '<div class="card">';
                                html += '<div class="card-body">';
                                html += '<div style="display: flex; justify-content: space-between; align-items: start;">';
                                html += '<h4>' + c.title + '</h4>';
                                html += '<span class="badge badge-primary">' + c.subject + '</span></div>';
                                html += '<p class="text-muted" style="margin: 10px 0;">' + (c.description || '') + '</p>';
                                html += '<div style="font-size: 0.9rem; margin-bottom: 10px;">';
                                html += '<div>📅 ' + c.class_date + '</div>';
                                html += '<div>🕐 ' + c.start_time + (c.end_time ? ' - ' + c.end_time : '') + '</div>';
                                html += '</div>';
                                if (c.join_link) {
                                    html += '<a href="' + c.join_link + '" target="_blank" class="btn btn-primary btn-sm" style="margin-right: 5px;">🔗 Join Kelas</a>';
                                }
                                html += '<button class="btn btn-secondary btn-sm" onclick="viewClassStudents(' + c.id + ', \'' + (c.title || '').replace(/'/g, "\\'") + '\')">👥 Pelajar</button>';
                                html += '<button class="btn btn-danger btn-sm" style="margin-left: 5px;" onclick="deleteClass(' + c.id + ')">🗑️</button>';
                                html += '</div></div>';
                            });
                            container.innerHTML = html;
                        } else {
                            container.innerHTML = '<div style="grid-column: 1/-1; text-align: center;"><p class="text-muted">Tiada kelas untuk subjek ini</p></div>';
                        }
                    } else {
                        container.innerHTML = '<div style="grid-column: 1/-1; text-align: center;"><p class="text-muted">Tiada kelas online</p></div>';
                    }
                })
                .catch(function (err) {
                    console.error('Error loading classes:', err);
                });
        }

        // Load and display taught students
        function loadTaughtStudents() {
            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>';
                });
        }

        // Filter classes by student name or subject
        function filterClassesByStudent() {
            var searchTerm = document.getElementById('classStudentSearch').value.toLowerCase();
            var subjectFilter = document.getElementById('classSubjectFilter').value;

            fetch(API_PATH + '?action=get_teacher_classes')
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    var container = document.getElementById('classesGrid');

                    if (result.success && result.classes && result.classes.length > 0) {
                        var classes = result.classes;

                        // Apply subject filter
                        if (subjectFilter !== 'all') {
                            classes = classes.filter(function (c) { return c.subject === subjectFilter; });
                        }

                        // Apply student name filter (by checking class title for student names is tricky)
                        // Instead, we'll filter by student enrollment
                        if (searchTerm) {
                            // Get enrollments and filter classes that have matching students
                            fetch(API_PATH + '?action=get_teacher_enrollments&status=Approved')
                                .then(function (r) { return r.json(); })
                                .then(function (enrollResult) {
                                    if (enrollResult.success && enrollResult.enrollments) {
                                        var matchingStudentIds = enrollResult.enrollments
                                            .filter(function (e) {
                                                return e.student_name && e.student_name.toLowerCase().includes(searchTerm);
                                            })
                                            .map(function (e) { return e.student_id; });

                                        // Filter classes that might be for these students
                                        // For now, just show all classes with a note
                                        displayFilteredClasses(classes, searchTerm);
                                    }
                                });
                        } else {
                            displayFilteredClasses(classes);
                        }
                    } else {
                        container.innerHTML = '<div style="grid-column: 1/-1; text-align: center;"><p class="text-muted">Tiada kelas online</p></div>';
                    }
                })
                .catch(function (err) {
                    console.error('Error filtering classes:', err);
                });
        }

        function displayFilteredClasses(classes, searchTerm = '') {
            var container = document.getElementById('classesGrid');

            if (classes.length > 0) {
                var html = '';
                classes.forEach(function (c) {
                    html += '<div class="card">';
                    html += '<div class="card-body">';
                    html += '<div style="display: flex; justify-content: space-between; align-items: start;">';
                    html += '<h4>' + c.title + '</h4>';
                    html += '<span class="badge badge-primary">' + c.subject + '</span></div>';
                    html += '<p class="text-muted" style="margin: 10px 0;">' + (c.description || '') + '</p>';
                    html += '<div style="font-size: 0.9rem; margin-bottom: 10px;">';
                    html += '<div>📅 ' + c.class_date + '</div>';
                    html += '<div>🕐 ' + c.start_time + (c.end_time ? ' - ' + c.end_time : '') + '</div>';
                    html += '</div>';
                    if (c.join_link) {
                        html += '<a href="' + c.join_link + '" target="_blank" class="btn btn-primary btn-sm" style="margin-right: 5px;">🔗 Join Kelas</a>';
                    }
                    html += '<button class="btn btn-secondary btn-sm" onclick="viewClassStudents(' + c.id + ', \'' + (c.title || '').replace(/'/g, "\\'") + '\')">👥 Pelajar</button>';
                    html += '<button class="btn btn-danger btn-sm" style="margin-left: 5px;" onclick="deleteClass(' + c.id + ')">🗑️</button>';
                    html += '</div></div>';
                });

                if (searchTerm) {
                    html = '<div style="grid-column: 1/-1; margin-bottom: 15px;"><p class="text-info">🔍 Menunjukkan kelas yang sepadan dengan "' + searchTerm + '"</p></div>' + html;
                }

                container.innerHTML = html;
            } else {
                var message = searchTerm
                    ? 'Tiada kelas yang sepadan dengan "' + searchTerm + '"'
                    : 'Tiada kelas online';
                container.innerHTML = '<div style="grid-column: 1/-1; text-align: center;"><p class="text-muted">' + message + '</p></div>';
            }
        }

        function filterClassesBySubject() {
            // Legacy function, now redirects to filterClassesByStudent
            filterClassesByStudent();
        }

        function viewClassStudents(classId, classTitle) {
            // Show students enrolled in this class
            document.getElementById('classDetailTitle').textContent = classTitle || 'Kelas';

            // Get students from enrollments
            fetch(API_PATH + '?action=get_teacher_enrollments&status=Approved')
                .then(function (r) { return r.json(); })
                .then(function (enrollResult) {
                    if (enrollResult.success && enrollResult.enrollments) {
                        // Group students by subject for display
                        var studentsBySubject = {};
                        enrollResult.enrollments.forEach(function (s) {
                            var subject = s.subject || 'Lain-lain';
                            if (!studentsBySubject[subject]) {
                                studentsBySubject[subject] = [];
                            }
                            studentsBySubject[subject].push(s);
                        });

                        var studentsHtml = '';
                        var hasStudents = false;

                        Object.keys(studentsBySubject).sort().forEach(function (subject) {
                            studentsHtml += '<div style="padding: 10px; background: #f8f9fa; border-radius: 5px; margin-bottom: 10px;">';
                            studentsHtml += '<strong style="color: var(--primary-color);">📚 ' + subject + '</strong>';
                            studentsHtml += '<div style="margin-top: 8px;">';

                            studentsBySubject[subject].forEach(function (s) {
                                studentsHtml += '<div style="padding: 8px; border-bottom: 1px solid #eee;">';
                                studentsHtml += '<strong>' + s.student_name + '</strong>';
                                if (s.student_phone) {
                                    studentsHtml += '<br><small>📞 ' + s.student_phone + '</small>';
                                }
                                studentsHtml += '</div>';
                                hasStudents = true;
                            });

                            studentsHtml += '</div></div>';
                        });

                        if (hasStudents) {
                            document.getElementById('classStudentsList').innerHTML = studentsHtml;
                        } else {
                            document.getElementById('classStudentsList').innerHTML = '<p class="text-center text-muted">Tiada pelajar untuk subjek ini</p>';
                        }
                        openModal('classStudentsModal');
                    }
                });
        }

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

            Swal.fire({
                title: 'Padam Kelas?',
                text: 'Kelas 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_class');
                    formData.append('id', id);

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

        function loadForum() {
            fetch(API_PATH + '?action=get_teacher_forums')
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    var container = document.getElementById('forumList');
                    if (result.success && result.forums && result.forums.length > 0) {
                        var html = '';
                        result.forums.forEach(function (f) {
                            html += '<div class="card"><div class="card-body"><h4>' + f.title + '</h4><p>' + (f.content ? f.content.substring(0, 100) + '...' : '') + '</p><small>' + f.subject + '</small></div></div>';
                        });
                        container.innerHTML = html;
                    } else {
                        container.innerHTML = '<div style="text-align: center;"><p class="text-muted">Tiada forum</p></div>';
                    }
                })
                .catch(function (err) {
                    console.error('Error loading forum:', err);
                });
        }

        function loadAnnouncements() {
            fetch(API_PATH + '?action=get_announcements')
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    var container = document.getElementById('announcementsList');
                    if (result.success && result.announcements && result.announcements.length > 0) {
                        var html = '';
                        result.announcements.forEach(function (a) {
                            var isOwner = (parseInt(a.teacher_id) === CURRENT_USER_ID);
                            var priorityClass = 'badge-info';
                            if (a.priority === 'High' || a.priority === 'Urgent') priorityClass = 'badge-danger';
                            if (a.priority === 'Medium' || a.priority === 'Penting') priorityClass = 'badge-warning';

                            var actionsHtml = '';
                            if (isOwner) {
                                // Encode content to safely pass as JS arguments
                                var titleEnc = encodeURIComponent(a.title);
                                var contentEnc = encodeURIComponent(a.content);
                                actionsHtml = '<div class="announcement-actions" style="margin-top: 10px; display: flex; gap: 8px;">' +
                                    '<button class="btn btn-sm btn-outline-primary" style="padding: 4px 10px; font-size: 12px;" onclick="openEditAnnouncementModal(' + a.id + ', \'' + titleEnc + '\', \'' + contentEnc + '\', \'' + a.priority + '\', \'' + a.target_audience + '\')">✏️ Edit</button>' +
                                    '<button class="btn btn-sm btn-outline-danger" style="padding: 4px 10px; font-size: 12px;" onclick="deleteAnnouncement(' + a.id + ')">🗑️ Hapus</button>' +
                                    '</div>';
                            }

                            html += '<div class="card" style="margin-bottom: 15px; border-radius: 12px; overflow: hidden; border-left: 4px solid ' + (isOwner ? 'var(--primary-color)' : '#eee') + ';">' +
                                '<div class="card-body" style="padding: 15px;">' +
                                '<div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 8px;">' +
                                '<span class="badge ' + priorityClass + '" style="font-size: 10px;">' + (a.priority || 'Normal') + '</span>';

                            if (a.target_audience && a.target_audience !== 'Semua') {
                                html += '<span class="badge badge-secondary" style="font-size: 10px; margin-left: 5px;">' + a.target_audience + '</span>';
                            }

                            html += '<small class="text-muted">' + formatDate(a.created_at) + '</small>' +
                                '</div>' +
                                '<h4 style="margin: 0 0 10px 0; color: var(--dark-color); font-size: 16px;">' + a.title + '</h4>' +
                                '<p style="margin: 0; color: #666; font-size: 14px; line-height: 1.5;">' + a.content + '</p>' +
                                '<div style="margin-top: 12px; display: flex; justify-content: justify-content; align-items: center;">' +
                                '<div style="display: flex; align-items: center; gap: 5px;">' +
                                '<div style="width: 24px; height: 24px; background: #f0f2f5; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 12px;">' + (a.profile_emoji || '👤') + '</div>' +
                                '<small style="color: #888;">' + (a.teacher_name || 'Admin') + '</small>' +
                                '</div>' +
                                '</div>' +
                                actionsHtml +
                                '</div></div>';
                        });
                        container.innerHTML = html;
                    } else {
                        container.innerHTML = '<div class="empty-state" style="padding: 40px 20px; text-align: center;">' +
                            '<div style="font-size: 40px; margin-bottom: 10px; opacity: 0.5;">📢</div>' +
                            '<p class="text-muted">Tiada pengumuman buat masa ini</p>' +
                            '</div>';
                    }
                })
                .catch(function (err) {
                    console.error('Error loading announcements:', err);
                    container.innerHTML = '<div class="text-center p-4 text-danger">Gagal memuatkan pengumuman</div>';
                });
        }

        function loadOPR() {
            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) {
                        showNotification('Profil dikemaskini', 'success');
                        setTimeout(function () { location.reload(); }, 1500);
                    } else {
                        showNotification(res.message, 'error');
                    }
                })
                .catch(function (err) {
                    showNotification('Ralat sambungan', 'error');
                });
        }

        // ========== MODAL HELPER FUNCTIONS ==========
        function openModal(modalId) {
            var modal = document.getElementById(modalId);
            if (modal) {
                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);

            // 1. Try to find in local data first
            var student = null;
            if (studentsData && 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 {
                            showNotification('Pelajar tidak dijumpai dalam pangkalan data.', 'error');
                        }
                    })
                    .catch(function (err) {
                        Swal.close();
                        console.error('Error fetching student:', err);
                        showNotification('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) {
                                showNotification('Pelajar berjaya dipadam', 'success');
                                if (typeof loadStudentManagementData === "function") { loadStudentManagementData(); } else { loadStudents(); }
                            } else {
                                showNotification(res.message, 'error');
                            }
                        })
                        .catch(function (err) {
                            showNotification('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) {
                        showNotification(editingStudentId ? 'Pelajar berjaya dikemaskini' : 'Pelajar berjaya ditambah', 'success');
                        closeModal('studentModal');
                        if (typeof loadStudentManagementData === 'function') {
                            loadStudentManagementData();
                        } else {
                            loadStudents();
                        }
                    } else {
                        showNotification(result.message, 'error');
                    }
                })
                .catch(function (err) {
                    showNotification('Ralat sambungan', 'error');
                })
                .finally(function () {
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = originalText;
                });
        }

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

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

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

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

        // ========== ANNOUNCEMENT FUNCTIONS ==========
        function showAddAnnouncementModal() {
            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>

    <div class="modal-overlay" id="moduleModal">
        <div class="modal" style="max-width: 750px;">
            <div class="modal-header">
                <h3 class="modal-title">📚 Tambah Modul Baru</h3>
                <button class="modal-close" onclick="closeModal('moduleModal')">×</button>
            </div>
            <div class="modal-body">
                <form id="moduleForm" onsubmit="saveModule(event)">
                    <input type="hidden" name="id" id="moduleId">

                    <div class="form-group">
                        <label class="form-label">Tajuk Modul <span class="required">*</span></label>
                        <input type="text" class="form-control" name="title" id="moduleTitle" required
                            placeholder="cth: Modul Matematik - Pecahan">
                    </div>

                    <div class="form-row" style="grid-template-columns: 1fr 1fr;">
                        <div class="form-group">
                            <label class="form-label">Subjek <span class="required">*</span></label>
                            <select class="form-control form-select" name="subject" id="moduleSubject" required
                                onchange="loadStudentsForSelection('module')">
                                <option value="">Pilih Subjek</option>
                                <?php foreach ($teacherSubjects as $subject): ?>
                                    <option value="<?php echo htmlspecialchars($subject); ?>">
                                        <?php echo htmlspecialchars($subject); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="form-group">
                            <label class="form-label">Akses Modul</label>
                            <select class="form-control form-select" id="moduleAccessType"
                                onchange="toggleStudentSelection('module')">
                                <option value="all">Semua Pelajar</option>
                                <option value="specific">Pelajar Tertentu</option>
                            </select>
                        </div>
                    </div>

                    <!-- Student Selection Section -->
                    <div id="moduleStudentSelection"
                        style="display: none; margin-top: 15px; padding: 15px; background: #f8f9fa; border-radius: 8px;">
                        <div
                            style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                            <label class="form-label" style="margin: 0;"><strong>Pilih Pelajar:</strong></label>
                            <div>
                                <button type="button" class="btn btn-sm btn-secondary"
                                    onclick="selectAllStudents('module')">Pilih Semua</button>
                                <button type="button" class="btn btn-sm btn-secondary"
                                    onclick="deselectAllStudents('module')">Batalkan Semua</button>
                            </div>
                        </div>
                        <div style="max-height: 150px; overflow-y: auto; border: 1px solid #ddd; border-radius: 8px; padding: 10px; background: white;"
                            id="moduleStudentList">
                            <p class="text-muted text-center">Sila pilih subjek terlebih dahulu</p>
                        </div>
                    </div>

                    <div class="form-group" style="margin-top: 15px;">
                        <label class="form-label">Penerangan</label>
                        <textarea class="form-control" name="description" id="moduleDescription" rows="3"
                            placeholder="Penerangan ringkas..."></textarea>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Kandungan/Nota</label>
                        <textarea class="form-control" name="content" id="moduleContent" rows="5"
                            placeholder="Kandungan modul..."></textarea>
                    </div>

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

    <div class="modal-overlay" id="scheduleModal">
        <div class="modal" style="max-width: 600px;">
            <div class="modal-header">
                <h3 class="modal-title">📅 Tambah Jadual</h3>
                <button class="modal-close" onclick="closeModal('scheduleModal')">×</button>
            </div>
            <div class="modal-body">
                <form id="scheduleForm" onsubmit="saveSchedule(event)">
                    <input type="hidden" name="id" id="scheduleId">

                    <div class="form-group">
                        <label class="form-label">Tajuk Sesi <span class="required">*</span></label>
                        <input type="text" class="form-control" name="title" id="scheduleTitle" required
                            placeholder="cth: Kelas Matematik">
                    </div>

                    <div class="form-row" style="grid-template-columns: 1fr 1fr;">
                        <div class="form-group">
                            <label class="form-label">Subjek <span class="required">*</span></label>
                            <select class="form-control form-select" name="subject" id="scheduleSubject" required>
                                <option value="">Pilih Subjek</option>
                                <?php foreach ($teacherSubjects as $subject): ?>
                                    <option value="<?php echo htmlspecialchars($subject); ?>">
                                        <?php echo htmlspecialchars($subject); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="form-group">
                            <label class="form-label">Tarikh <span class="required">*</span></label>
                            <input type="date" class="form-control" name="schedule_date" id="scheduleDate" required>
                        </div>
                    </div>

                    <div class="form-row" style="grid-template-columns: 1fr 1fr;">
                        <div class="form-group">
                            <label class="form-label">Masa Mula <span class="required">*</span></label>
                            <input type="time" class="form-control" name="start_time" id="scheduleStartTime" required>
                        </div>

                        <div class="form-group">
                            <label class="form-label">Masa Tamat</label>
                            <input type="time" class="form-control" name="end_time" id="scheduleEndTime">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Penerangan</label>
                        <textarea class="form-control" name="description" id="scheduleDescription" rows="3"
                            placeholder="Penerangan sesi..."></textarea>
                    </div>

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

    <div class="modal-overlay" id="classModal">
        <div class="modal" style="max-width: 800px;">
            <div class="modal-header">
                <h3 class="modal-title">🏫 Buat Kelas Online</h3>
                <button class="modal-close" onclick="closeModal('classModal')">×</button>
            </div>
            <div class="modal-body">
                <form id="classForm" onsubmit="saveClass(event)">
                    <input type="hidden" name="id" id="classId">

                    <div class="form-row" style="grid-template-columns: 1fr 1fr;">
                        <div class="form-group">
                            <label class="form-label">Tajuk Kelas <span class="required">*</span></label>
                            <input type="text" class="form-control" name="title" id="classTitle" required
                                placeholder="cth: Kelas Matematik Online">
                        </div>

                        <div class="form-group">
                            <label class="form-label">Subjek <span class="required">*</span></label>
                            <select class="form-control form-select" name="subject" id="classSubject" required
                                onchange="loadStudentsForSelection('class')">
                                <option value="">Pilih Subjek</option>
                                <?php foreach ($teacherSubjects as $subject): ?>
                                    <option value="<?php echo htmlspecialchars($subject); ?>">
                                        <?php echo htmlspecialchars($subject); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="form-row" style="grid-template-columns: 1fr 1fr;">
                        <div class="form-group">
                            <label class="form-label">Tarikh <span class="required">*</span></label>
                            <input type="date" class="form-control" name="class_date" id="classDate" required>
                        </div>

                        <div class="form-group">
                            <label class="form-label">Akses Kelas</label>
                            <select class="form-control form-select" id="classAccessType"
                                onchange="toggleStudentSelection('class')">
                                <option value="all">Semua Pelajar</option>
                                <option value="specific">Pelajar Tertentu</option>
                            </select>
                        </div>
                    </div>

                    <!-- Student Selection Section -->
                    <div id="classStudentSelection"
                        style="display: none; margin-top: 15px; padding: 15px; background: #f8f9fa; border-radius: 8px;">
                        <div
                            style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                            <label class="form-label" style="margin: 0;"><strong>Pilih Pelajar:</strong></label>
                            <div>
                                <button type="button" class="btn btn-sm btn-secondary"
                                    onclick="selectAllStudents('class')">Pilih Semua</button>
                                <button type="button" class="btn btn-sm btn-secondary"
                                    onclick="deselectAllStudents('class')">Batalkan Semua</button>
                            </div>
                        </div>
                        <div style="max-height: 150px; overflow-y: auto; border: 1px solid #ddd; border-radius: 8px; padding: 10px; background: white;"
                            id="classStudentList">
                            <p class="text-muted text-center">Sila pilih subjek terlebih dahulu</p>
                        </div>
                    </div>

                    <div class="form-row" style="grid-template-columns: 1fr 1fr; margin-top: 15px;">
                        <div class="form-group">
                            <label class="form-label">Masa Mula <span class="required">*</span></label>
                            <input type="time" class="form-control" name="start_time" id="classStartTime" required>
                        </div>

                        <div class="form-group">
                            <label class="form-label">Masa Tamat</label>
                            <input type="time" class="form-control" name="end_time" id="classEndTime">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Pautan Sertai (Zoom/Google Meet)</label>
                        <input type="url" class="form-control" name="join_link" id="classJoinLink"
                            placeholder="https://zoom.us/j/...">
                    </div>

                    <div class="form-group">
                        <label class="form-label">Penerangan</label>
                        <textarea class="form-control" name="description" id="classDescription" rows="3"
                            placeholder="Penerangan kelas..."></textarea>
                    </div>

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

    <div class="modal-overlay" id="forumModal">
        <div class="modal" style="max-width: 750px;">
            <div class="modal-header">
                <h3 class="modal-title">💬 Tambah Forum</h3>
                <button class="modal-close" onclick="closeModal('forumModal')">×</button>
            </div>
            <div class="modal-body">
                <form id="forumForm" onsubmit="saveForum(event)">
                    <input type="hidden" name="id" id="forumId">

                    <div class="form-row" style="grid-template-columns: 1fr 1fr;">
                        <div class="form-group">
                            <label class="form-label">Tajuk <span class="required">*</span></label>
                            <input type="text" class="form-control" name="title" id="forumTitle" required
                                placeholder="cth: Soalan Matematik">
                        </div>

                        <div class="form-group">
                            <label class="form-label">Subjek <span class="required">*</span></label>
                            <select class="form-control form-select" name="subject" id="forumSubject" required
                                onchange="loadStudentsForSelection('forum')">
                                <option value="">Pilih Subjek</option>
                                <?php foreach ($teacherSubjects as $subject): ?>
                                    <option value="<?php echo htmlspecialchars($subject); ?>">
                                        <?php echo htmlspecialchars($subject); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="form-row" style="grid-template-columns: 1fr 1fr;">
                        <div class="form-group">
                            <label class="form-label">Sasaran</label>
                            <select class="form-control form-select" name="target_audience" id="forumTarget"
                                onchange="toggleStudentSelection('forum')">
                                <option value="all">Semua (Guru & Pelajar)</option>
                                <option value="students">Pelajar Saya Sahaja</option>
                                <option value="teachers">Guru Sahaja</option>
                                <option value="specific">Pelajar Tertentu</option>
                            </select>
                        </div>

                        <!-- Student Selection Section for Forum -->
                        <div class="form-group" id="forumStudentSelectionContainer" style="display: none;">
                            <label class="form-label">Akses Forum</label>
                            <select class="form-control form-select" id="forumAccessType"
                                onchange="toggleStudentSelection('forum')">
                                <option value="all_students">Semua Pelajar Saya</option>
                                <option value="specific_students">Pelajar Tertentu</option>
                            </select>
                        </div>
                    </div>

                    <!-- Student Selection Section -->
                    <div id="forumStudentSelection"
                        style="display: none; margin-top: 15px; padding: 15px; background: #f8f9fa; border-radius: 8px;">
                        <div
                            style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                            <label class="form-label" style="margin: 0;"><strong>Pilih Pelajar:</strong></label>
                            <div>
                                <button type="button" class="btn btn-sm btn-secondary"
                                    onclick="selectAllStudents('forum')">Pilih Semua</button>
                                <button type="button" class="btn btn-sm btn-secondary"
                                    onclick="deselectAllStudents('forum')">Batalkan Semua</button>
                            </div>
                        </div>
                        <div style="max-height: 150px; overflow-y: auto; border: 1px solid #ddd; border-radius: 8px; padding: 10px; background: white;"
                            id="forumStudentList">
                            <p class="text-muted text-center">Sila pilih subjek terlebih dahulu</p>
                        </div>
                    </div>

                    <div class="form-group" style="margin-top: 15px;">
                        <label class="form-label">Pautan Rujukan (Video/Dokumen)</label>
                        <input type="url" class="form-control" name="link" id="forumLink"
                            placeholder="https://youtube.com/... atau https://docs.google.com/...">
                    </div>

                    <div class="form-group">
                        <label class="form-label">Kandungan <span class="required">*</span></label>
                        <textarea class="form-control" name="content" id="forumContent" rows="5" required
                            placeholder="Tulis soalan atau topik..."></textarea>
                    </div>

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

    <div class="modal-overlay" id="announcementModal">
        <div class="modal" style="max-width: 650px;">
            <div class="modal-header">
                <h3 class="modal-title">📢 Buat Pengumuman</h3>
                <button class="modal-close" onclick="closeModal('announcementModal')">×</button>
            </div>
            <div class="modal-body">
                <form id="announcementForm" onsubmit="saveAnnouncement(event)">
                    <input type="hidden" name="id" id="announcementId">

                    <div class="form-group">
                        <label class="form-label">Tajuk <span class="required">*</span></label>
                        <input type="text" class="form-control" name="title" id="announcementTitle" required
                            placeholder="cth: Pengumuman Penting">
                    </div>

                    <div class="form-row" style="grid-template-columns: 1fr 1fr;">
                        <div class="form-group">
                            <label class="form-label">Kategori <span class="required">*</span></label>
                            <select class="form-control form-select" name="category" id="announcementCategory" required>
                                <option value="Umum">Umum</option>
                                <option value="Akademik">Akademik</option>
                                <option value="Aktiviti">Aktiviti</option>
                                <option value="Lain-lain">Lain-lain</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label class="form-label">Sasaran <span class="required">*</span></label>
                            <select class="form-control form-select" name="target_audience" id="announcementTarget"
                                required>
                                <option value="Semua">Semua (Guru & Pelajar)</option>
                                <option value="Guru Sahaja">Guru Sahaja</option>
                                <option value="Pelajar">Pelajar Sahaja</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Priority</label>
                        <select class="form-control form-select" name="priority" id="announcementPriority">
                            <option value="Normal">Normal</option>
                            <option value="Penting">Penting</option>
                            <option value="Urgent">Urgent</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Kandungan <span class="required">*</span></label>
                        <textarea class="form-control" name="content" id="announcementContent" rows="5" required
                            placeholder="Tulis pengumuman..."></textarea>
                    </div>

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

    <!-- Edit Announcement Modal -->
    <div class="modal-overlay" id="editAnnouncementModal">
        <div class="modal" style="max-width: 600px;">
            <div class="modal-header">
                <h3 class="modal-title">✏️ Kemaskini Pengumuman</h3>
                <button class="modal-close" onclick="closeModal('editAnnouncementModal')">×</button>
            </div>
            <div class="modal-body">
                <form id="editAnnouncementForm" onsubmit="updateAnnouncement(event)">
                    <input type="hidden" name="id" id="editAnnouncementId">

                    <div class="form-group">
                        <label class="form-label">Tajuk <span class="required">*</span></label>
                        <input type="text" class="form-control" name="title" id="editAnnouncementTitle" required>
                    </div>

                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                        <div class="form-group">
                            <label class="form-label">Sasaran <span class="required">*</span></label>
                            <select class="form-control form-select" name="target_audience" id="editAnnouncementTarget"
                                required>
                                <option value="Semua">Semua</option>
                                <option value="Guru Sahaja">Guru Sahaja</option>
                                <option value="Pelajar">Pelajar Sahaja</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Priority</label>
                            <select class="form-control form-select" name="priority" id="editAnnouncementPriority">
                                <option value="Normal">Normal</option>
                                <option value="Penting">Penting</option>
                                <option value="Urgent">Urgent</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Kandungan <span class="required">*</span></label>
                        <textarea class="form-control" name="content" id="editAnnouncementContent" rows="5"
                            required></textarea>
                    </div>

                    <div style="margin-top: 20px; display: flex; gap: 10px;">
                        <button type="button" class="btn btn-secondary" style="flex: 1;"
                            onclick="closeModal('editAnnouncementModal')">Batal</button>
                        <button type="submit" class="btn btn-primary" style="flex: 1;">💾 Simpan Perubahan</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 -->
    <div class="modal-overlay" id="moduleDetailModal">
        <div class="modal" style="max-width: 600px;">
            <div class="modal-header">
                <h3 class="modal-title">📚 Maklumat Modul</h3>
                <button class="modal-close" onclick="closeModal('moduleDetailModal')">×</button>
            </div>
            <div class="modal-body">
                <h4 id="moduleDetailTitle" style="margin-bottom: 10px;">-</h4>
                <span id="moduleDetailSubject" class="badge badge-primary" style="margin-bottom: 15px;">-</span>

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

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

                <div class="form-group">
                    <label class="form-label">Pautan</label>
                    <div id="moduleDetailLinks"></div>
                </div>

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

    <!-- Class Students Modal -->
    <div class="modal-overlay" id="classStudentsModal">
        <div class="modal" style="max-width: 500px;">
            <div class="modal-header">
                <h3 class="modal-title">👥 Pelajar - <span id="classDetailTitle"></span></h3>
                <button class="modal-close" onclick="closeModal('classStudentsModal')">×</button>
            </div>
            <div class="modal-body">
                <div id="classStudentsList" style="max-height: 300px; overflow-y: auto;">
                    <p class="text-center text-muted">Memuatkan...</p>
                </div>

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



    <!-- 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>

    <!-- ========== OPEN POOL MODALS ========== -->

    <!-- Open Pool Approve with Password Modal -->
    <div class="modal-overlay" id="openPoolApproveModal">
        <div class="modal" style="max-width: 550px;">
            <div class="modal-header">
                <h3 class="modal-title">🔑 Luluskan & Tetapkan Kata Laluan</h3>
                <button class="modal-close" onclick="closeModal('openPoolApproveModal')">×</button>
            </div>
            <div class="modal-body">
                <!-- Student Info Card -->
                <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 20px;">
                    <div style="display: flex; align-items: center; gap: 15px;">
                        <div style="font-size: 2.5rem;">👨‍🎓</div>
                        <div>
                            <h4 style="margin: 0;" id="openPoolApproveStudentName">-</h4>
                            <p style="margin: 5px 0 0 0; color: #666;" id="openPoolApproveStudentInfo">-</p>
                        </div>
                    </div>
                </div>

                <input type="hidden" id="openPoolApproveEnrollmentId" value="">
                <input type="hidden" id="openPoolApproveStudentId" value="">

                <!-- Password Setup Form -->
                <div
                    style="background: #fff3cd; padding: 15px; border-radius: 8px; margin-bottom: 20px; border-left: 4px solid #ffc107;">
                    <p style="margin: 0; font-weight: bold; color: #856404;">⚠️ WAJIB: Sila tetapkan kata laluan baharu
                        untuk pelajar sebelum meluluskan.</p>
                </div>

                <div class="form-check mb-3">
                    <input class="form-check-input" type="checkbox" id="useDefaultPassword"
                        onchange="togglePasswordFields()" checked>
                    <label class="form-check-label" for="useDefaultPassword">
                        Gunakan kata laluan lalai: <strong>student123</strong>
                    </label>
                </div>

                <div class="form-group">
                    <label class="form-label">Kata Laluan Baharu <span class="required">*</span></label>
                    <input type="password" class="form-control" id="openPoolStudentPassword" required
                        placeholder="Minima 6 aksara" minlength="6" disabled value="student123">
                </div>

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

                <div class="form-group">
                    <label class="form-label">Catatan (Optional)</label>
                    <textarea class="form-control" id="openPoolApproveNotes" rows="2"
                        placeholder="Catatan untuk pelajar..."></textarea>
                </div>

                <div style="margin-top: 20px; display: flex; gap: 10px;">
                    <button type="button" class="btn btn-secondary" style="flex: 1;"
                        onclick="closeModal('openPoolApproveModal')">Batal</button>
                    <button type="button" class="btn btn-success" style="flex: 1;" onclick="confirmOpenPoolApprove()">✅
                        Luluskan</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Open Pool Reject with Fallback Modal -->
    <div class="modal-overlay" id="openPoolRejectModal">
        <div class="modal" style="max-width: 550px;">
            <div class="modal-header">
                <h3 class="modal-title">❌ Tolak Pendaftaran (dengan Auto-Fallback)</h3>
                <button class="modal-close" onclick="closeModal('openPoolRejectModal')">×</button>
            </div>
            <div class="modal-body">
                <!-- Student Info Card -->
                <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 20px;">
                    <div style="display: flex; align-items: center; gap: 15px;">
                        <div style="font-size: 2.5rem;">👨‍🎓</div>
                        <div>
                            <h4 style="margin: 0;" id="openPoolRejectStudentName">-</h4>
                            <p style="margin: 5px 0 0 0; color: #666;" id="openPoolRejectStudentSubject">-</p>
                        </div>
                    </div>
                </div>

                <input type="hidden" id="openPoolRejectEnrollmentId" value="">

                <div class="form-group">
                    <label class="form-label">Sebab Penolakan <span class="required">*</span></label>
                    <select class="form-control form-select" id="openPoolRejectReason"
                        onchange="toggleCustomRejectReason()">
                        <option value="">Pilih sebab...</option>
                        <option value="Cuti">🏖️ Cuti/Luangkan masa</option>
                        <option value="Sibuk">📅 Terlalu sibuk</option>
                        <option value="Capacity">👥 Kapasiti penuh</option>
                        <option value="Bukan subjek">📚 Bukan subjek khusus</option>
                        <option value="Lain-lain">📝 Lain-lain</option>
                    </select>
                </div>

                <div class="form-group" id="openPoolCustomReasonGroup" style="display: none;">
                    <label class="form-label">Nyatakan sebab lain <span class="required">*</span></label>
                    <textarea class="form-control" id="openPoolRejectCustomReason" rows="3"
                        placeholder="Nyatakan sebab..."></textarea>
                </div>

                <!-- Fallback Options -->
                <div
                    style="background: #e8f4ff; padding: 15px; border-radius: 8px; margin-top: 15px; border-left: 4px solid #667eea;">
                    <p style="margin: 0 0 10px 0; font-weight: bold;">🔄 Auto-Fallback:</p>
                    <div style="display: flex; gap: 10px;">
                        <button type="button" class="btn btn-primary btn-sm" id="btnOpenPoolAutoFallback"
                            style="flex: 1;" onclick="setOpenPoolRejectType('auto')">
                            ⚡ Auto-assign ke guru lain
                        </button>
                        <button type="button" class="btn btn-secondary btn-sm" id="btnOpenPoolManualReject"
                            style="flex: 1;" onclick="setOpenPoolRejectType('manual')">
                            ❌ Tolak sahaja
                        </button>
                    </div>
                </div>

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

    <!-- Open Pool Student Detail Modal -->
    <div class="modal-overlay" id="openPoolStudentDetailModal">
        <div class="modal" style="max-width: 600px;">
            <div class="modal-header">
                <h3 class="modal-title">👨‍🎓 Maklumat Pelajar</h3>
                <button class="modal-close" onclick="closeModal('openPoolStudentDetailModal')">×</button>
            </div>
            <div class="modal-body">
                <div id="openPoolStudentDetailContent">
                    <!-- Content loaded dynamically -->
                </div>

                <div style="margin-top: 20px; display: flex; gap: 10px;">
                    <button type="button" class="btn btn-secondary" style="flex: 1;"
                        onclick="closeModal('openPoolStudentDetailModal')">Tutup</button>
                </div>
            </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 showAddStudentModal() {
            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
        function saveModule(event) {
            event.preventDefault();
            var formData = new FormData(document.getElementById('moduleForm'));
            formData.append('action', 'add_module');

            // Get selected students if "specific" is chosen
            var accessType = document.getElementById('moduleAccessType').value;
            if (accessType === 'specific') {
                var selectedStudents = [];
                document.querySelectorAll('#moduleStudentList input[type="checkbox"]:checked').forEach(function (cb) {
                    selectedStudents.push(cb.value);
                });
                formData.append('selected_students', JSON.stringify(selectedStudents));
            }

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success) {
                        showNotification('Modul berjaya disimpan', 'success');
                        closeModal('moduleModal');
                        loadModules();
                    } else {
                        showNotification(result.message, 'error');
                    }
                })
                .catch(function (err) {
                    showNotification('Ralat sambungan', 'error');
                });
        }

        // ========== 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 loadStudentsForSelection(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
        function saveSchedule(event) {
            event.preventDefault();
            var formData = new FormData(document.getElementById('scheduleForm'));
            formData.append('action', 'add_schedule');

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success) {
                        showNotification('Jadual berjaya disimpan', 'success');
                        closeModal('scheduleModal');
                        loadSchedule();
                    } else {
                        showNotification(result.message, 'error');
                    }
                })
                .catch(function (err) {
                    showNotification('Ralat sambungan', 'error');
                });
        }

        // Delete schedule function
        function deleteSchedule(id) {
            if (!confirm('Adakah anda pasti ingin memadam jadual ini?')) return;

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

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success) {
                        showNotification('Jadual berjaya dipadam', 'success');
                        loadSchedule();
                    } else {
                        showNotification(result.message, 'error');
                    }
                })
                .catch(function (err) {
                    showNotification('Ralat sambungan', 'error');
                });
        }

        // Class save function
        function saveClass(event) {
            event.preventDefault();
            var formData = new FormData(document.getElementById('classForm'));
            formData.append('action', 'add_class');

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success) {
                        showNotification('Kelas berjaya disimpan', 'success');
                        closeModal('classModal');
                        loadClasses();
                    } else {
                        showNotification(result.message, 'error');
                    }
                })
                .catch(function (err) {
                    showNotification('Ralat sambungan', 'error');
                });
        }

        // Forum save function
        function saveForum(event) {
            event.preventDefault();
            var formData = new FormData(document.getElementById('forumForm'));
            formData.append('action', 'add_forum');

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success) {
                        showNotification('Forum berjaya disimpan', 'success');
                        closeModal('forumModal');
                        loadForum();
                    } else {
                        showNotification(result.message, 'error');
                    }
                })
                .catch(function (err) {
                    showNotification('Ralat sambungan', 'error');
                });
        }
        // Fungsi untuk tukar kata laluan
        function updatePassword(event) {
            event.preventDefault();

            const newPass = document.getElementById('newPassword').value;
            const confirmPass = document.getElementById('confirmPassword').value;

            // Validasi ringkas di client-side
            if (newPass !== confirmPass) {
                showNotification('Kata laluan baru tidak sepadan!', 'error');
                return;
            }

            if (newPass.length < 6) {
                showNotification('Kata laluan mesti sekurang-kurangnya 6 aksara', 'error');
                return;
            }

            var formData = new FormData(document.getElementById('passwordForm'));
            formData.append('action', 'change_password'); // Action untuk API

            // UI Feedback
            var btn = event.target.querySelector('button');
            var originalText = btn.innerHTML;
            btn.innerHTML = '⏳ Sedang memproses...';
            btn.disabled = true;

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (res) {
                    if (res.success) {
                        showNotification('Kata laluan berjaya ditukar!', 'success');
                        document.getElementById('passwordForm').reset(); // Kosongkan borang
                    } else {
                        showNotification(res.message, 'error');
                    }
                })
                .catch(function (err) {
                    console.error(err);
                    showNotification('Ralat sambungan ke server', 'error');
                })
                .finally(function () {
                    btn.innerHTML = originalText;
                    btn.disabled = false;
                });
        }

        // Announcement save function
        function saveAnnouncement(event) {
            event.preventDefault();
            var formData = new FormData(document.getElementById('announcementForm'));
            formData.append('action', 'add_announcement');

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success) {
                        showNotification('Pengumuman berjaya dihantar', 'success');
                        closeModal('announcementModal');
                        loadAnnouncements();
                    } else {
                        showNotification(result.message, 'error');
                    }
                })
                .catch(function (err) {
                    showNotification('Ralat sambungan', 'error');
                });
        }

        // Open Edit Modal with Data
        function openEditAnnouncementModal(id, titleEncoded, contentEncoded, priority, target) {
            document.getElementById('editAnnouncementId').value = id;
            document.getElementById('editAnnouncementTitle').value = decodeURIComponent(titleEncoded);
            document.getElementById('editAnnouncementContent').value = decodeURIComponent(contentEncoded);
            document.getElementById('editAnnouncementPriority').value = priority;
            document.getElementById('editAnnouncementTarget').value = target;

            openModal('editAnnouncementModal');
        }

        // Update Announcement function
        function updateAnnouncement(event) {
            event.preventDefault();
            var formData = new FormData(document.getElementById('editAnnouncementForm'));
            formData.append('action', 'update_announcement');

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success) {
                        showNotification('Pengumuman berjaya dikemaskini', 'success');
                        closeModal('editAnnouncementModal');
                        loadAnnouncements();
                    } else {
                        showNotification(result.message, 'error');
                    }
                })
                .catch(function (err) {
                    showNotification('Ralat sambungan', 'error');
                });
        }

        // Delete Announcement function
        function deleteAnnouncement(id) {
            showConfirm('Hapus Pengumuman?', 'Adakah anda pasti ingin menghapus pengumuman ini? Tindakan ini tidak boleh dibatalkan.', function () {
                var formData = new FormData();
                formData.append('action', 'delete_announcement');
                formData.append('id', id);

                fetch(API_PATH, { method: 'POST', body: formData })
                    .then(function (response) { return response.json(); })
                    .then(function (result) {
                        if (result.success) {
                            showNotification('Pengumuman berjaya dihapus', 'success');
                            loadAnnouncements();
                        } else {
                            showNotification(result.message, 'error');
                        }
                    })
                    .catch(function (err) {
                        showNotification('Ralat sambungan', 'error');
                    });
            });
        }

        // ========== 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')) {
                    loadNotifications();
                }
            }
        }

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

        var notificationSystemInitialized = false;

        // Initialize notification system with bell animation
        function initNotificationSystem() {
            // 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(); switchTab(event, \'announcements\'); loadAnnouncements();" 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(); switchTab(event, \'forums\'); loadForums();" 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 loadNotifications() {
            console.log('loadNotifications 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) {
                        loadNotifications(); // Reload to update UI
                    }
                })
                .catch(function (err) {
                    console.error('Error marking notification as read:', err);
                });
        }

        // Mark all notifications as read
        function markAllNotificationsRead() {
            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) {
                        showNotification('Semua notifikasi telah dibaca', 'success');
                        loadNotifications();
                    }
                })
                .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) {
                        loadNotifications();
                    }
                })
                .catch(function (err) {
                    console.error('Error deleting notification:', err);
                });
        }

        // Delete all notifications
        function deleteAllNotifications() {
            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) {
                            showNotification('Semua notifikasi telah dipadam', 'success');
                            loadNotifications();
                        }
                    })
                    .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);
            }
            showNotification(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);
            showNotification(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);
                        showNotification(result.message, 'success');
                    } else {
                        // Revert toggle on error
                        var toggle = document.getElementById('statusToggle');
                        toggle.checked = !toggle.checked;
                        updateStatusUI(toggle.checked);
                        showNotification(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);
                    showNotification('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
                            loadStudents();
                            loadEnrollments();
                            loadTaughtStudents();
                            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 {
                                showNotification(syncResult.message || 'Ralat semasa penyelarasan', 'error');
                            }
                        })
                        .catch(function (err) {
                            Swal.close();
                            console.error('Error syncing student data:', err);
                            showNotification('Ralat sambungan semasa sync', 'error');
                        });
                }
            });
        }

        function loadEnrollments() {
            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');
                        if (pendingCountEl) pendingCountEl.textContent = result.stats.pending || 0;
                        if (approvedCountEl) approvedCountEl.textContent = result.stats.approved || 0;
                        if (rejectedCountEl) rejectedCountEl.textContent = result.stats.rejected || 0;

                        // 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) {
                        showNotification('Maklumat pendaftaran berjaya dikemaskini!', 'success');
                        closeModal('editEnrollmentModal');
                        loadEnrollments(); // Reload enrollments list
                    } else {
                        showNotification(result.message, 'error');
                    }
                })
                .catch(function (err) {
                    console.error('Error updating enrollment:', err);
                    showNotification('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=Approved')
                .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) {
                                        showNotification('Pelajar berjaya diluluskan', 'success');
                                        loadEnrollments();
                                        loadStudents();
                                    } else {
                                        showNotification(res.message, 'error');
                                    }
                                })
                                .catch(function (err) {
                                    showNotification('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) {
                    showNotification('Kata laluan tidak sepadan!', 'error');
                    return;
                }

                if (newPassword.length < 6) {
                    showNotification('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) {
                            showNotification('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 {
                            showNotification(result.message, 'error');
                        }
                    })
                    .catch(function (err) {
                        showNotification('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) {
                                showNotification('Pelajar berjaya diluluskan! 🎉', 'success');
                                loadEnrollments();
                                loadStudents();
                                loadPendingPasswordStudents();
                            } else {
                                showNotification(res.message, 'error');
                            }
                        })
                        .catch(function (err) {
                            showNotification('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,
                showConfirmButton: 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 { loadEnrollments(); }
                    } else {
                        showNotification(result.message, 'error');
                    }
                })
                .catch(function (err) {
                    showNotification('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) {
                showNotification('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) {
                        showNotification('Pelajar berjaya diassign!', 'success');
                        closeModal('quickAssignModal');
                        loadUnassignedStudents();
                        loadEnrollments();
                    } else {
                        showNotification(result.message, 'error');
                    }
                })
                .catch(function (err) {
                    showNotification('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 loadNotifications() {
            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) {
                        loadNotifications();
                    }
                })
                .catch(function (err) {
                    console.error('Error marking notification read:', err);
                });
        }

        // Mark all notifications as read
        function markAllNotificationsRead() {
            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) {
                        showNotification('Semua notifikasi telah dibaca', 'success');
                        loadNotifications();
                    }
                })
                .catch(function (err) {
                    console.error('Error marking all notifications read:', err);
                });
        }

        // Delete all notifications
        function deleteAllNotifications() {
            // 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) {
                                showNotification('Semua notifikasi telah dipadam', 'success');
                                loadNotifications();
                            } else {
                                showNotification(result.message, 'error');
                            }
                        })
                        .catch(function (err) {
                            console.error('Error deleting all notifications:', err);
                            showNotification('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(loadNotifications, 30000);
            } else {
                if (notificationInterval) {
                    clearInterval(notificationInterval);
                    notificationInterval = null;
                }
            }

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

        // Load maintenance logs
        function loadMaintenanceLogs() {
            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 loadPendingPasswordStudents() {
            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) {
                showNotification('Kata laluan tidak sepadan!', 'error');
                return;
            }

            if (newPassword.length < 6) {
                showNotification('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) {
                        showNotification('Kata laluan pelajar berjaya ditetapkan!', 'success');
                        closeModal('setupPasswordModal');
                        document.getElementById('setupPasswordForm').reset();
                        loadPendingPasswordStudents();
                    } else {
                        showNotification(result.message, 'error');
                    }
                })
                .catch(function (err) {
                    showNotification('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 loadNotifications() {
            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) {
                        loadNotifications();
                    }
                })
                .catch(function (err) {
                    console.error('Error marking notification read:', err);
                });
        }

        // Mark all notifications as read
        function markAllNotificationsRead() {
            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) {
                        showNotification('Semua notifikasi telah dibaca', 'success');
                        loadNotifications();
                    }
                })
                .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')) {
                loadNotifications();
            }
        }

        // 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(loadNotifications, 30000);
            } else {
                // Stop auto-refresh
                if (notificationInterval) {
                    clearInterval(notificationInterval);
                    notificationInterval = null;
                }
            }

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

        // ========== MAINTENANCE LOGS FUNCTIONS ==========
        function loadMaintenanceLogs() {
            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>';
                });
        }

        // ========== PENDING PASSWORD STUDENTS ==========
        function loadPendingPasswordStudents() {
            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) {
                showNotification('Kata laluan tidak sepadan!', 'error');
                return;
            }

            if (newPassword.length < 6) {
                showNotification('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) {
                        showNotification('Kata laluan pelajar berjaya ditetapkan!', 'success');
                        closeModal('setupPasswordModal');
                        document.getElementById('setupPasswordForm').reset();
                        loadPendingPasswordStudents();
                    } else {
                        showNotification(result.message, 'error');
                    }
                })
                .catch(function (err) {
                    showNotification('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(loadNotifications, 30000);
            } else {
                clearInterval(notificationInterval);
            }
        }

        // Load notifications
        function loadNotifications() {
            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');
            loadNotifications();
        }

        // Mark all notifications as read
        function markAllNotificationsRead() {
            lastNotificationCount = 0;
            document.getElementById('notificationCount').style.display = 'none';
            document.getElementById('notificationBellBtn').classList.remove('has-notifications');
            showNotification('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 loadMaintenanceLogs() {
            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 loadPendingPasswordStudents() {
            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) {
                showNotification('Kata laluan tidak sepadan!', 'error');
                return;
            }

            if (newPassword.length < 6) {
                showNotification('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) {
                        showNotification('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
                            loadPendingPasswordStudents();
                        }
                    } else {
                        showNotification(result.message, 'error');
                    }
                })
                .catch(function (err) {
                    showNotification('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
            loadNotifications();

            // Check for new notifications every 30 seconds
            if (autoRefreshEnabled) {
                notificationInterval = setInterval(loadNotifications, 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 loadNotifications() {
            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'
                                });
                                loadNotifications();
                            } 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')) {
                    loadNotifications();
                }
            } 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) {
                    loadNotifications();
                    // Handle specific notification actions
                    if (type === 'announcement') {
                        switchTab(null, 'announcements');
                    } else if (type === 'forum') {
                        switchTab(null, 'forum');
                    } else if (type === 'enrollment' || type === 'student') {
                        switchTab(null, 'enrollments');
                    }
                    document.getElementById('notificationDropdown').classList.remove('show');
                });
        }

        function markAllNotificationsRead() {
            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) {
                    loadNotifications();
                    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 loadMaintenanceLogs() {
            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 loadPendingPasswordStudents() {
            // 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) {
                showNotification('Kata laluan tidak sepadan!', 'error');
                return;
            }

            if (newPassword.length < 6) {
                showNotification('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) {
                        showNotification('Kata laluan pelajar berjaya ditetapkan!', 'success');
                        closeModal('setupPasswordModal');
                        document.getElementById('setupPasswordForm').reset();
                    } else {
                        showNotification(result.message, 'error');
                    }
                })
                .catch(function (err) {
                    showNotification('Ralat sambungan', 'error');
                })
                .finally(function () {
                    btn.disabled = false;
                    btn.innerHTML = originalText;
                });
        }

        // ========== OPEN POOL FUNCTIONS ==========

        // Store open pool students data
        var openPoolStudentsData = [];

        // Load Open Pool students
        function loadOpenPoolStudents() {
            var subjectFilter = document.getElementById('openPoolSubjectFilter').value;
            var container = document.getElementById('openPoolStudentsContainer');

            container.innerHTML = '<div style="text-align: center; padding: 50px 20px;"><div style="font-size: 3rem; margin-bottom: 15px;">🌊</div><p class="text-muted" style="font-size: 1.1rem;">Memuatkan pelajar dari Open Pool...</p></div>';

            // Fetch students who are in open pool (no teacher assigned or rejected by all teachers)
            fetch(API_PATH + '?action=get_open_pool_students' + (subjectFilter ? '&subject=' + encodeURIComponent(subjectFilter) : ''))
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success && result.students) {
                        openPoolStudentsData = result.students;
                        displayOpenPoolStudents(openPoolStudentsData);
                        refreshOpenPoolStats();
                    } else {
                        container.innerHTML = '<div style="text-align: center; padding: 50px 20px;"><div style="font-size: 3rem; margin-bottom: 15px;">🌊</div><p class="text-muted" style="font-size: 1.1rem;">Tiada pelajar dalam Open Pool</p></div>';
                    }
                })
                .catch(function (err) {
                    console.error('Error loading open pool students:', err);
                    container.innerHTML = '<div style="text-align: center; padding: 50px 20px;"><div style="font-size: 3rem; margin-bottom: 15px;">❌</div><p class="text-danger">Ralat memuatkan data</p></div>';
                });
        }

        // Display Open Pool students in a grid
        function displayOpenPoolStudents(students) {
            var container = document.getElementById('openPoolStudentsContainer');
            var badge = document.getElementById('openPoolTotalBadge');

            badge.textContent = students.length + ' pelajar';

            if (!students || students.length === 0) {
                container.innerHTML = '<div style="text-align: center; padding: 50px 20px;"><div style="font-size: 3rem; margin-bottom: 15px;">🌊</div><p class="text-muted" style="font-size: 1.1rem;">Tiada pelajar menunggu untuk subjek yang anda ajar</p></div>';
                return;
            }

            var html = '<div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 20px;">';

            students.forEach(function (s) {
                // Handle new data format from API (students table only)
                var studentId = s.student_id || s.id;
                var studentName = s.student_name || s.full_name || '';
                var studentPhone = s.student_phone || s.phone || '';
                var parentName = s.parent_guardian_name || '';
                var educationLevel = s.education_level || '';
                var gradeLevel = s.grade_level || '';
                var matchingSubjects = s.matching_subjects || [];
                var subjectDisplay = matchingSubjects.length > 0 ? matchingSubjects.join(', ') : 'Tiada subjek';

                // All students from Open Pool are "Menunggu" status
                var statusBadge = '⏳ Menunggu';
                var statusClass = 'warning';

                html += '<div class="card" style="border-left: 4px solid #ffc107;">';
                html += '<div class="card-body">';
                html += '<div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 15px;">';
                html += '<div style="display: flex; align-items: center; gap: 15px;">';
                html += '<div style="font-size: 2.5rem;">👨‍🎓</div>';
                html += '<div>';
                html += '<h5 style="margin: 0;">' + studentName + '</h5>';
                html += '<small style="color: #666;">' + (educationLevel ? educationLevel + ' - ' + gradeLevel : (educationLevel || gradeLevel || '-')) + '</small>';
                html += '</div></div>';
                html += '<span class="badge badge-' + statusClass + '">' + statusBadge + '</span>';
                html += '</div>';

                html += '<div style="font-size: 0.9rem; margin-bottom: 15px;">';
                html += '<p style="margin: 5px 0;"><strong>📚 Subjek:</strong> ' + subjectDisplay + '</p>';
                html += '<p style="margin: 5px 0;"><strong>📞</strong> ' + (studentPhone || '-') + '</p>';
                html += '<p style="margin: 5px 0;"><strong>👤 Penjaga:</strong> ' + (parentName || '-') + '</p>';
                html += '</div>';

                // Action buttons
                html += '<div style="display: flex; gap: 10px; flex-wrap: wrap;">';

                // All students in Open Pool need approval
                html += '<button class="btn btn-success btn-sm" onclick="showOpenPoolApproveModal(' + studentId + ', \'' + studentName.replace(/'/g, "\\'") + '\', \'' + studentPhone.replace(/'/g, "\\'") + '\', \'' + subjectDisplay.replace(/'/g, "\\'") + '\')">🔑 Lulus & Kata Laluan</button>';
                html += '<button class="btn btn-danger btn-sm" onclick="showOpenPoolRejectModal(' + studentId + ', \'' + studentName.replace(/'/g, "\\'") + '\', \'' + subjectDisplay.replace(/'/g, "\\'") + '\')">❌ Tolak</button>';

                html += '<button class="btn btn-info btn-sm" onclick="viewOpenPoolStudentDetails(' + studentId + ')">👁️ Maklumat</button>';
                html += '</div>';

                html += '</div></div>';
            });

            html += '</div>';
            container.innerHTML = html;
        }

        // Refresh Open Pool statistics
        function refreshOpenPoolStats() {
            fetch(API_PATH + '?action=get_open_pool_stats')
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success) {
                        document.getElementById('openPoolPendingCount').textContent = result.stats.pending || 0;
                        document.getElementById('openPoolApprovedToday').textContent = result.stats.approved_today || 0;

                        // Update stats grid
                        document.getElementById('openPoolStatPending').textContent = result.stats.pending || 0;
                        document.getElementById('openPoolStatApproved').textContent = result.stats.approved || 0;
                        document.getElementById('openPoolStatRejected').textContent = result.stats.rejected || 0;
                        document.getElementById('openPoolStatTotal').textContent = result.stats.total || 0;
                    }
                })
                .catch(function (err) {
                    console.error('Error refreshing open pool stats:', err);
                });
        }

        // Show approve modal for Open Pool
        function showOpenPoolApproveModal(id, name, phone, subject) {
            document.getElementById('openPoolApproveEnrollmentId').value = id;
            document.getElementById('openPoolApproveStudentId').value = id;
            document.getElementById('openPoolApproveStudentName').textContent = name;
            document.getElementById('openPoolApproveStudentInfo').textContent = (phone ? '📞 ' + phone : '📚 ' + subject);

            // Reset password fields
            document.getElementById('openPoolStudentPassword').value = '';
            document.getElementById('openPoolStudentConfirmPassword').value = '';
            document.getElementById('openPoolApproveNotes').value = '';

            openModal('openPoolApproveModal');
        }

        // Confirm Open Pool approve with password
        function confirmOpenPoolApprove() {
            var enrollmentId = document.getElementById('openPoolApproveEnrollmentId').value;
            var studentId = document.getElementById('openPoolApproveStudentId').value;
            var password = document.getElementById('openPoolStudentPassword').value;
            var confirmPassword = document.getElementById('openPoolStudentConfirmPassword').value;
            var notes = document.getElementById('openPoolApproveNotes').value;

            // Validate password
            if (password.length < 6) {
                showNotification('Kata laluan minima 6 aksara!', 'error');
                return;
            }

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

            var formData = new FormData();
            formData.append('action', 'approve_open_pool_student');
            formData.append('enrollment_id', enrollmentId);
            formData.append('student_id', studentId);
            formData.append('new_password', password);
            formData.append('notes', notes);

            var btn = document.querySelector('#openPoolApproveModal .btn-success');
            var originalText = btn.textContent;
            btn.disabled = true;
            btn.textContent = '⏳ Sedang memproses...';

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Berjaya!',
                            text: 'Pelajar berjaya diluluskan dan kata laluan ditetapkan.',
                            timer: 2000,
                            showConfirmButton: false
                        });
                        closeModal('openPoolApproveModal');
                        if (typeof loadStudentManagementData === 'function') {
                            loadStudentManagementData();
                        } else {
                            loadOpenPoolStudents();
                            refreshOpenPoolStats();
                        }
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Ralat',
                            text: result.message
                        });
                    }
                })
                .catch(function (err) {
                    console.error('Error approving open pool student:', err);
                    Swal.fire({
                        icon: 'error',
                        title: 'Ralat Sambungan',
                        text: 'Sila cuba lagi nanti.'
                    });
                })
                .finally(function () {
                    btn.disabled = false;
                    btn.textContent = originalText;
                });
        }

        // Variables for Open Pool reject
        var openPoolRejectType = 'manual';
        var openPoolCurrentRejectData = null;

        // Show reject modal for Open Pool
        function showOpenPoolRejectModal(id, name, subject) {
            openPoolCurrentRejectData = { id: id, name: name, subject: subject };

            document.getElementById('openPoolRejectEnrollmentId').value = id;
            document.getElementById('openPoolRejectStudentName').textContent = name;
            document.getElementById('openPoolRejectStudentSubject').textContent = '📚 ' + subject;

            // Reset form
            document.getElementById('openPoolRejectReason').value = '';
            document.getElementById('openPoolRejectCustomReason').value = '';
            document.getElementById('openPoolCustomReasonGroup').style.display = 'none';

            // Reset buttons
            document.getElementById('btnOpenPoolAutoFallback').classList.remove('btn-primary');
            document.getElementById('btnOpenPoolAutoFallback').classList.add('btn-secondary');
            document.getElementById('btnOpenPoolManualReject').classList.remove('btn-secondary');
            document.getElementById('btnOpenPoolManualReject').classList.add('btn-primary');

            openPoolRejectType = 'manual';

            openModal('openPoolRejectModal');
        }

        // Toggle custom reason field
        function toggleCustomRejectReason() {
            var reason = document.getElementById('openPoolRejectReason').value;
            var customGroup = document.getElementById('openPoolCustomReasonGroup');
            customGroup.style.display = reason === 'Lain-lain' ? 'block' : 'none';
        }

        // Set reject type (auto-fallback or manual)
        function setOpenPoolRejectType(type) {
            openPoolRejectType = type;

            var autoBtn = document.getElementById('btnOpenPoolAutoFallback');
            var manualBtn = document.getElementById('btnOpenPoolManualReject');

            if (type === 'auto') {
                autoBtn.classList.remove('btn-secondary');
                autoBtn.classList.add('btn-primary');
                manualBtn.classList.remove('btn-primary');
                manualBtn.classList.add('btn-secondary');
            } else {
                manualBtn.classList.remove('btn-secondary');
                manualBtn.classList.add('btn-primary');
                autoBtn.classList.remove('btn-primary');
                autoBtn.classList.add('btn-secondary');
            }
        }

        // Confirm Open Pool reject
        function confirmOpenPoolReject() {
            if (!openPoolCurrentRejectData) return;

            var enrollmentId = openPoolCurrentRejectData.id;
            var reason = document.getElementById('openPoolRejectReason').value;
            var customReason = document.getElementById('openPoolRejectCustomReason').value;

            // Build full reason
            var fullReason = reason;
            if (reason === 'Lain-lain') {
                fullReason = customReason || 'Lain-lain';
            }

            if (!fullReason) {
                showNotification('Sila pilih atau nyatakan sebab penolakan!', 'warning');
                return;
            }

            var formData = new FormData();
            formData.append('action', openPoolRejectType === 'auto' ? 'reject_with_auto_fallback' : 'reject_student');
            formData.append('enrollment_id', enrollmentId);
            formData.append('reason', fullReason);

            var btn = document.getElementById('btnOpenPoolConfirmReject');
            var originalText = btn.textContent;
            btn.disabled = true;
            btn.textContent = '⏳ Sedang memproses...';

            fetch(API_PATH, { method: 'POST', body: formData })
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success) {
                        var message = openPoolRejectType === 'auto'
                            ? 'Pendaftaran ditolak dan pelajar akan di-auto-assign ke guru lain yang sesuai.'
                            : 'Pendaftaran ditolak.';
                        Swal.fire({
                            icon: 'success',
                            title: 'Selesai',
                            text: message,
                            timer: 2500,
                            showConfirmButton: false
                        });
                        closeModal('openPoolRejectModal');
                        loadOpenPoolStudents();
                        refreshOpenPoolStats();
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Ralat',
                            text: result.message
                        });
                    }
                })
                .catch(function (err) {
                    console.error('Error rejecting open pool student:', err);
                    Swal.fire({
                        icon: 'error',
                        title: 'Ralat Sambungan',
                        text: 'Sila cuba lagi nanti.'
                    });
                })
                .finally(function () {
                    btn.disabled = false;
                    btn.textContent = originalText;
                });
        }

        // View Open Pool student details
        function viewOpenPoolStudentDetails(studentId) {
            // Find student in open pool data
            var student = openPoolStudentsData.find(function (s) { return s.id === studentId; });

            if (!student) {
                showNotification('Pelajar tidak dijumpai', 'error');
                return;
            }

            var subjects = [];
            try {
                subjects = JSON.parse(student.required_subjects || '[]');
            } catch (e) {
                subjects = [];
            }

            var content = '<div style="text-align: center; margin-bottom: 20px;">';
            content += '<div style="font-size: 4rem; margin-bottom: 15px;">👨‍🎓</div>';
            content += '<h4 style="margin: 0;">' + (student.full_name || '-') + '</h4>';
            content += '</div>';

            content += '<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 20px;">';
            content += '<div><strong>Umur:</strong> ' + (student.age || '-') + ' tahun</div>';
            content += '<div><strong>Telefon:</strong> ' + (student.phone || '-') + '</div>';
            content += '<div><strong>Tahap:</strong> ' + (student.education_level || '-') + '</div>';
            content += '<div><strong>Kelas:</strong> ' + (student.grade_level || '-') + '</div>';
            content += '<div><strong>Penjaga:</strong> ' + (student.parent_guardian_name || '-') + '</div>';
            content += '<div><strong>Status:</strong> <span class="badge badge-warning">' + (student.status || 'Menunggu') + '</span></div>';
            content += '</div>';

            content += '<div style="margin-bottom: 20px;">';
            content += '<strong>Subjek Diperlukan:</strong><br>';
            content += '<div style="margin-top: 10px;">';
            subjects.forEach(function (sub) {
                content += '<span class="badge badge-primary" style="margin: 2px;">' + sub + '</span>';
            });
            if (subjects.length === 0) {
                content += '<span class="text-muted">Tiada subjek</span>';
            }
            content += '</div></div>';

            if (student.notes) {
                content += '<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 20px;">';
                content += '<strong>Nota:</strong><br>' + student.notes;
                content += '</div>';
            }

            if (student.rejected_reason) {
                content += '<div style="background: #f8d7da; padding: 15px; border-radius: 8px; border-left: 4px solid #dc3545;">';
                content += '<strong>⚠️ Sewasta Penolakan:</strong><br>' + student.rejected_reason;
                content += '</div>';
            }

            document.getElementById('openPoolStudentDetailContent').innerHTML = content;
            openModal('openPoolStudentDetailModal');
        }
    </script>
</body>

</html>