/**
 * TutorKita - Student Dashboard JavaScript
 * All functionality for student dashboard
 * Handles: API calls, UI interactions, data display
 */

// API Base path
const API_PATH = '../api.php';

// Global data storage
var allSchedules = [];
var allModules = [];
var allClasses = [];
var allForums = [];
var allAnnouncements = [];

// ========== DASHBOARD TAB FUNCTIONS ==========

/**
 * Load all dashboard data
 */
function loadDashboardData() {
    loadTodaySchedule();
    loadRecentAnnouncements();
    loadDashboardStats();
    loadStudentContacts();
    updateBannerDay();
}

/**
 * Update banner day display
 */
function updateBannerDay() {
    const days = ['Ahad', 'Isnin', 'Selasa', 'Rabu', 'Khamis', 'Jumaat', 'Sabtu'];
    const now = new Date();
    const dayName = days[now.getDay()];
    const dateStr = now.toLocaleDateString('ms-MY', {
        day: 'numeric',
        month: 'long',
        year: 'numeric'
    });
    const bannerDay = document.getElementById('bannerDay');
    if (bannerDay) {
        bannerDay.textContent = `📅 ${dayName}, ${dateStr}`;
    }
}

/**
 * Load month's schedule widget
 */
function loadTodaySchedule() {
    fetch(API_PATH + '?action=get_student_schedule')
        .then(response => response.json())
        .then(result => {
            var container = document.getElementById('todayScheduleWidget');

            if (result.success && result.schedules && result.schedules.length > 0) {
                var now = new Date();
                var currentMonthPrefix = now.getFullYear() + '-' + String(now.getMonth() + 1).padStart(2, '0');

                // Filter schedules for current month
                var monthSchedules = result.schedules.filter(s => s.schedule_date.startsWith(currentMonthPrefix));

                if (monthSchedules.length > 0) {
                    var html = '';
                    // Sort by date then time
                    monthSchedules.sort((a, b) => {
                        if (a.schedule_date !== b.schedule_date) return a.schedule_date.localeCompare(b.schedule_date);
                        return a.start_time.localeCompare(b.start_time);
                    });

                    monthSchedules.slice(0, 3).forEach(s => {
                        html += '<div class="premium-card animate__animated animate__fadeInUp" style="padding: 20px; margin-bottom: 12px; border-left: 5px solid var(--primary-color);">';
                        html += '<div style="display: flex; justify-content: space-between; align-items: center;">';
                        html += '<div>';
                        html += '<div style="font-weight: 700; color: #1e293b; font-size: 1.05rem;">' + s.subject + '</div>';
                        html += '<div style="font-size: 0.85rem; color: #64748b; margin-top: 4px;">📅 ' + s.schedule_date + ' | ‍🏫 Cikgu ' + (s.teacher_name || 'Guru') + '</div>';
                        html += '</div>';
                        html += '<div style="text-align: right;">';
                        html += '<div style="background: var(--primary-color); color: white; padding: 4px 12px; border-radius: 20px; font-weight: 700; font-size: 0.85rem; box-shadow: 0 4px 10px rgba(102, 126, 234, 0.3);">🕐 ' + s.start_time + '</div>';
                        html += '</div>';
                        html += '</div>';
                        html += '</div>';
                    });

                    if (document.getElementById('classTodayCount')) {
                        document.getElementById('classTodayCount').textContent = monthSchedules.length;
                    }

                    if (monthSchedules.length > 3) {
                        html += '<div style="text-align: center; margin-top: 10px;">';
                        html += '<a href="#" onclick="switchTab(event, \'schedule\')" class="btn btn-sm btn-outline-primary">Lihat ' + (monthSchedules.length - 3) + ' lagi</a>';
                        html += '</div>';
                    }

                    container.innerHTML = html;
                } else {
                    container.innerHTML = '<p class="text-center text-muted">Tiada sesi kelas untuk bulan ini 😊</p>';
                    if (document.getElementById('classTodayCount')) {
                        document.getElementById('classTodayCount').textContent = '0';
                    }
                }
            } else {
                container.innerHTML = '<p class="text-center text-muted">Tiada jadual. Sila hubungi guru anda.</p>';
                if (document.getElementById('classTodayCount')) {
                    document.getElementById('classTodayCount').textContent = '0';
                }
            }
        })
        .catch(err => {
            console.error('Error loading month schedule:', err);
            document.getElementById('todayScheduleWidget').innerHTML = '<p class="text-center text-danger">Ralat memuatkan jadual</p>';
        });
}

/**
 * Load recent announcements widget
 */
function loadRecentAnnouncements() {
    fetch(API_PATH + '?action=get_announcements')
        .then(response => response.json())
        .then(result => {
            var container = document.getElementById('recentAnnouncementsWidget');

            if (result.success && result.announcements && result.announcements.length > 0) {
                var html = '';
                result.announcements.slice(0, 3).forEach(a => {
                    var priorityStyle = a.priority === 'Urgent' ? 'background: #fef2f2; color: #ef4444; border: 1px solid #fee2e2;' :
                        a.priority === 'Penting' ? 'background: #fffbeb; color: #f59e0b; border: 1px solid #fef3c7;' : 'background: #f8fafc; color: #64748b; border: 1px solid #f1f5f9;';

                    html += '<div class="premium-card animate__animated animate__fadeInUp" style="padding: 16px; margin-bottom: 12px;">';
                    html += '<div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 10px;">';
                    html += '<div style="font-weight: 700; color: #1e293b; font-size: 0.95rem; flex: 1; padding-right: 10px;">' + a.title + '</div>';
                    html += '<span style="padding: 4px 10px; border-radius: 8px; font-size: 0.7rem; font-weight: 800; text-transform: uppercase; ' + priorityStyle + '">' + a.priority + '</span>';
                    html += '</div>';
                    html += '<div style="font-size: 0.85rem; color: #64748b; line-height: 1.5; margin-bottom: 12px;">' + truncateText(a.content, 90) + '</div>';
                    html += '<div style="display: flex; justify-content: space-between; align-items: center;">';
                    html += '<small style="color: #94a3b8; font-weight: 500;">👨‍🏫 Cikgu ' + (a.teacher_name || 'Pentadbir') + '</small>';
                    html += '<button onclick="viewAnnouncementDetail(' + a.id + ')" style="background: none; border: none; color: var(--primary-color); font-weight: 700; font-size: 0.8rem; padding: 0;">Lihat Penuh →</button>';
                    html += '</div>';
                    html += '</div>';
                });

                if (result.announcements.length > 3) {
                    html += '<div style="text-align: center; margin-top: 10px;">';
                    html += '<a href="#" onclick="switchTab(event, \'announcements\')" class="btn btn-sm btn-outline-primary">Lihat ' + (result.announcements.length - 3) + ' lagi</a>';
                    html += '</div>';
                }

                container.innerHTML = html;
            } else {
                container.innerHTML = '<p class="text-center text-muted">Tiada pengumuman terkini</p>';
            }
        })
        .catch(err => {
            console.error('Error loading announcements:', err);
            document.getElementById('recentAnnouncementsWidget').innerHTML = '<p class="text-center text-danger">Ralat memuatkan pengumuman</p>';
        });
}

