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

/**
 * Load today'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 today = new Date().toISOString().split('T')[0];
                var todaySchedules = result.schedules.filter(s => s.schedule_date === today);

                if (todaySchedules.length > 0) {
                    var html = '';
                    todaySchedules.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.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>';
                    });

                    document.getElementById('classTodayCount').textContent = todaySchedules.length;

                    if (todaySchedules.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 ' + (todaySchedules.length - 3) + ' lagi</a>';
                        html += '</div>';
                    }

                    container.innerHTML = html;
                } else {
                    container.innerHTML = '<p class="text-center text-muted">Tiada kelas hari ini 😊</p>';
                }
            } else {
                container.innerHTML = '<p class="text-center text-muted">Tiada jadual. Sila hubungi guru anda.</p>';
            }
        })
        .catch(err => {
            console.error('Error loading today 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;">👨‍🏫 ' + (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>';
        });
}

/**
 * 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__fadeIn">';
        html += '<div style="text-align: center; margin-bottom: 15px;">';
        html += '<div style="font-size: 3rem; margin-bottom: 10px;">' + emoji + '</div>';
        html += '<h4 style="color: var(--primary-color); margin: 0;">' + module.title + '</h4>';
        html += '</div>';
        html += '<div style="text-align: center; margin-bottom: 15px;">';
        html += '<span class="badge badge-primary">' + module.subject + '</span>';
        html += '</div>';
        html += '<p style="color: #666; font-size: 0.9rem; text-align: center;">' + (module.description || 'Tiada penerangan') + '</p>';
        html += '<div style="text-align: center; margin-top: 15px;">';
        html += '<small class="text-muted">👨‍🏫 ' + (module.teacher_name || 'Guru') + '</small><br>';
        html += '<small class="text-muted">📎 ' + links.length + ' pautan</small>';
        html += '</div>';
        html += '<button class="btn btn-primary btn-sm" style="width: 100%; margin-top: 15px;" onclick="viewModuleDetail(' + module.id + ')">';
        html += '<i class="fas fa-eye"></i> Lihat Modul';
        html += '</button>';
        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 => {
            linksHtml += '<a href="' + link + '" target="_blank" class="btn btn-outline-primary btn-sm" style="margin: 3px;">';
            linksHtml += '<i class="fas fa-external-link-alt"></i> ' + truncateText(link, 40);
            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;
                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);
        });
}

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

        html += '<div class="class-card">';
        html += '<div style="display: flex; justify-content: space-between; align-items: start;">';
        html += '<div style="flex: 1;">';
        html += '<h5 style="margin: 0 0 5px 0; color: var(--primary-color);">' + c.title + '</h5>';
        html += '<div style="margin: 5px 0;"><span class="badge badge-primary">' + c.subject + '</span></div>';
        html += '<p style="margin: 5px 0; font-size: 0.9rem; color: #666;">' + (c.description || '') + '</p>';
        html += '<div style="margin-top: 10px; font-size: 0.9rem;">';
        html += '<div>📅 ' + formatDate(c.class_date) + '</div>';
        html += '<div>🕐 ' + c.start_time + (c.end_time ? ' - ' + c.end_time : '') + '</div>';
        html += '<div>👨‍🏫 ' + (c.teacher_name || 'Guru') + '</div>';
        html += '</div>';
        html += '</div>';
        html += '<div style="text-align: right;">';
        html += '<div class="countdown-timer" id="countdown_' + c.id + '">' + timeUntil + '</div>';
        html += '</div>';
        html += '</div>';

        if (c.join_link) {
            html += '<a href="' + c.join_link + '" target="_blank" class="btn btn-success" style="width: 100%; margin-top: 15px;">';
            html += '<i class="fas fa-video"></i> Join Kelas Sekarang';
            html += '</a>';
        }
        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 => {
        html += '<div class="class-card" style="opacity: 0.8;">';
        html += '<div style="display: flex; justify-content: space-between; align-items: start;">';
        html += '<div style="flex: 1;">';
        html += '<h5 style="margin: 0 0 5px 0;">' + c.title + '</h5>';
        html += '<div style="margin: 5px 0;"><span class="badge badge-secondary">' + c.subject + '</span></div>';
        html += '<div style="margin-top: 10px; font-size: 0.9rem; color: #666;">';
        html += '<div>📅 ' + formatDate(c.class_date) + '</div>';
        html += '<div>🕐 ' + c.start_time + '</div>';
        html += '<div>👨‍🏫 ' + (c.teacher_name || 'Guru') + '</div>';
        html += '</div>';
        html += '</div>';
        html += '</div>';

        if (c.recording_link) {
            html += '<a href="' + c.recording_link + '" target="_blank" class="btn btn-outline-primary btn-sm" style="margin-top: 10px;">';
            html += '<i class="fas fa-play-circle"></i> Tonton Rakaman';
            html += '</a>';
        }
        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;

    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>';
                    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);

    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 = '';
                loadForumReplies(forumId);
            } else {
                showNotification(result.message, 'error');
            }
        })
        .catch(err => {
            showNotification('Ralat sambungan', 'error');
        });
}

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