/**
 * 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();
}

/**
 * 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;">👨‍🏫 Guru 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;">' + 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;"></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> ' + (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;">Tiada modul untuk penapis ini</p>';
        return;
    }

    var emojis = ['🚀','📚','📖','✏','🔬','🔢','🌍','💡','🎯','🎵','🎨','💻','📝'];
    var html = '';

    modules.forEach((module, i) => {
        var emoji = emojis[i % emojis.length];
        var links = JSON.parse(module.links || '[]');

        html += '<div class="module-card animate__animated animate__fadeInUp" style="padding:0; overflow:hidden; border-left: 5px solid var(--primary-color);">';
        html += '<div style="background: linear-gradient(135deg, var(--primary-color), var(--primary-dark)); color:white; padding:16px; display:flex; align-items:center; gap:14px;">';
        html += '<div style="font-size:2.2rem;">' + emoji + '</div>';
        html += '<div style="flex:1;">';
        html += '<div style="font-weight:800; font-size:1.05rem; line-height:1.4;">' + module.title + '</div>';
        html += '<div style="font-size:0.85rem; opacity:0.9;">' + (module.subject || '-') + ' • 👨‍🏫 ' + (module.teacher_name || 'Guru') + '</div>';
        html += '</div>';
        html += '</div>';
        html += '<div style="padding:16px;">';
        html += '<p style="margin:0; color:#475569; font-size:0.95rem;">' + (module.description || 'Tiada penerangan') + '</p>';
        html += '<div style="margin-top:12px; display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:8px;">';
        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>';
        html += '</div>';
        html += '<button class="btn btn-primary btn-sm" style="width:100%; margin-top:12px;" onclick="viewModuleDetail(' + module.id + ')">Mula Belajar</button>';
        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 = '👨‍🏫 ' + (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 => {
            var href = link;
            if (!link.match(/^https?:\/\//) && !link.startsWith('../')) {
                href = '../' + link;
            }
            var displayLink = link.split('/').pop();
            if (link.match(/^https?:\/\//)) displayLink = truncateText(link, 40);

            linksHtml += '<a href="' + href + '" target="_blank" class="btn btn-outline-primary btn-sm" style="margin: 3px;">';
            linksHtml += '<i class="fas fa-file-download"></i> ' + displayLink;
            linksHtml += '</a>';
        });
    } else {
        linksHtml = '<p class="text-muted">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();

    // 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">Tiada kelas akan datang</p>';
        return;
    }

    var html = '';
    classes.forEach(c => {
        var classDateTime = new Date(c.class_date + ' ' + c.start_time);
        var timeUntil = getTimeUntil(classDateTime);

        var emoji = '🎥';
        html += '<div class="class-card animate__animated animate__fadeInUp" style="padding:0; overflow:hidden; border-left: 5px solid var(--primary-color);">';
        html += '<div style="background: linear-gradient(135deg, var(--primary-color), var(--primary-dark)); color:white; padding:16px; display:flex; align-items:center; justify-content:space-between; gap:12px;">';
        html += '<div style="font-size:2rem;">' + emoji + '</div>';
        html += '<div style="flex:1;">';
        html += '<div style="font-weight:800; font-size:1.05rem;">' + c.title + '</div>';
        html += '<div style="font-size:0.85rem; opacity:0.9;">' + (c.subject || '-') + ' • 👨‍🏫 ' + (c.teacher_name || 'Guru') + '</div>';
        html += '</div>';
        html += '<div class="countdown-timer" id="countdown_' + c.id + '" style="background: rgba(255,255,255,0.2); padding:6px 10px; border-radius: 12px;">' + timeUntil + '</div>';
        html += '</div>';
        html += '<div style="padding:16px;">';
        html += '<div style="display:flex; gap:14px; flex-wrap:wrap; color:#475569; font-size:0.95rem;">';
        html += '<span>📅 ' + formatDate(c.class_date) + '</span>';
        html += '<span>🕐 ' + c.start_time + (c.end_time ? ' - ' + c.end_time : '') + '</span>';
        if (c.join_link) {
            html += '<a href="' + c.join_link + '" target="_blank" class="btn btn-success btn-sm" style="margin-left:auto;">Join Kelas</a>';
        }
        html += '</div>';
        html += '<button class="btn btn-primary btn-sm" style="margin-top:12px;" onclick="switchTab(\'classes\')">Lihat Butiran</button>';
        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">Tiada kelas lepas</p>';
        return;
    }

    var html = '';
    classes.forEach(c => {
        var emoji = '🏫';
        html += '<div class="class-card animate__animated animate__fadeIn" style="padding:0; overflow:hidden; border-left: 5px solid var(--primary-color); opacity:0.95;">';
        html += '<div style="background: linear-gradient(135deg, var(--primary-color), var(--primary-dark)); color:white; padding:16px; display:flex; align-items:center; gap:12px;">';
        html += '<div style="font-size:2rem;">' + emoji + '</div>';
        html += '<div style="flex:1;">';
        html += '<div style="font-weight:800; font-size:1.05rem;">' + c.title + '</div>';
        html += '<div style="font-size:0.85rem; opacity:0.9;">' + (c.subject || '-') + ' • 👨‍🏫 ' + (c.teacher_name || 'Guru') + '</div>';
        html += '</div>';
        html += '</div>';
        html += '<div style="padding:16px;">';
        html += '<div style="display:flex; gap:14px; flex-wrap:wrap; color:#475569; font-size:0.95rem;">';
        html += '<span>📅 ' + formatDate(c.class_date) + '</span>';
        html += '<span>🕐 ' + c.start_time + (c.end_time ? ' - ' + c.end_time : '') + '</span>';
        html += '</div>';

        if (c.recording_link) {
            html += '<a href="' + c.recording_link + '" target="_blank" class="btn btn-outline-primary btn-sm" style="margin-top:12px;">Tonton Rakaman</a>';
        }
        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">👨‍🏫 ' + (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 = '👨‍🏫 ' + (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">👨‍🏫 ' + (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 = 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>👨‍🏫 ' + (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);
    }
});