function loadStudentContacts() {
    fetch(API_PATH + '?action=get_student_contacts')
        .then(function (response) { return response.json(); })
        .then(function (result) {
            var container = document.getElementById('studentContactsWidget');
            if (!container) return;
            if (result.success) {
                var html = '';
                var mentor = result.mentor || null;
                var additional = result.additional_teachers || [];
                if (mentor) {
                    var mp = mentor.phone || '';
                    var mpDigits = String(mp).replace(/\D/g, '');
                    var waLink = mpDigits ? ('https://wa.me/' + mpDigits) : '#';
                    html += '<div class="premium-card animate__animated animate__fadeInUp" style="padding:16px; margin-bottom:12px; border-left:5px solid var(--primary-color);">';
                    html += '<div style="display:flex; justify-content:space-between; align-items:center;">';
                    html += '<div>';
                    html += '<div style="font-weight:800; color:#1e293b; font-size:1rem;">👨‍🏫 Mentor Utama</div>';
                    html += '<div style="font-size:0.9rem; color:#475569; margin-top:4px;"> Cikgu ' + mentor.full_name + '</div>';
                    html += '<div style="font-size:0.85rem; color:#64748b; margin-top:4px;">📞 ' + (mp || '-') + '</div>';
                    html += '</div>';
                    html += '<div class="contact-actions" style="display:flex; gap:8px; flex-wrap:wrap; align-items:center; justify-content:flex-end;">';
                    html += '<a href="' + waLink + '" target="_blank" class="btn btn-sm btn-success rounded-pill d-flex align-items-center gap-2"><i class="fab fa-whatsapp"></i><span>WhatsApp</span></a>';
                    html += '<a href="tel:' + mp + '" class="btn btn-sm btn-outline-primary rounded-pill d-flex align-items-center gap-2"><i class="fas fa-phone"></i><span>Panggil</span></a>';
                    html += '</div>';
                    html += '</div>';
                    html += '</div>';
                }
                if (additional && additional.length > 0) {
                    html += '<div class="premium-card animate__animated animate__fadeInUp" style="padding:16px; margin-bottom:12px;">';
                    html += '<div style="font-weight:800; color:#1e293b; font-size:1rem; margin-bottom:8px;">✨ Guru Tambahan</div>';
                    additional.forEach(function (t) {
                        var tp = t.phone || '';
                        var tpDigits = String(tp).replace(/\D/g, '');
                        var waLinkT = tpDigits ? ('https://wa.me/' + tpDigits) : '#';
                        html += '<div style="display:flex; justify-content:space-between; align-items:center; padding:8px 0; border-top:1px solid #f1f5f9;">';
                        html += '<div>';
                        html += '<div style="font-size:0.9rem; color:#334155;"> Cikgu ' + t.full_name + '</div>';
                        html += '<div style="font-size:0.85rem; color:#64748b;">📞 ' + (tp || '-') + '</div>';
                        html += '</div>';
                        html += '<div class="contact-actions" style="display:flex; gap:8px; flex-wrap:wrap; align-items:center; justify-content:flex-end;">';
                        html += '<a href="' + waLinkT + '" target="_blank" class="btn btn-sm btn-success rounded-pill d-flex align-items-center gap-2"><i class="fab fa-whatsapp"></i><span>WhatsApp</span></a>';
                        html += '<a href="tel:' + tp + '" class="btn btn-sm btn-outline-primary rounded-pill d-flex align-items-center gap-2"><i class="fas fa-phone"></i><span>Panggil</span></a>';
                        html += '</div>';
                        html += '</div>';
                    });
                    html += '</div>';
                }
                html += '<p class="text-center text-muted" style="margin-top:8px;">info : Jika perlukan bantuan, boleh berhubung dengan Tutor anda.</p>';
                if (!mentor && (!additional || additional.length === 0)) {
                    html = '<p class="text-center text-muted">Tiada kontak ditemui</p>' + html;
                }
                container.innerHTML = html;
            } else {
                container.innerHTML = '<p class="text-center text-danger">Ralat memuatkan kontak</p>';
            }
        })
        .catch(function (err) {
            var container = document.getElementById('studentContactsWidget');
            if (container) container.innerHTML = '<p class="text-center text-danger">Ralat memuatkan kontak</p>';
        });
}

/**
 * Load dashboard statistics
 */
function loadDashboardStats() {
    // Load upcoming classes count
    fetch(API_PATH + '?action=get_student_classes')
        .then(response => response.json())
        .then(result => {
            if (result.success && result.classes) {
                var today = new Date();
                var upcoming = result.classes.filter(c => {
                    var classDate = new Date(c.class_date + ' ' + c.start_time);
                    return classDate > today && c.status !== 'Cancelled';
                });
                var obj = document.getElementById('upcomingClassesCount');
                var current = parseInt(obj.textContent) || 0;
                animateValue('upcomingClassesCount', current, upcoming.length, 1000);
            }
        });

    // Load modules count
    fetch(API_PATH + '?action=get_student_modules')
        .then(response => response.json())
        .then(result => {
            if (result.success && result.modules) {
                var obj = document.getElementById('modulesCount');
                var current = parseInt(obj.textContent) || 0;
                animateValue('modulesCount', current, result.modules.length, 1000);
            }
        });
}

// ========== SCHEDULE TAB FUNCTIONS ==========

/**
 * Load student schedule
 */
function loadStudentSchedule() {
    fetch(API_PATH + '?action=get_student_schedule')
        .then(response => response.json())
        .then(result => {
            var container = document.getElementById('studentSchedule');

            if (result.success && result.schedules && result.schedules.length > 0) {
                allSchedules = result.schedules;
                displaySchedule(allSchedules);
            } else {
                container.innerHTML = '<div class="alert alert-warning">Tiada jadual waktu. Sila hubungi guru anda.</div>';
            }
        })
        .catch(err => {
            console.error('Error loading schedule:', err);
            document.getElementById('studentSchedule').innerHTML = '<p class="text-center text-danger">Ralat memuatkan jadual</p>';
        });
}

/**
 * Display schedule in table format
 */
function displaySchedule(schedules) {
    var container = document.getElementById('studentSchedule');

    if (schedules.length === 0) {
        container.innerHTML = '<div class="alert alert-info text-center">Tiada jadual untuk penapis ini</div>';
        return;
    }

    // Separate Mentor vs Additional Teachers
    var mentorSchedules = schedules.filter(s => s.is_mentor == 1);
    var additionalSchedules = schedules.filter(s => s.is_mentor == 0);

    var html = '';

    // Helper function to generate table
    function generateTableHtml(data, title, badgeColor) {
        if (data.length === 0) return '';

        var grouped = {};
        data.forEach(s => {
            var key = s.day_of_week || s.schedule_date;
            if (!grouped[key]) grouped[key] = [];
            grouped[key].push(s);
        });

        var sectionHtml = '<div class="mb-4">';
        sectionHtml += '<h5 style="color: var(--primary-color); border-bottom: 2px solid #eee; padding-bottom: 10px; margin-bottom: 15px;">' + title + '</h5>';
        sectionHtml += '<div class="table-responsive"><table class="table table-hover align-middle"><thead><tr class="bg-light">';
        sectionHtml += '<th>Hari/Tarikh</th><th>Masa</th><th>Subjek</th><th>Guru</th><th>Penerangan</th>';
        sectionHtml += '</tr></thead><tbody>';

        Object.keys(grouped).sort().forEach(key => {
            grouped[key].forEach(s => {
                sectionHtml += '<tr>';
                sectionHtml += '<td style="font-weight: 500;">' + key + '</td>';
                sectionHtml += '<td><div class="d-flex align-items-center gap-1"><i class="fas fa-clock text-muted"></i> ' + s.start_time + (s.end_time ? ' - ' + s.end_time : '') + '</div></td>';
                sectionHtml += '<td><span class="badge ' + badgeColor + '">' + s.subject + '</span></td>';
                sectionHtml += '<td><div class="d-flex align-items-center gap-2"><div class="avatar-xs rounded-circle bg-light d-flex align-items-center justify-content-center" style="width:24px;height:24px;">👨‍🏫</div> Cikgu ' + (s.teacher_name || '-') + '</div></td>';
                sectionHtml += '<td class="text-muted small">' + (s.description || '-') + '</td>';
                sectionHtml += '</tr>';
            });
        });

        sectionHtml += '</tbody></table></div></div>';
        return sectionHtml;
    }

    if (mentorSchedules.length > 0) {
        html += generateTableHtml(mentorSchedules, '📚 Jadual Mentor Saya (Guru Kelas)', 'badge-primary');
    }

    if (additionalSchedules.length > 0) {
        html += generateTableHtml(additionalSchedules, '✨ Jadual Guru Tambahan', 'badge-info');
    }

    if (html === '') {
        html = '<div class="alert alert-warning text-center">Tiada jadual untuk dipaparkan.</div>';
    }

    container.innerHTML = html;
}

