<?php
require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../config/rbac.php';
require_once '../includes/functions.php';
require_once '../includes/middleware.php';

// Check if user is student or higher
studentOrHigher();

$user = getUserContext();
$page_title = 'My Reports - Mutalex Academy';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($page_title); ?></title>
    <!-- Load Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Set up Tailwind configuration for Inter font and a professional color palette -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'primary-blue': '#1E3A8A', // Deep Indigo/Navy
                        'background-light': '#F8FAFC', // Slate 50
                        'text-dark': '#1F2937', // Gray 800
                        'accent-subtle': '#E5E7EB', // Gray 200
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style>
        /* Ensuring full page height and scrolling */
        html, body {
            height: 100%;
        }
        /* Custom scrollbar for a cleaner look */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        ::-webkit-scrollbar-thumb {
            background-color: #D1D5DB; /* Gray 300 */
            border-radius: 4px;
        }
        ::-webkit-scrollbar-track {
            background-color: transparent;
        }
    </style>
</head>
<body class="bg-background-light font-sans text-text-dark min-h-screen">

    <!-- Main Application Container -->
    <div id="app" class="flex">

        <!-- Sidebar Navigation (Desktop View) -->
        <aside class="hidden lg:block w-64 bg-white border-r border-accent-subtle p-6 shadow-sm sticky top-0 h-screen">
            <div class="flex flex-col h-full">
                <!-- Logo/Title -->
                <div class="text-xl font-extrabold text-primary-blue mb-10 tracking-wider">
                    MUTALEX ACADEMY
                </div>

                <!-- Navigation Links -->
                <nav class="space-y-2 flex-grow">
                    <a href="dashboard.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Home -->
                        <span class="w-5 h-5">🏠</span>
                        <span>Dashboard</span>
                    </a>
                    <a href="courses.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Book -->
                        <span class="w-5 h-5">📚</span>
                        <span>My Courses</span>
                    </a>
                    <a href="reports.php" class="flex items-center space-x-3 p-3 rounded-lg bg-primary-blue text-white font-semibold transition duration-150 shadow-md">
                        <!-- Icon Placeholder: Checkmark -->
                        <span class="w-5 h-5">✅</span>
                        <span>Grades & Reports</span>
                    </a>
                    <a href="#" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Calendar -->
                        <span class="w-5 h-5">📅</span>
                        <span>Calendar</span>
                    </a>
                </nav>

                <!-- Footer/User Info (Bottom of Sidebar) -->
                <div class="mt-8 pt-4 border-t border-accent-subtle">
                    <p class="text-xs text-gray-500 mb-2">Authenticated User:</p>
                    <p class="text-xs text-gray-700 truncate font-mono bg-accent-subtle p-1 rounded"><?php echo htmlspecialchars($user['username'] ?? 'User'); ?></p>
                </div>
            </div>
        </aside>

        <!-- Main Content Area -->
        <main class="flex-1 overflow-y-auto">

            <!-- Top Bar (Mobile/Desktop Header) -->
            <header class="bg-white shadow-sm sticky top-0 z-10 border-b border-accent-subtle">
                <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 flex justify-between items-center">
                    <h1 class="text-2xl font-bold text-text-dark">My Reports</h1>

                    <div class="flex items-center space-x-4">
                        <!-- User Profile Dropdown (Mock) -->
                        <div class="relative group">
                            <button class="flex items-center space-x-2 p-2 rounded-full hover:bg-accent-subtle transition duration-150">
                                <span class="text-sm font-medium hidden sm:inline"><?php echo htmlspecialchars($user['username'] ?? 'Student'); ?></span>
                                <img class="h-10 w-10 rounded-full border-2 border-primary-blue object-cover" src="https://placehold.co/100x100/1E3A8A/ffffff?text=<?php echo substr(htmlspecialchars($user['username'] ?? 'S'), 0, 1); ?>" alt="User Avatar">
                            </button>
                            <!-- Mobile Menu Button (Hamburger) -->
                            <button class="lg:hidden p-2 rounded-lg text-text-dark hover:bg-accent-subtle ml-4" id="mobileMenuButton">
                                <span class="text-xl">☰</span>
                            </button>
                        </div>
                    </div>
                </div>
            </header>

            <!-- Mobile Navigation Overlay (Hidden by default) -->
            <div id="mobileMenu" class="fixed inset-0 bg-white z-20 p-6 transform -translate-x-full transition-transform duration-300 lg:hidden">
                <div class="flex justify-between items-center mb-10">
                    <div class="text-xl font-extrabold text-primary-blue tracking-wider">MUTALEX ACADEMY</div>
                    <button id="closeMobileMenu" class="text-3xl text-text-dark">&times;</button>
                </div>
                <nav class="space-y-4">
                    <!-- Links repeated from sidebar -->
                    <a href="dashboard.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">🏠 Dashboard</a>
                    <a href="courses.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📚 My Courses</a>
                    <a href="reports.php" class="block p-3 rounded-lg bg-primary-blue text-white font-semibold">✅ Grades & Reports</a>
                    <a href="#" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📅 Calendar</a>
                </nav>
            </div>

            <!-- Main Content Area -->
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">

                <!-- Welcome Banner -->
                <div class="bg-white p-6 sm:p-8 rounded-xl shadow-lg mb-8 border-t-4 border-primary-blue">
                    <div class="flex items-center justify-between">
                        <div>
                            <h1 class="text-3xl font-bold text-gray-800">My Learning Reports</h1>
                            <p class="mt-2 text-gray-600">Track your progress, view grades, and analyze your learning journey.</p>
                        </div>
                        <div class="hidden sm:block">
                            <i data-lucide="bar-chart-3" class="w-16 h-16 text-primary-blue"></i>
                        </div>
                    </div>
                </div>

                <!-- Overview Statistics -->
                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 mb-10" id="overview-stats">
                    <!-- Stat Card 1: Enrolled Courses -->
                    <div class="bg-white p-6 rounded-xl shadow-md transition duration-300 hover:shadow-lg flex flex-col justify-between">
                        <div class="flex items-center justify-between">
                            <p class="text-sm font-medium text-gray-500">Enrolled Courses</p>
                            <i data-lucide="book-open" class="text-blue-500 h-6 w-6"></i>
                        </div>
                        <p class="mt-1 text-4xl font-extrabold text-gray-900" id="enrolled-courses">-</p>
                        <p class="text-sm text-gray-500 mt-2">Total courses enrolled</p>
                    </div>

                    <!-- Stat Card 2: Completed Courses -->
                    <div class="bg-white p-6 rounded-xl shadow-md transition duration-300 hover:shadow-lg flex flex-col justify-between">
                        <div class="flex items-center justify-between">
                            <p class="text-sm font-medium text-gray-500">Completed Courses</p>
                            <i data-lucide="check-circle" class="text-green-500 h-6 w-6"></i>
                        </div>
                        <p class="mt-1 text-4xl font-extrabold text-gray-900" id="completed-courses">-</p>
                        <p class="text-sm text-gray-500 mt-2">Successfully finished</p>
                    </div>

                    <!-- Stat Card 3: Average Grade -->
                    <div class="bg-white p-6 rounded-xl shadow-md transition duration-300 hover:shadow-lg flex flex-col justify-between">
                        <div class="flex items-center justify-between">
                            <p class="text-sm font-medium text-gray-500">Average Grade</p>
                            <i data-lucide="trending-up" class="text-purple-500 h-6 w-6"></i>
                        </div>
                        <p class="mt-1 text-4xl font-extrabold text-gray-900" id="avg-grade">0.0%</p>
                        <p class="text-sm text-gray-500 mt-2">Across all exams</p>
                    </div>

                    <!-- Stat Card 4: Study Time -->
                    <div class="bg-white p-6 rounded-xl shadow-md transition duration-300 hover:shadow-lg flex flex-col justify-between">
                        <div class="flex items-center justify-between">
                            <p class="text-sm font-medium text-gray-500">Study Time</p>
                            <i data-lucide="clock" class="text-orange-500 h-6 w-6"></i>
                        </div>
                        <p class="mt-1 text-4xl font-extrabold text-gray-900" id="study-time">0h</p>
                        <p class="text-sm text-gray-500 mt-2">This week</p>
                    </div>
                </div>

                <!-- Analytics Charts -->
                <div class="grid grid-cols-1 lg:grid-cols-3 gap-8 mb-10">
                    <!-- Progress Trend Chart -->
                    <div class="bg-white p-6 rounded-xl shadow-lg">
                        <h3 class="text-xl font-semibold text-gray-800 mb-4 flex items-center">
                            <i data-lucide="trending-up" class="w-5 h-5 mr-2 text-blue-500"></i>
                            Progress Trend
                        </h3>
                        <div class="h-64">
                            <canvas id="progress-trend-chart"></canvas>
                        </div>
                    </div>

                    <!-- Grade History Chart -->
                    <div class="bg-white p-6 rounded-xl shadow-lg">
                        <h3 class="text-xl font-semibold text-gray-800 mb-4 flex items-center">
                            <i data-lucide="bar-chart-3" class="w-5 h-5 mr-2 text-green-500"></i>
                            Grade History
                        </h3>
                        <div class="h-64">
                            <canvas id="grade-history-chart"></canvas>
                        </div>
                    </div>

                    <!-- Course Completion Chart -->
                    <div class="bg-white p-6 rounded-xl shadow-lg">
                        <h3 class="text-xl font-semibold text-gray-800 mb-4 flex items-center">
                            <i data-lucide="pie-chart" class="w-5 h-5 mr-2 text-purple-500"></i>
                            Course Completion
                        </h3>
                        <div class="h-64">
                            <canvas id="course-completion-chart"></canvas>
                        </div>
                    </div>
                </div>

                <!-- Detailed Reports Sections -->
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-10">

                    <!-- Course Progress -->
                    <div class="bg-white p-6 rounded-xl shadow-lg">
                        <h3 class="text-xl font-semibold text-gray-800 mb-6 flex items-center">
                            <i data-lucide="book-open" class="w-5 h-5 mr-2 text-blue-500"></i>
                            Course Progress
                        </h3>
                        <div id="course-progress" class="space-y-4">
                            <div class="flex items-center justify-center py-8">
                                <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
                                <span class="ml-3 text-gray-600">Loading course progress...</span>
                            </div>
                        </div>
                    </div>

                    <!-- Grade History -->
                    <div class="bg-white p-6 rounded-xl shadow-lg">
                        <h3 class="text-xl font-semibold text-gray-800 mb-6 flex items-center">
                            <i data-lucide="graduation-cap" class="w-5 h-5 mr-2 text-green-500"></i>
                            Grade History
                        </h3>
                        <div id="grade-history" class="overflow-x-auto">
                            <div class="flex items-center justify-center py-8">
                                <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-green-500"></div>
                                <span class="ml-3 text-gray-600">Loading grade history...</span>
                            </div>
                        </div>
                    </div>

                    <!-- Achievement Timeline -->
                    <div class="bg-white p-6 rounded-xl shadow-lg">
                        <h3 class="text-xl font-semibold text-gray-800 mb-6 flex items-center">
                            <i data-lucide="trophy" class="w-5 h-5 mr-2 text-amber-500"></i>
                            Achievement Timeline
                        </h3>
                        <div id="achievement-timeline" class="space-y-4">
                            <div class="flex items-center justify-center py-8">
                                <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-amber-500"></div>
                                <span class="ml-3 text-gray-600">Loading achievements...</span>
                            </div>
                        </div>
                    </div>

                    <!-- Upcoming Deadlines -->
                    <div class="bg-white p-6 rounded-xl shadow-lg">
                        <h3 class="text-xl font-semibold text-gray-800 mb-6 flex items-center">
                            <i data-lucide="calendar" class="w-5 h-5 mr-2 text-red-500"></i>
                            Upcoming Deadlines
                        </h3>
                        <div id="upcoming-deadlines" class="space-y-4">
                            <div class="flex items-center justify-center py-8">
                                <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-red-500"></div>
                                <span class="ml-3 text-gray-600">Loading deadlines...</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Export Options -->
                <div class="bg-white p-6 rounded-xl shadow-lg">
                    <h3 class="text-xl font-semibold text-gray-800 mb-6 flex items-center">
                        <i data-lucide="download" class="w-5 h-5 mr-2 text-indigo-500"></i>
                        Export Reports
                    </h3>
                    <p class="text-gray-600 mb-6">Download your learning reports in various formats for your records.</p>
                    <div class="flex flex-wrap gap-4">
                        <button onclick="exportReport('progress')" class="flex items-center gap-3 bg-blue-600 text-white px-6 py-3 rounded-lg font-semibold hover:bg-blue-700 transition duration-200">
                            <i data-lucide="file-text" class="w-5 h-5"></i>
                            Progress Report
                        </button>
                        <button onclick="exportReport('grades')" class="flex items-center gap-3 bg-green-600 text-white px-6 py-3 rounded-lg font-semibold hover:bg-green-700 transition duration-200">
                            <i data-lucide="file-spreadsheet" class="w-5 h-5"></i>
                            Grade Report
                        </button>
                        <button onclick="exportReport('certificate')" class="flex items-center gap-3 bg-purple-600 text-white px-6 py-3 rounded-lg font-semibold hover:bg-purple-700 transition duration-200">
                            <i data-lucide="award" class="w-5 h-5"></i>
                            Certificates
                        </button>
                    </div>
                </div>

            </div>
        </main>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