/**
 * Filter schedule by subject
 */
function filterSchedule() {
    var subjectFilter = document.getElementById('scheduleSubjectFilter').value;

    if (subjectFilter === 'all') {
        displaySchedule(allSchedules);
    } else {
        var filtered = allSchedules.filter(s => s.subject === subjectFilter);
        displaySchedule(filtered);
    }
}

// ========== MODULES TAB FUNCTIONS ==========

/**
 * Load student modules
 */
function loadStudentModules() {
    fetch(API_PATH + '?action=get_student_modules')
        .then(response => response.json())
        .then(result => {
            var container = document.getElementById('studentModules');

            if (result.success && result.modules && result.modules.length > 0) {
                allModules = result.modules;
                displayModules(allModules);
            } else {
                container.innerHTML = '<div class="alert alert-warning" style="grid-column: 1/-1;">Tiada modul. Sila hubungi guru anda.</div>';
            }
        })
        .catch(err => {
            console.error('Error loading modules:', err);
            document.getElementById('studentModules').innerHTML = '<p class="text-center text-danger">Ralat memuatkan modul</p>';
        });
}

/**
 * Display modules in grid
 */
function displayModules(modules) {
    var container = document.getElementById('studentModules');

    if (modules.length === 0) {
        container.innerHTML = '<p class="text-center text-muted" style="grid-column: 1/-1; padding: 40px 20px; background: #f8fafc; border-radius: var(--radius-lg);">Tiada modul untuk penapis ini</p>';
        return;
    }

    // Expanded motivational and subject-specific emojis
    var emojis = ['🚀', '📚', '🌟', '💡', '🎯', '🎨', '🔬', '🔢', '🌍', '📝', '�', '�', '📖', '✍️', '🎵', '🧮', '🎓'];
    var html = '';

    modules.forEach((module, i) => {
        var emoji = emojis[i % emojis.length];
        var links = JSON.parse(module.links || '[]');
        var difficulty = module.difficulty || 'medium'; // Assuming difficulty field exists, otherwise default to medium
        var progress = module.progress || 0; // Assuming progress field exists, otherwise default to 0

        // Dynamic difficulty color
        var diffColor = difficulty === 'easy' ? '#10b981' : difficulty === 'medium' ? '#f59e0b' : '#ef4444';

        // Progress percentage badge
        var progressBadge = progress > 0 ? `<span class="badge" style="background: linear-gradient(90deg, var(--primary-color) ${progress}%, #e2e8f0 ${progress}%); color: white; font-weight: 700;">${progress}% Selesai</span>` : '';

        html += '<div class="module-card animate__animated animate__fadeInUp" style="padding:0; overflow:hidden; border-radius: var(--radius-lg); box-shadow: var(--premium-shadow); border: none; transition: all 0.3s ease; transform: translateY(0);">';
        html += '<div onmouseover="this.parentElement.style.transform=\'translateY(-5px)\'" onmouseout="this.parentElement.style.transform=\'translateY(0)\'">';
        html += '<div style="background: linear-gradient(135deg, var(--primary-color), var(--primary-dark)); color:white; padding:20px; display:flex; align-items:center; gap:16px; position: relative; overflow: hidden;">';
        // Animated background circles
        html += '<div style="position: absolute; top: -50px; right: -50px; width: 150px; height: 150px; background: rgba(255,255,255,0.1); border-radius: 50%;"></div>';
        html += '<div style="position: absolute; bottom: -30px; left: -30px; width: 100px; height: 100px; background: rgba(255,255,255,0.15); border-radius: 50%;"></div>';
        html += '<div style="font-size:2.5rem; z-index: 1;">' + emoji + '</div>';
        html += '<div style="flex:1; z-index: 1;">';
        html += '<div style="font-weight:800; font-size:1.15rem; line-height:1.4; margin-bottom: 4px;">' + module.title + '</div>';
        html += '<div style="font-size:0.85rem; opacity:0.9; display: flex; align-items: center; gap: 12px;">';
        html += '<span><i class="fas fa-book-open"></i> ' + (module.subject || '-') + '</span>';
        html += '<span><i class="fas fa-chalkboard-teacher"></i> ' + (module.teacher_name || 'Guru') + '</span>';
        html += '</div>';
        html += '</div>';
        html += '</div>';
        html += '<div style="padding:20px; background: white;">';
        html += '<p style="margin:0 0 16px 0; color:#475569; font-size:0.95rem; line-height:1.6;">' + (module.description || 'Tiada penerangan') + '</p>';
        html += '<div style="margin-bottom: 16px; display: flex; align-items: center; gap: 8px; flex-wrap: wrap;">';
        html += '<span class="badge" style="background: ' + diffColor + '; color: white;"><i class="fas fa-signal"></i> ' + difficulty.charAt(0).toUpperCase() + difficulty.slice(1) + '</span>';
        html += '<span class="badge badge-primary"><i class="fas fa-paperclip"></i> ' + links.length + ' pautan</span>';
        html += '<span class="badge badge-secondary"><i class="far fa-calendar"></i> ' + (module.created_at ? formatDate(module.created_at) : '-') + '</span>';
        if (progressBadge) {
            html += progressBadge;
        }
        html += '</div>';

        // Display links directly in card for quick access
        if (links.length > 0) {
            html += '<div style="margin-bottom: 16px;">';
            html += '<p style="font-size: 0.85rem; color: #64748b; margin-bottom: 8px; font-weight: 600;"><i class="fas fa-link"></i> Pautan & Sumber:</p>';
            html += '<div style="display: flex; flex-wrap: wrap; gap: 6px;">';

            links.slice(0, 3).forEach(link => { // Show first 3 links
                if (!link || link.trim() === '') return;

                var href = link;
                var displayLink = link;
                var icon = '<i class="fas fa-file"></i>';

                // Improved path handling
                if (!link.match(/^https?:\/\//) && !link.match(/^www\./)) {
                    if (link.startsWith('assets/')) {
                        href = '../' + link;
                    } else if (!link.startsWith('../')) {
                        href = '../assets/uploads/modules/' + link;
                    }
                    displayLink = link.split('/').pop(); // Show filename only
                    icon = '<i class="fas fa-file-pdf"></i>';

                    // Detect file type for better icons
                    if (link.match(/\.(jpg|jpeg|png|gif|webp)$/i)) icon = '<i class="fas fa-file-image"></i>';
                    else if (link.match(/\.(doc|docx)$/i)) icon = '<i class="fas fa-file-word"></i>';
                    else if (link.match(/\.(xls|xlsx)$/i)) icon = '<i class="fas fa-file-excel"></i>';
                    else if (link.match(/\.(zip|rar|7z)$/i)) icon = '<i class="fas fa-file-archive"></i>';

                } else {
                    // Handle web URLs
                    if (link.match(/^www\./)) href = 'https://' + link;
                    displayLink = link.replace(/^https?:\/\/(www\.)?/, '');
                    if (displayLink.length > 20) {
                        displayLink = displayLink.substring(0, 17) + '...';
                    }
                    icon = '<i class="fas fa-globe"></i>';
                }

                html += '<a href="' + href + '" target="_blank" class="btn btn-outline-primary btn-sm d-flex align-items-center gap-1" style="font-size: 0.75rem; padding: 4px 8px; border-radius: 6px;">';
                html += icon;
                html += '<span style="max-width: 80px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">' + displayLink + '</span>';
                html += '</a>';
            });

            if (links.length > 3) {
                html += '<span class="badge badge-light" style="font-size: 0.75rem;">+' + (links.length - 3) + ' lagi</span>';
            }

            html += '</div>';
            html += '</div>';
        }
        html += '<div style="display: flex; gap: 10px;">';
        html += '<button class="btn btn-primary btn-sm flex-1" style="font-weight: 700; padding: 10px 16px; border-radius: var(--radius-lg); box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3); transition: all 0.3s ease;" onclick="viewModuleDetail(' + module.id + ')">';
        html += '<i class="fas fa-play-circle"></i> Mula Belajar';
        html += '</button>';
        html += '<button class="btn btn-outline-primary btn-sm" style="border-radius: var(--radius-lg); padding: 10px 16px;" onclick="viewModuleDetail(' + module.id + ')">';
        html += '<i class="fas fa-info-circle"></i>';
        html += '</button>';
        html += '</div>';
        html += '</div>';
        html += '</div>';
        html += '</div>';
    });

    container.innerHTML = html;
}

/**
 * View module details
 */
function viewModuleDetail(moduleId) {
    var module = allModules.find(m => m.id == moduleId);

    if (!module) {
        showNotification('Modul tidak dijumpai', 'error');
        return;
    }

    document.getElementById('moduleDetailTitle').textContent = module.title;
    document.getElementById('moduleDetailSubject').textContent = module.subject;
    document.getElementById('moduleDetailTeacher').textContent = '👨‍🏫 Cikgu ' + (module.teacher_name || 'Guru');
    document.getElementById('moduleDetailDescription').textContent = module.description || 'Tiada penerangan';
    document.getElementById('moduleDetailContent').textContent = module.content || 'Tiada kandungan';

    var links = JSON.parse(module.links || '[]');
    var linksHtml = '';
    if (links.length > 0) {
        links.forEach(link => {
            if (!link || link.trim() === '') return; // Skip empty links

            var href = link;
            var displayLink = link;
            var icon = '<i class="fas fa-file-download"></i>';

            // Improved path handling
            if (!link.match(/^https?:\/\//) && !link.match(/^www\./)) {
                if (link.startsWith('assets/')) {
                    href = '../' + link;
                } else if (!link.startsWith('../')) {
                    href = '../assets/uploads/modules/' + link;
                }
                displayLink = link.split('/').pop(); // Show filename only
                icon = '<i class="fas fa-file"></i>';
            } else {
                // Handle web URLs
                if (link.match(/^www\./)) href = 'https://' + link;
                displayLink = link.replace(/^https?:\/\/(www\.)?/, '');
                if (displayLink.length > 25) {
                    displayLink = displayLink.substring(0, 22) + '...';
                }
                icon = '<i class="fas fa-globe"></i>';
            }

            linksHtml += '<a href="' + href + '" target="_blank" class="btn btn-outline-primary btn-sm d-flex align-items-center gap-2" style="margin: 3px;">';
            linksHtml += icon;
            linksHtml += '<span style="max-width: 150px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">' + displayLink + '</span>';
            linksHtml += '</a>';
        });
    } else {
        linksHtml = '<p class="text-muted"><i class="fas fa-link-slash"></i> Tiada pautan</p>';
    }
    document.getElementById('moduleDetailLinks').innerHTML = linksHtml;

    openModal('moduleDetailModal');
}

/**
 * Filter modules
 */
function filterModules() {
    var searchTerm = document.getElementById('moduleSearch').value.toLowerCase();
    var subjectFilter = document.getElementById('moduleSubjectFilter').value;

    var filtered = allModules.filter(m => {
        var matchesSearch = m.title.toLowerCase().includes(searchTerm) ||
            (m.description || '').toLowerCase().includes(searchTerm);
        var matchesSubject = subjectFilter === 'all' || m.subject === subjectFilter;
        return matchesSearch && matchesSubject;
    });

    displayModules(filtered);
}

// ========== CLASSES TAB FUNCTIONS ==========

/**
 * Load student classes
 */
function loadStudentClasses() {
    fetch(API_PATH + '?action=get_student_classes')
        .then(response => response.json())
        .then(result => {
            if (result.success && result.classes) {
                allClasses = result.classes;

                // Populate subject filter
                var subjectFilter = document.getElementById('classSubjectFilter');
                if (subjectFilter) {
                    var subjects = [...new Set(allClasses.map(c => c.subject))];
                    var currentVal = subjectFilter.value;
                    var html = '<option value="all">Semua Subjek</option>';
                    subjects.forEach(s => {
                        html += `<option value="${s}" ${s === currentVal ? 'selected' : ''}>${s}</option>`;
                    });
                    subjectFilter.innerHTML = html;
                }

                filterClasses();
            } else {
                document.getElementById('upcomingClassesList').innerHTML = '<p class="text-center text-muted">Tiada kelas</p>';
                document.getElementById('pastClassesList').innerHTML = '<p class="text-center text-muted">Tiada kelas</p>';
            }
        })
        .catch(err => {
            console.error('Error loading classes:', err);
            document.getElementById('upcomingClassesList').innerHTML = '<p class="text-center text-danger">Ralat memuatkan kelas</p>';
            document.getElementById('pastClassesList').innerHTML = '<p class="text-center text-danger">Ralat memuatkan kelas</p>';
        });
}

/**
 * Filter and display classes
 */
function filterClasses() {
    var statusFilter = document.getElementById('classStatusFilter').value;
    var subjectFilter = document.getElementById('classSubjectFilter') ? document.getElementById('classSubjectFilter').value : 'all';

    var now = new Date();

    // Show/Hide sections based on filter
    var sectionUpcoming = document.getElementById('sectionUpcoming');
    var sectionPast = document.getElementById('sectionPast');

    if (sectionUpcoming && sectionPast) {
        if (statusFilter === 'all') {
            sectionUpcoming.style.display = 'block';
            sectionPast.style.display = 'block';
        } else if (statusFilter === 'upcoming') {
            sectionUpcoming.style.display = 'block';
            sectionPast.style.display = 'none';
        } else if (statusFilter === 'past') {
            sectionUpcoming.style.display = 'none';
            sectionPast.style.display = 'block';
        }
    }

    // Filter classes
    var filtered = allClasses.filter(c => {
        var classDateTime = new Date(c.class_date + ' ' + c.start_time);
        var isUpcoming = classDateTime > now;
        var isPast = classDateTime <= now;

        var matchesStatus = statusFilter === 'all' ||
            (statusFilter === 'upcoming' && isUpcoming) ||
            (statusFilter === 'past' && isPast);
        var matchesSubject = subjectFilter === 'all' || c.subject === subjectFilter;

        return matchesStatus && matchesSubject && c.status !== 'Cancelled';
    });

    // Separate upcoming and past
    var upcoming = filtered.filter(c => new Date(c.class_date + ' ' + c.start_time) > now);
    var past = filtered.filter(c => new Date(c.class_date + ' ' + c.start_time) <= now);

    displayUpcomingClasses(upcoming);
    displayPastClasses(past);
}

/**
 * Display upcoming classes
 */
function displayUpcomingClasses(classes) {
    var container = document.getElementById('upcomingClassesList');

    if (classes.length === 0) {
        container.innerHTML = '<p class="text-center text-muted" style="padding: 40px 20px; background: #f8fafc; border-radius: var(--radius-lg);">Tiada kelas akan datang</p>';
        return;
    }

    var classEmojis = ['🎥', '🌟', '📚', '💡', '🔬', '🎨', '🎵', '🧮', '🌍', '💻'];
    var html = '';

    classes.forEach((c, i) => {
        var classDateTime = new Date(c.class_date + ' ' + c.start_time);
        var timeUntil = getTimeUntil(classDateTime);
        var emoji = classEmojis[i % classEmojis.length];
        var classType = c.type || 'online';
        var typeBadge = classType === 'online' ? '<span class="badge bg-success bg-opacity-10 text-success" style="font-size: 0.75rem;"><i class="fas fa-video"></i> Dalam Talian</span>' : '<span class="badge bg-primary bg-opacity-10 text-primary" style="font-size: 0.75rem;"><i class="fas fa-building"></i> Bersemuka</span>';

        html += '<div class="class-card animate__animated animate__fadeInUp" style="padding:0; overflow:hidden; border-radius: var(--radius-lg); box-shadow: var(--premium-shadow); border: none; transition: all 0.3s ease; transform: translateY(0);">';
        html += '<div onmouseover="this.parentElement.style.transform=\'translateY(-5px)\'" onmouseout="this.parentElement.style.transform=\'translateY(0)\'">';
        html += '<div style="background: linear-gradient(135deg, var(--primary-color), var(--primary-dark)); color:white; padding:20px; display:flex; align-items:center; justify-content:space-between; gap:16px; position: relative; overflow: hidden;">';
        // Animated background circles
        html += '<div style="position: absolute; top: -40px; right: -40px; width: 120px; height: 120px; background: rgba(255,255,255,0.1); border-radius: 50%;"></div>';
        html += '<div style="font-size:2.5rem; z-index: 1;">' + emoji + '</div>';
        html += '<div style="flex:1; z-index: 1;">';
        html += '<div style="display: flex; align-items: center; gap: 8px; margin-bottom: 4px;">';
        html += '<div style="font-weight:800; font-size:1.15rem;">' + c.title + '</div>';
        html += typeBadge;
        html += '</div>';
        html += '<div style="font-size:0.85rem; opacity:0.9; display: flex; align-items: center; gap: 12px;">';
        html += '<span><i class="fas fa-book-open"></i> ' + (c.subject || '-') + '</span>';
        html += '<span><i class="fas fa-chalkboard-teacher"></i> Cikgu ' + (c.teacher_name || 'Guru') + '</span>';
        html += '</div>';
        html += '</div>';
        html += '<div class="countdown-timer" id="countdown_' + c.id + '" style="background: rgba(255,255,255,0.25); padding:8px 14px; border-radius: 20px; font-weight: 700; font-size: 0.9rem; min-width: 120px; text-align: center; z-index: 1;">' + timeUntil + '</div>';
        html += '</div>';
        html += '<div style="padding:20px; background: white;">';
        html += '<div style="display:flex; gap:16px; flex-wrap:wrap; color:#475569; font-size:0.95rem; margin-bottom: 16px;">';
        html += '<div style="display: flex; align-items: center; gap: 6px;"><i class="fas fa-calendar-alt text-primary"></i> ' + formatDate(c.class_date) + '</div>';
        html += '<div style="display: flex; align-items: center; gap: 6px;"><i class="fas fa-clock text-primary"></i> ' + c.start_time + (c.end_time ? ' - ' + c.end_time : '') + '</div>';
        if (c.location) {
            html += '<div style="display: flex; align-items: center; gap: 6px;"><i class="fas fa-map-marker-alt text-primary"></i> ' + c.location + '</div>';
        }
        html += '</div>';

        html += '<div style="display: flex; gap: 10px; flex-wrap: wrap;">';
        if (c.join_link) {
            html += '<a href="' + c.join_link + '" target="_blank" class="btn btn-success btn-sm flex-1" style="font-weight: 700; padding: 10px 16px; border-radius: var(--radius-lg); box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3); transition: all 0.3s ease;">';
            html += '<i class="fas fa-video"></i> Join Kelas';
            html += '</a>';
        }
        html += '</div>';
        html += '</div>';
        html += '</div>';
        html += '</div>';
    });

    container.innerHTML = html;

    // Start countdown timers
    classes.forEach(c => {
        startCountdown(c.id, new Date(c.class_date + ' ' + c.start_time));
    });
}

/**
 * Display past classes
 */
function displayPastClasses(classes) {
    var container = document.getElementById('pastClassesList');

    if (classes.length === 0) {
        container.innerHTML = '<p class="text-center text-muted" style="padding: 40px 20px; background: #f8fafc; border-radius: var(--radius-lg);">Tiada kelas lepas</p>';
        return;
    }

    var classEmojis = ['🏫', '✅', '🎓', '📝', '🎬', '🎨', '🎵', '🧪', '🌍', '💻'];
    var html = '';

    classes.forEach((c, i) => {
        var emoji = classEmojis[i % classEmojis.length];
        var classType = c.type || 'online';
        var typeBadge = classType === 'online' ? '<span class="badge bg-success bg-opacity-10 text-success" style="font-size: 0.75rem;"><i class="fas fa-video"></i> Dalam Talian</span>' : '<span class="badge bg-primary bg-opacity-10 text-primary" style="font-size: 0.75rem;"><i class="fas fa-building"></i> Bersemuka</span>';
        var statusBadge = c.status === 'Completed' ? '<span class="badge bg-primary bg-opacity-10 text-primary" style="font-size: 0.75rem;"><i class="fas fa-check-circle"></i> Selesai</span>' : '<span class="badge bg-warning bg-opacity-10 text-warning" style="font-size: 0.75rem;"><i class="fas fa-exclamation-circle"></i> ' + c.status + '</span>';

        html += '<div class="class-card animate__animated animate__fadeIn" style="padding:0; overflow:hidden; border-radius: var(--radius-lg); box-shadow: var(--premium-shadow); border: none; transition: all 0.3s ease; transform: translateY(0); opacity: 0.98;">';
        html += '<div onmouseover="this.parentElement.style.transform=\'translateY(-5px)\'" onmouseout="this.parentElement.style.transform=\'translateY(0)\'">';
        html += '<div style="background: linear-gradient(135deg, var(--primary-light), var(--primary-color)); color:white; padding:20px; display:flex; align-items:center; gap:16px; position: relative; overflow: hidden;">';
        // Animated background circles
        html += '<div style="position: absolute; top: -40px; right: -40px; width: 120px; height: 120px; background: rgba(255,255,255,0.1); border-radius: 50%;"></div>';
        html += '<div style="font-size:2.5rem; z-index: 1;">' + emoji + '</div>';
        html += '<div style="flex:1; z-index: 1;">';
        html += '<div style="display: flex; align-items: center; gap: 8px; margin-bottom: 4px;">';
        html += '<div style="font-weight:800; font-size:1.15rem;">' + c.title + '</div>';
        html += typeBadge;
        html += statusBadge;
        html += '</div>';
        html += '<div style="font-size:0.85rem; opacity:0.9; display: flex; align-items: center; gap: 12px;">';
        html += '<span><i class="fas fa-book-open"></i> ' + (c.subject || '-') + '</span>';
        html += '<span><i class="fas fa-chalkboard-teacher"></i> Cikgu ' + (c.teacher_name || 'Guru') + '</span>';
        html += '</div>';
        html += '</div>';
        html += '</div>';
        html += '<div style="padding:20px; background: white;">';
        html += '<div style="display:flex; gap:16px; flex-wrap:wrap; color:#475569; font-size:0.95rem; margin-bottom: 16px;">';
        html += '<div style="display: flex; align-items: center; gap: 6px;"><i class="fas fa-calendar-alt text-primary"></i> ' + formatDate(c.class_date) + '</div>';
        html += '<div style="display: flex; align-items: center; gap: 6px;"><i class="fas fa-clock text-primary"></i> ' + c.start_time + (c.end_time ? ' - ' + c.end_time : '') + '</div>';
        if (c.location) {
            html += '<div style="display: flex; align-items: center; gap: 6px;"><i class="fas fa-map-marker-alt text-primary"></i> ' + c.location + '</div>';
        }
        html += '</div>';

        html += '<div style="display: flex; gap: 10px; flex-wrap: wrap;">';
        if (c.recording_link) {
            html += '<a href="' + c.recording_link + '" target="_blank" class="btn btn-outline-primary btn-sm flex-1" style="font-weight: 700; padding: 10px 16px; border-radius: var(--radius-lg); transition: all 0.3s ease;">';
            html += '<i class="fas fa-play-circle"></i> Tonton Rakaman';
            html += '</a>';
        }
        if (c.materials_link) {
            html += '<a href="' + c.materials_link + '" target="_blank" class="btn btn-outline-info btn-sm flex-1" style="font-weight: 700; padding: 10px 16px; border-radius: var(--radius-lg); transition: all 0.3s ease;">';
            html += '<i class="fas fa-download"></i> Muat Turun Bahan';
            html += '</a>';
        }
        html += '</div>';
        html += '</div>';
        html += '</div>';
        html += '</div>';
    });

    container.innerHTML = html;
}

/**
 * Start countdown timer for a class
 */
function startCountdown(classId, targetDate) {
    var countdownEl = document.getElementById('countdown_' + classId);
    if (!countdownEl) return;

    var interval = setInterval(function () {
        var now = new Date().getTime();
        var distance = targetDate - now;

        if (distance < 0) {
            clearInterval(interval);
            countdownEl.textContent = 'Bermula!';
            return;
        }

        var hours = Math.floor(distance / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));

        if (hours > 24) {
            var days = Math.floor(hours / 24);
            countdownEl.textContent = days + ' hari lagi';
        } else if (hours > 0) {
            countdownEl.textContent = hours + ' jam ' + minutes + ' minit';
        } else {
            countdownEl.textContent = minutes + ' minit lagi';
        }
    }, 1000);
}

/**
 * Get time until class
 */
function getTimeUntil(targetDate) {
    var now = new Date();
    var distance = targetDate - now;

    if (distance < 0) return 'Bermula!';

    var hours = Math.floor(distance / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));

    if (hours > 24) {
        var days = Math.floor(hours / 24);
        return days + ' hari lagi';
    } else if (hours > 0) {
        return hours + ' jam ' + minutes + ' minit';
    } else {
        return minutes + ' minit lagi';
    }
}

// ========== FORUM TAB FUNCTIONS ==========

/**
 * Load student forums
 */
function loadStudentForum() {
    fetch(API_PATH + '?action=get_student_forums')
        .then(response => response.json())
        .then(result => {
            var container = document.getElementById('studentForum');

            if (result.success && result.forums && result.forums.length > 0) {
                allForums = result.forums;
                displayForums(allForums);
            } else {
                container.innerHTML = '<div class="alert alert-warning">Tiada forum. Sila hubungi guru anda.</div>';
            }
        })
        .catch(err => {
            console.error('Error loading forum:', err);
            document.getElementById('studentForum').innerHTML = '<p class="text-center text-danger">Ralat memuatkan forum</p>';
        });
}

/**
 * Display forums
 */
function displayForums(forums) {
    var container = document.getElementById('studentForum');

    if (forums.length === 0) {
        container.innerHTML = '<p class="text-center text-muted">Tiada forum untuk penapis ini</p>';
        return;
    }

    var html = '';
    forums.forEach(f => {
        var isPinned = f.is_pinned === 'Yes';

        html += '<div class="forum-card' + (isPinned ? ' animate__animated animate__pulse' : '') + '">';
        html += '<div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 10px;">';
        html += '<div style="flex: 1;">';
        html += '<h5 style="margin: 0; color: var(--primary-color);">';
        if (isPinned) html += '📌 ';
        html += f.title + '</h5>';
        html += '</div>';
        html += '<span class="badge badge-primary">' + f.subject + '</span>';
        html += '</div>';
        html += '<p style="color: #666; margin: 10px 0;">' + truncateText(f.content, 150) + '</p>';
        html += '<div style="display: flex; justify-content: space-between; align-items: center; margin-top: 15px;">';
        html += '<small class="text-muted">👨‍🏫 Cikgu ' + (f.teacher_name || 'Guru') + '</small>';
        html += '<button class="btn btn-sm btn-primary" onclick="viewForumDetail(' + f.id + ')">';
        html += '<i class="fas fa-comments"></i> Lihat & Balas';
        html += '</button>';
        html += '</div>';
        html += '</div>';
    });

    container.innerHTML = html;
}