// Toast notification system
function showToast(message, type = 'success') {
    // Remove existing toasts
    const existingToasts = document.querySelectorAll('.toast-notification');
    existingToasts.forEach(toast => toast.remove());

    // Create toast element
    const toast = document.createElement('div');
    toast.className = `toast-notification fixed top-4 right-4 z-50 p-4 rounded-lg shadow-lg transform translate-x-full transition-all duration-300 ${
        type === 'success' ? 'bg-green-500 text-white' : 'bg-red-500 text-white'
    }`;
    toast.innerHTML = `
        <div class="flex items-center gap-3">
            <i class="fas ${type === 'success' ? 'fa-check-circle' : 'fa-exclamation-triangle'}"></i>
            <span>${message}</span>
        </div>
    `;

    // Add to page
    document.body.appendChild(toast);

    // Animate in
    setTimeout(() => {
        toast.classList.remove('translate-x-full');
    }, 100);

    // Auto remove after 4 seconds
    setTimeout(() => {
        toast.classList.add('translate-x-full');
        setTimeout(() => {
            toast.remove();
        }, 300);
    }, 4000);
}

let progressTrendChart, gradeHistoryChart, courseCompletionChart;

document.addEventListener('DOMContentLoaded', function() {
    // Initialize Lucide Icons
    lucide.createIcons();

    // Mobile Menu Toggle
    const mobileMenuButton = document.getElementById('mobile-menu-button');
    const mobileMenu = document.getElementById('mobile-menu');

    if (mobileMenuButton && mobileMenu) {
        mobileMenuButton.addEventListener('click', () => {
            mobileMenu.classList.toggle('hidden');
        });
    }

    loadStudentReports();
    initializeCharts();
});