/**
 * View forum details and replies
 */
function viewForumDetail(forumId) {
    var forum = allForums.find(f => f.id == forumId);

    if (!forum) {
        showNotification('Forum tidak dijumpai', 'error');
        return;
    }

    document.getElementById('forumDetailTitle').textContent = forum.title;
    document.getElementById('forumDetailSubject').textContent = forum.subject;
    document.getElementById('forumDetailTeacher').textContent = '👨‍🏫 Cikgu ' + (forum.teacher_name || 'Guru');
    document.getElementById('forumDetailDate').textContent = formatDateTime(forum.created_at);
    document.getElementById('forumDetailContent').textContent = forum.content;

    var attachmentHtml = '';
    if (forum.attachment) {
        var fileType = (forum.attachment_type || '').toLowerCase();
        if (['jpg', 'jpeg', 'png'].includes(fileType)) {
            attachmentHtml = '<div style="margin-top:10px;"><a href="../' + forum.attachment + '" target="_blank"><img src="../' + forum.attachment + '" style="max-width:100%; border-radius:10px; border:1px solid #eee;"></a></div>';
        } else if (fileType === 'pdf') {
            attachmentHtml = '<div style="margin-top:10px;"><a href="../' + forum.attachment + '" target="_blank" class="btn btn-sm btn-outline-danger"><i class="fas fa-file-pdf"></i> Lihat PDF</a></div>';
        }
    }
    var attachContainer = document.getElementById('forumDetailAttachment');
    if (attachContainer) attachContainer.innerHTML = attachmentHtml;

    if (forum.link) {
        document.getElementById('forumDetailLink').innerHTML = '<a href="' + forum.link + '" target="_blank" class="btn btn-sm btn-outline-primary"><i class="fas fa-link"></i> Pautan Rujukan</a>';
    } else {
        document.getElementById('forumDetailLink').innerHTML = '';
    }

    document.getElementById('replyForumId').value = forumId;

    // Load replies
    loadForumReplies(forumId);

    openModal('forumDetailModal');
}

/**
 * Load forum replies
 */
function loadForumReplies(forumId) {
    fetch(API_PATH + '?action=get_forum_replies&forum_id=' + forumId)
        .then(response => response.json())
        .then(result => {
            var container = document.getElementById('forumRepliesList');

            if (result.success && result.replies && result.replies.length > 0) {
                document.getElementById('forumReplyCount').textContent = result.replies.length;

                var html = '';
                result.replies.forEach(r => {
                    var isTeacher = r.user_type === 'teacher';
                    html += '<div style="background: ' + (isTeacher ? '#e8f4ff' : '#f8f9fa') + '; padding: 15px; border-radius: 10px; margin-bottom: 10px; border-left: 3px solid ' + (isTeacher ? 'var(--primary-color)' : '#ddd') + ';">';
                    html += '<div style="display: flex; justify-content: space-between; margin-bottom: 8px;">';
                    html += '<strong>' + (r.user_emoji || '👤') + ' ' + (r.user_name || 'Pengguna') + '</strong>';
                    html += '<small class="text-muted">' + formatDateTime(r.created_at) + '</small>';
                    html += '</div>';
                    html += '<p style="margin: 0; white-space: pre-wrap;">' + r.content + '</p>';

                    if (r.attachment) {
                        html += '<div style="margin-top: 10px;">';
                        var fileType = (r.attachment_type || '').toLowerCase();
                        if (['jpg', 'jpeg', 'png'].includes(fileType)) {
                            html += '<a href="../' + r.attachment + '" target="_blank">';
                            html += '<img src="../' + r.attachment + '" style="max-width: 100%; max-height: 200px; border-radius: 8px; border: 1px solid #ddd; object-fit: cover;">';
                            html += '</a>';
                        } else if (fileType === 'pdf') {
                            html += '<div style="background: #fff; padding: 10px; border-radius: 8px; border: 1px solid #eee; display: inline-flex; align-items: center; gap: 10px;">';
                            html += '<i class="fas fa-file-pdf text-danger" style="font-size: 1.5rem;"></i>';
                            html += '<div>';
                            html += '<div style="font-size: 0.85rem; font-weight: 600;">Dokumen PDF</div>';
                            html += '<a href="../' + r.attachment + '" target="_blank" class="text-primary" style="font-size: 0.8rem; text-decoration: none;">Muat Turun &searrow;</a>';
                            html += '</div>';
                            html += '</div>';
                        }
                        html += '</div>';
                    }

                    html += '</div>';
                });
                container.innerHTML = html;
            } else {
                document.getElementById('forumReplyCount').textContent = '0';
                container.innerHTML = '<p class="text-center text-muted">Tiada balasan. Jadilah yang pertama!</p>';
            }
        });
}