function loadStudentReports() {
    fetch('../api/analytics/index.php?action=student_progress')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                updateOverviewStats(data.data);
                updateCharts(data.data);
                updateCourseProgress(data.data.course_progress);
                updateGradeHistory(data.data.grade_history);
                updateAchievementTimeline(data.data.achievement_timeline);
                updateUpcomingDeadlines(data.data.upcoming_deadlines);
            } else {
                console.error('Failed to load student reports:', data.message);
                showError('Failed to load reports');
            }
        })
        .catch(error => {
            console.error('Error loading student reports:', error);
            showError('Error loading reports');
        });
}

function updateOverviewStats(data) {
    // This would be calculated from the API response
    // For now, using placeholder data
    document.getElementById('enrolled-courses').textContent = '5';
    document.getElementById('completed-courses').textContent = '2';
    document.getElementById('avg-grade').textContent = '85.5';
    document.getElementById('study-time').textContent = '12h';
}

function initializeCharts() {
    // Progress Trend Chart
    const progressTrendCtx = document.getElementById('progress-trend-chart').getContext('2d');
    progressTrendChart = new Chart(progressTrendCtx, {
        type: 'line',
        data: {
            labels: ['Week 1', 'Week 2', 'Week 3', 'Week 4'],
            datasets: [{
                label: 'Progress %',
                data: [20, 45, 65, 85],
                borderColor: '#007bff',
                backgroundColor: 'rgba(0, 123, 255, 0.1)',
                tension: 0.4,
                fill: true
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    max: 100
                }
            }
        }
    });

    // Grade History Chart
    const gradeHistoryCtx = document.getElementById('grade-history-chart').getContext('2d');
    gradeHistoryChart = new Chart(gradeHistoryCtx, {
        type: 'bar',
        data: {
            labels: ['Exam 1', 'Exam 2', 'Exam 3', 'Final'],
            datasets: [{
                label: 'Grade %',
                data: [78, 85, 92, 88],
                backgroundColor: '#28a745',
                borderColor: '#28a745',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    max: 100
                }
            }
        }
    });

    // Course Completion Chart
    const courseCompletionCtx = document.getElementById('course-completion-chart').getContext('2d');
    courseCompletionChart = new Chart(courseCompletionCtx, {
        type: 'doughnut',
        data: {
            labels: ['Completed', 'In Progress', 'Not Started'],
            datasets: [{
                data: [40, 35, 25],
                backgroundColor: [
                    '#28a745',
                    '#ffc107',
                    '#dc3545'
                ],
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });
}

function updateCharts(data) {
    // Update charts with real data from API
    if (data.study_time && progressTrendChart) {
        // Update progress trend chart
        const weeks = data.study_time.map(item => `Week ${item.week}`);
        const progressData = data.study_time.map(item => Math.floor(Math.random() * 100)); // Placeholder
        progressTrendChart.data.labels = weeks;
        progressTrendChart.data.datasets[0].data = progressData;
        progressTrendChart.update();
    }
}

function updateCourseProgress(courses) {
    const container = document.getElementById('course-progress');
    if (!courses || courses.length === 0) {
        container.innerHTML = '<div class="text-center py-8"><i data-lucide="book-open" class="w-12 h-12 text-gray-300 mx-auto mb-3"></i><p class="text-gray-500">No courses enrolled yet.</p></div>';
        lucide.createIcons();
        return;
    }

    container.innerHTML = courses.map(course => `
        <div class="bg-gray-50 p-4 rounded-lg">
            <div class="flex justify-between items-start mb-3">
                <h5 class="font-semibold text-gray-800">${course.title}</h5>
                <span class="px-2 py-1 text-xs font-medium rounded-full ${
                    course.status === 'completed' ? 'bg-green-100 text-green-800' :
                    course.status === 'in_progress' ? 'bg-blue-100 text-blue-800' :
                    'bg-gray-100 text-gray-800'
                }">${course.status.replace('_', ' ')}</span>
            </div>
            <div class="mb-2">
                <div class="flex justify-between text-sm text-gray-600 mb-1">
                    <span>Progress</span>
                    <span>${course.progress_percentage}%</span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-2">
                    <div class="bg-blue-600 h-2 rounded-full transition-all duration-300" style="width: ${course.progress_percentage}%"></div>
                </div>
            </div>
        </div>
    `).join('');
    lucide.createIcons();
}

function updateGradeHistory(grades) {
    const container = document.getElementById('grade-history');
    if (!grades || grades.length === 0) {
        container.innerHTML = '<div class="text-center py-8"><i data-lucide="graduation-cap" class="w-12 h-12 text-gray-300 mx-auto mb-3"></i><p class="text-gray-500">No grades available yet.</p></div>';
        lucide.createIcons();
        return;
    }

    container.innerHTML = `
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Exam</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Course</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Grade</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Date</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    ${grades.map(grade => `
                        <tr class="hover:bg-gray-50">
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${grade.exam_title}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${grade.course_title}</td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                                    grade.percentage >= 90 ? 'bg-green-100 text-green-800' :
                                    grade.percentage >= 80 ? 'bg-blue-100 text-blue-800' :
                                    grade.percentage >= 70 ? 'bg-yellow-100 text-yellow-800' :
                                    grade.percentage >= 60 ? 'bg-orange-100 text-orange-800' :
                                    'bg-red-100 text-red-800'
                                }">
                                    ${grade.percentage}%
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                                    grade.is_passed ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                                }">
                                    ${grade.is_passed ? 'Passed' : 'Failed'}
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${new Date(grade.completed_at).toLocaleDateString()}</td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        </div>
    `;
    lucide.createIcons();
}

function updateAchievementTimeline(achievements) {
    const container = document.getElementById('achievement-timeline');
    if (!achievements || achievements.length === 0) {
        container.innerHTML = '<div class="text-center py-8"><i data-lucide="trophy" class="w-12 h-12 text-gray-300 mx-auto mb-3"></i><p class="text-gray-500">No achievements yet. Keep learning!</p></div>';
        lucide.createIcons();
        return;
    }

    container.innerHTML = achievements.map(achievement => `
        <div class="flex items-start gap-4 pb-4">
            <div class="w-10 h-10 bg-amber-100 rounded-full flex items-center justify-center flex-shrink-0">
                <i data-lucide="trophy" class="w-5 h-5 text-amber-600"></i>
            </div>
            <div class="flex-1 min-w-0">
                <h6 class="text-sm font-medium text-gray-900">${achievement.action_description}</h6>
                <p class="text-xs text-gray-500 mt-1">${new Date(achievement.created_at).toLocaleDateString()}</p>
            </div>
        </div>
    `).join('');
    lucide.createIcons();
}

function updateUpcomingDeadlines(deadlines) {
    const container = document.getElementById('upcoming-deadlines');
    if (!deadlines || deadlines.length === 0) {
        container.innerHTML = '<div class="text-center py-8"><i data-lucide="calendar" class="w-12 h-12 text-gray-300 mx-auto mb-3"></i><p class="text-gray-500">No upcoming deadlines.</p></div>';
        lucide.createIcons();
        return;
    }

    container.innerHTML = deadlines.map(deadline => `
        <div class="flex items-center justify-between p-4 bg-red-50 border border-red-200 rounded-lg">
            <div>
                <h6 class="font-medium text-gray-900 text-sm">${deadline.title}</h6>
                <p class="text-xs text-gray-600 mt-1">${deadline.course_title}</p>
            </div>
            <div class="text-right">
                <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800">
                    ${new Date(deadline.end_date).toLocaleDateString()}
                </span>
            </div>
        </div>
    `).join('');
    lucide.createIcons();
}

function exportReport(type) {
    let endpoint = '';
    switch (type) {
        case 'progress':
            endpoint = '../api/analytics/index.php?action=export_data&type=user_data&format=csv';
            break;
        case 'grades':
            endpoint = '../api/analytics/index.php?action=export_data&type=exam_results&format=csv';
            break;
        case 'certificate':
            showToast('Certificate download feature coming soon!', 'success');
            return;
    }

    // Show loading toast
    showToast('Preparing your report...', 'success');

    const link = document.createElement('a');
    link.href = endpoint;
    link.download = `${type}_report.csv`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    // Show success toast
    setTimeout(() => {
        showToast('Report downloaded successfully!', 'success');
    }, 1000);
}

function showError(message) {
    showToast(message, 'error');
}
    </script>

    <!-- JavaScript for Mobile Menu Functionality -->
    <script>
        const mobileMenuButton = document.getElementById('mobileMenuButton');
        const closeMobileMenu = document.getElementById('closeMobileMenu');
        const mobileMenu = document.getElementById('mobileMenu');

        if (mobileMenuButton && closeMobileMenu && mobileMenu) {
            mobileMenuButton.addEventListener('click', () => {
                mobileMenu.classList.remove('-translate-x-full');
            });

            closeMobileMenu.addEventListener('click', () => {
                mobileMenu.classList.add('-translate-x-full');
            });

            // Close menu when a link is clicked
            mobileMenu.querySelectorAll('a').forEach(link => {
                link.addEventListener('click', () => {
                    mobileMenu.classList.add('-translate-x-full');
                });
            });
        }
    </script>
</body>
</html>