/**
 * Submit forum reply
 */
function submitForumReply(event) {
    event.preventDefault();

    var forumId = document.getElementById('replyForumId').value;
    var content = document.getElementById('replyContent').value;

    if (!content.trim()) {
        showNotification('Sila tulis balasan anda', 'warning');
        return;
    }

    var formData = new FormData();
    formData.append('action', 'add_forum_reply');
    formData.append('forum_id', forumId);
    formData.append('content', content);

    var fileInput = document.getElementById('studentReplyAttachment');
    if (fileInput && fileInput.files.length > 0) {
        formData.append('attachment', fileInput.files[0]);
    }

    fetch(API_PATH, { method: 'POST', body: formData })
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                showNotification('Balasan berjaya dihantar!', 'success');
                document.getElementById('replyContent').value = '';
                clearStudentFile(); // Clear file input
                loadForumReplies(forumId);
            } else {
                showNotification(result.message, 'error');
            }
        })
        .catch(err => {
            showNotification('Ralat sambungan', 'error');
        });
}

function previewStudentFile() {
    var input = document.getElementById('studentReplyAttachment');
    if (input.files.length > 0) {
        document.getElementById('studentFileName').innerText = input.files[0].name;
        document.getElementById('studentFilePreview').style.display = 'block';
    }
}

function clearStudentFile() {
    var input = document.getElementById('studentReplyAttachment');
    if (input) input.value = '';
    var preview = document.getElementById('studentFilePreview');
    if (preview) preview.style.display = 'none';
}

/**
 * Filter forums
 */
function filterForum() {
    var searchTerm = document.getElementById('forumSearch').value.toLowerCase();
    var subjectFilter = document.getElementById('forumSubjectFilter').value;

    var filtered = allForums.filter(f => {
        var matchesSearch = f.title.toLowerCase().includes(searchTerm) ||
            f.content.toLowerCase().includes(searchTerm);
        var matchesSubject = subjectFilter === 'all' || f.subject === subjectFilter;
        return matchesSearch && matchesSubject;
    });

    displayForums(filtered);
}

// ========== ANNOUNCEMENTS TAB FUNCTIONS ==========

/**
 * Load student announcements
 */
function loadStudentAnnouncements() {
    fetch(API_PATH + '?action=get_announcements')
        .then(response => response.json())
        .then(result => {
            var container = document.getElementById('studentAnnouncements');

            if (result.success && result.announcements && result.announcements.length > 0) {
                allAnnouncements = result.announcements;
                displayAnnouncements(allAnnouncements);
            } else {
                container.innerHTML = '<div class="alert alert-warning">Tiada pengumuman.</div>';
            }
        })
        .catch(err => {
            console.error('Error loading announcements:', err);
            document.getElementById('studentAnnouncements').innerHTML = '<p class="text-center text-danger">Ralat memuatkan pengumuman</p>';
        });
}

/**
 * Display announcements
 */
function displayAnnouncements(announcements) {
    var container = document.getElementById('studentAnnouncements');

    if (announcements.length === 0) {
        container.innerHTML = '<p class="text-center text-muted">Tiada pengumuman untuk penapis ini</p>';
        return;
    }

    var html = '';
    announcements.forEach(a => {
        var priorityClass = a.priority === 'Urgent' ? 'priority-urgent' :
            a.priority === 'Penting' ? 'priority-important' : 'priority-normal';

        html += '<div class="announcement-card">';
        html += '<div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 10px;">';
        html += '<div style="flex: 1;">';
        html += '<h5 style="margin: 0; color: var(--primary-color);">' + a.title + '</h5>';
        html += '</div>';
        html += '<span class="' + priorityClass + '">' + a.priority + '</span>';
        html += '</div>';
        html += '<p style="color: #666; margin: 10px 0;">' + truncateText(a.content, 200) + '</p>';
        html += '<div style="display: flex; justify-content: space-between; align-items: center; margin-top: 15px;">';
        html += '<div>';
        html += '<small class="text-muted">👨‍🏫 Cikgu ' + (a.teacher_name || 'Guru') + '</small><br>';
        html += '<small class="text-muted">📅 ' + formatDate(a.created_at) + '</small>';
        html += '</div>';
        html += '<button class="btn btn-sm btn-primary" onclick="viewAnnouncementDetail(' + a.id + ')">';
        html += '<i class="fas fa-eye"></i> Lihat Penuh';
        html += '</button>';
        html += '</div>';
        html += '</div>';
    });

    container.innerHTML = html;
}

/**
 * View announcement details
 */
function viewAnnouncementDetail(announcementId) {
    var announcement = allAnnouncements.find(a => a.id == announcementId);

    if (!announcement) {
        showNotification('Pengumuman tidak dijumpai', 'error');
        return;
    }

    document.getElementById('announcementDetailTitle').textContent = announcement.title;
    document.getElementById('announcementDetailCategory').textContent = announcement.category || 'Umum';

    var priorityClass = announcement.priority === 'Urgent' ? 'priority-urgent' :
        announcement.priority === 'Penting' ? 'priority-important' : 'priority-normal';
    document.getElementById('announcementDetailPriority').innerHTML = '<span class="' + priorityClass + '">' + announcement.priority + '</span>';

    document.getElementById('announcementDetailTeacher').textContent = 'Cikgu ' + (announcement.teacher_name || 'Guru');
    document.getElementById('announcementDetailDate').textContent = formatDateTime(announcement.created_at);
    document.getElementById('announcementDetailContent').textContent = announcement.content;

    if (announcement.attachment_link) {
        document.getElementById('announcementDetailAttachment').innerHTML =
            '<a href="' + announcement.attachment_link + '" target="_blank" class="btn btn-outline-primary btn-sm">' +
            '<i class="fas fa-paperclip"></i> Lampiran' +
            '</a>';
    } else {
        document.getElementById('announcementDetailAttachment').innerHTML = '';
    }

    openModal('announcementDetailModal');
}

/**
 * Filter announcements
 */
function filterAnnouncements() {
    var priorityFilter = document.getElementById('announcementPriorityFilter').value;
    var subjectFilter = document.getElementById('announcementSubjectFilter') ?
        document.getElementById('announcementSubjectFilter').value : 'all';

    var filtered = allAnnouncements.filter(a => {
        var matchesPriority = priorityFilter === 'all' || a.priority === priorityFilter;
        var matchesSubject = subjectFilter === 'all' || a.subject === subjectFilter;
        return matchesPriority && matchesSubject;
    });

    displayAnnouncements(filtered);
}

// ========== PROFILE TAB FUNCTIONS ==========

/**
 * Update student profile
 */
function updateProfile(event) {
    event.preventDefault();

    var formData = new FormData(document.getElementById('profileForm'));
    formData.append('action', 'update_student_profile');

    var btn = event.target.querySelector('button[type="submit"]');
    var originalText = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Menyimpan...';

    fetch(API_PATH, { method: 'POST', body: formData })
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                showNotification('Profil berjaya dikemaskini!', 'success');
                setTimeout(() => location.reload(), 1500);
            } else {
                showNotification(result.message, 'error');
                btn.disabled = false;
                btn.innerHTML = originalText;
            }
        })
        .catch(err => {
            showNotification('Ralat sambungan', 'error');
            btn.disabled = false;
            btn.innerHTML = originalText;
        });
}

/**
 * Update password
 */
function updatePassword(event) {
    event.preventDefault();

    var currentPassword = document.getElementById('currentPassword').value;
    var newPassword = document.getElementById('newPassword').value;
    var confirmPassword = document.getElementById('confirmPassword').value;

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

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

    var formData = new FormData();
    formData.append('action', 'change_student_password');
    formData.append('current_password', currentPassword);
    formData.append('new_password', newPassword);
    formData.append('confirm_password', confirmPassword);

    var btn = event.target.querySelector('button[type="submit"]');
    var originalText = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Memproses...';

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

/**
 * Load enrollment status
 */
function loadEnrollmentStatus() {
    fetch(API_PATH + '?action=get_student_enrollments')
        .then(response => response.json())
        .then(result => {
            var container = document.getElementById('enrollmentStatus');

            if (result.success && result.enrollments && result.enrollments.length > 0) {
                var html = '<div class="table-container"><table class="table"><thead><tr>';
                html += '<th>Subjek</th><th>Guru</th><th>Status</th><th>Tarikh</th>';
                html += '</tr></thead><tbody>';

                result.enrollments.forEach(e => {
                    var statusBadge = e.status === 'Approved' ? 'badge-success' :
                        e.status === 'Pending' ? 'badge-warning' : 'badge-danger';
                    var statusText = e.status === 'Approved' ? '✅ Diluluskan' :
                        e.status === 'Pending' ? '⏳ Menunggu' : '❌ Ditolak';

                    html += '<tr>';
                    html += '<td><span class="badge badge-primary">' + e.subject + '</span></td>';
                    html += '<td>👨‍🏫 Cikgu ' + (e.teacher_name || '-') + '<br><small>' + (e.teacher_phone || '') + '</small></td>';
                    html += '<td><span class="badge ' + statusBadge + '">' + statusText + '</span></td>';
                    html += '<td>' + formatDate(e.enrolled_at) + '</td>';
                    html += '</tr>';
                });

                html += '</tbody></table></div>';
                container.innerHTML = html;
            } else {
                container.innerHTML = '<p class="text-center text-muted">Tiada maklumat pendaftaran</p>';
            }
        })
        .catch(err => {
            console.error('Error loading enrollment status:', err);
        });
}

// ========== HELPER FUNCTIONS ==========

/**
 * Show notification using SweetAlert2
 */
function showNotification(message, type) {
    const themeColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#667eea';

    const iconMap = {
        'success': '✅',
        'error': '❌',
        'warning': '⚠️',
        'info': 'ℹ️'
    };

    Swal.fire({
        title: iconMap[type] || 'ℹ️',
        text: message,
        icon: type,
        confirmButtonColor: themeColor,
        confirmButtonText: 'OK',
        timer: type === 'success' ? 2000 : undefined,
        timerProgressBar: type === 'success'
    });
}

/**
 * Open modal
 */
function openModal(modalId) {
    var modal = document.getElementById(modalId);
    if (modal) {
        modal.classList.add('active');
        document.body.style.overflow = 'hidden';
    }
}

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

/**
 * Truncate text
 */
function truncateText(text, length) {
    if (!text) return '';
    if (text.length <= length) return text;
    return text.substring(0, length) + '...';
}

/**
 * Format date
 */
function formatDate(dateString) {
    if (!dateString || dateString === '0000-00-00') return '-';

    var date = new Date(dateString);
    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();
}

/**
 * Format date time
 */
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()] + ' ' +
        String(date.getHours()).padStart(2, '0') + ':' + String(date.getMinutes()).padStart(2, '0');
}

// ========== INITIALIZATION ==========

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

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