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

// Establish secure database connection
$db = getDB();

// Fetch student progress data
$studentId = $user['id'];

// Overview stats
$stmt = $db->prepare("SELECT COUNT(*) as enrolled_courses FROM course_enrollments WHERE student_id = ? AND status = 'enrolled'");
$stmt->execute([$studentId]);
$enrolledCourses = $stmt->fetch(PDO::FETCH_ASSOC)['enrolled_courses'];

$stmt = $db->prepare("SELECT COUNT(*) as completed_courses FROM course_enrollments WHERE student_id = ? AND status = 'completed'");
$stmt->execute([$studentId]);
$completedCourses = $stmt->fetch(PDO::FETCH_ASSOC)['completed_courses'];

$stmt = $db->prepare("
    SELECT AVG(ea.percentage) as avg_grade
    FROM exam_attempts ea
    JOIN exams e ON ea.exam_id = e.id
    JOIN course_enrollments ce ON e.course_id = ce.course_id
    WHERE ce.student_id = ? AND ea.status = 'completed'
");
$stmt->execute([$studentId]);
$avgGrade = round($stmt->fetch(PDO::FETCH_ASSOC)['avg_grade'] ?? 0, 2);

$stmt = $db->prepare("
    SELECT SUM(clp.time_spent) as study_time
    FROM course_lesson_progress clp
    JOIN course_enrollments ce ON clp.enrollment_id = ce.id
    WHERE ce.student_id = ? AND clp.last_accessed >= DATE_SUB(NOW(), INTERVAL 7 DAY)
");
$stmt->execute([$studentId]);
$studyTime = $stmt->fetch(PDO::FETCH_ASSOC)['study_time'] ?? 0;

$overview = [
    'enrolled_courses' => $enrolledCourses,
    'completed_courses' => $completedCourses,
    'avg_grade' => $avgGrade,
    'study_time_week' => $studyTime
];

// Course progress
$stmt = $db->prepare("
    SELECT ce.course_id, c.title, ce.progress_percentage, ce.status, ce.enrollment_date, ce.completion_date
    FROM course_enrollments ce
    JOIN courses c ON ce.course_id = c.id
    WHERE ce.student_id = ?
    ORDER BY ce.enrollment_date DESC
");
$stmt->execute([$studentId]);
$courseProgress = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Grade history
$stmt = $db->prepare("
    SELECT e.title as exam_title, c.title as course_title, ea.percentage, ea.is_passed, ea.completed_at
    FROM exam_attempts ea
    JOIN exams e ON ea.exam_id = e.id
    JOIN courses c ON e.course_id = c.id
    JOIN course_enrollments ce ON c.id = ce.course_id
    WHERE ce.student_id = ? AND ea.status = 'completed'
    ORDER BY ea.completed_at DESC
");
$stmt->execute([$studentId]);
$gradeHistory = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Achievement timeline
$stmt = $db->prepare("
    SELECT ua.action_description, ua.created_at, ua.metadata
    FROM user_activities ua
    WHERE ua.user_id = ? AND ua.action_type IN ('course_completed', 'exam_passed', 'achievement_earned')
    ORDER BY ua.created_at DESC
    LIMIT 20
");
$stmt->execute([$studentId]);
$achievementTimeline = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Upcoming deadlines
$stmt = $db->prepare("
    SELECT e.title, e.end_date, c.title as course_title
    FROM exams e
    JOIN courses c ON e.course_id = c.id
    JOIN course_enrollments ce ON c.id = ce.course_id
    WHERE ce.student_id = ? AND e.end_date > NOW()
    ORDER BY e.end_date ASC
    LIMIT 5
");
$stmt->execute([$studentId]);
$upcomingDeadlines = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Charts data
// Progress trend
$stmt = $db->prepare("
    SELECT DATE(clp.last_accessed) as date, AVG(clp.progress_percentage) as avg_progress
    FROM course_lesson_progress clp
    JOIN course_enrollments ce ON clp.enrollment_id = ce.id
    WHERE ce.student_id = ? AND clp.last_accessed >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    GROUP BY DATE(clp.last_accessed)
    ORDER BY date
");
$stmt->execute([$studentId]);
$progressTrend = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Grade history chart
$stmt = $db->prepare("
    SELECT DATE(ea.completed_at) as date, ea.percentage as grade, e.title as exam_title
    FROM exam_attempts ea
    JOIN exams e ON ea.exam_id = e.id
    JOIN course_enrollments ce ON e.course_id = ce.course_id
    WHERE ce.student_id = ? AND ea.status = 'completed'
    ORDER BY ea.completed_at DESC
    LIMIT 20
");
$stmt->execute([$studentId]);
$gradeHistoryChart = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Course completion chart
$stmt = $db->prepare("
    SELECT c.title, ce.progress_percentage as progress
    FROM course_enrollments ce
    JOIN courses c ON ce.course_id = c.id
    WHERE ce.student_id = ?
    ORDER BY ce.enrollment_date DESC
");
$stmt->execute([$studentId]);
$courseCompletion = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Prepare data for JavaScript
$reportData = [
    'overview' => $overview,
    'course_progress' => $courseProgress,
    'grade_history' => $gradeHistory,
    'achievement_timeline' => $achievementTimeline,
    'upcoming_deadlines' => $upcomingDeadlines,
    'charts' => [
        'progress_trend' => $progressTrend,
        'grade_history' => $gradeHistoryChart,
        'course_completion' => $courseCompletion
    ]
];
?>

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

        <!-- Top Bar (Mobile/Desktop Header) -->
        <header class="bg-white shadow-sm fixed top-0 left-0 right-0 z-10 border-b border-accent-subtle">
            <div class="px-4 sm:px-6 lg:px-8 py-4 flex justify-between items-center">
                <div class="flex items-center space-x-3">
                    <img src="../assets/images/logo_1757657555.jpg" alt="Mutalex Academy Logo" class="h-10 w-10">
                    <div>
                        <h1 class="text-xl font-bold text-primary-blue">Mutalex Academy</h1>
                        <p class="text-sm text-gray-600">Grades & Reports</p>
                    </div>
                </div>

                <div class="flex items-center space-x-4">
                    <!-- Cart Button -->
                    <button onclick="showDashboardCheckoutModal()" class="text-gray-600 hover:text-primary-blue p-2 rounded-full relative transition duration-150">
                        <!-- Shopping Cart Icon -->
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-shopping-cart">
                            <circle cx="8" cy="21" r="1"/>
                            <circle cx="19" cy="21" r="1"/>
                            <path d="M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.15"/>
                        </svg>
                        <span id="dashboard-cart-count" class="absolute -top-1 -right-1 bg-red-500 text-white text-xs font-bold rounded-full h-5 w-5 flex items-center justify-center hidden">0</span>
                    </button>

                    <!-- User Profile -->
                    <div class="flex items-center space-x-2">
                        <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">
                        <!-- 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>

        <!-- Sidebar Navigation (Desktop View) -->
        <aside class="hidden lg:block w-64 bg-white border-r border-accent-subtle p-6 shadow-sm sticky top-16 h-screen">
            <div class="flex flex-col h-full">
                <!-- Logo/Title -->
                <div class="text-xl font-extrabold text-primary-blue mb-10 tracking-wider">
                </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="available_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: Catalog -->
                        <span class="w-5 h-5">📖</span>
                        <span>View All Courses</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="exams.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Exam -->
                        <span class="w-5 h-5">📝</span>
                        <span>My Exam</span>
                    </a>
                    <a href="../exams/catalog.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: All Exams -->
                        <span class="w-5 h-5">📋</span>
                        <span>All Exam</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="calendar.php" 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>
                    <a href="../index.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Globe -->
                        <span class="w-5 h-5">🌐</span>
                        <span>View Site</span>
                    </a>
                    <a href="../logout.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Logout -->
                        <span class="w-5 h-5">🚪</span>
                        <span>Logout</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 pt-16">

            <!-- 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"></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="available_courses.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📖 View All Courses</a>
                    <a href="courses.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📚 My Courses</a>
                    <a href="exams.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📝 My Exam</a>
                    <a href="../exams/catalog.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📋 All Exam</a>
                    <a href="reports.php" class="block p-3 rounded-lg bg-primary-blue text-white font-semibold">✅ Grades & Reports</a>
                    <a href="calendar.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📅 Calendar</a>
                    <a href="../index.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">🌐 View Site</a>
                    <a href="../logout.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">🚪 Logout</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>

                <!-- Filters -->
                <div class="bg-white p-6 rounded-xl shadow-lg mb-8">
                    <h3 class="text-xl font-semibold text-gray-800 mb-4">Filters</h3>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Course</label>
                            <select id="course-filter" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-blue focus:ring-primary-blue">
                                <option value="">All Courses</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700">From Date</label>
                            <input type="date" id="date-from" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-blue focus:ring-primary-blue">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700">To Date</label>
                            <input type="date" id="date-to" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-blue focus:ring-primary-blue">
                        </div>
                    </div>
                    <button onclick="applyFilters()" class="mt-4 bg-primary-blue text-white px-6 py-2 rounded-lg font-semibold hover:bg-blue-700 transition duration-200">Apply Filters</button>
                </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>
        // Server-side loaded data
        window.currentData = <?php echo json_encode($reportData); ?>;
    </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');
        });
    }

    // Load data from server-side
    updateOverviewStats(window.currentData);
    updateCharts(window.currentData);
    updateCourseProgress(window.currentData.course_progress);
    updateGradeHistory(window.currentData.grade_history);
    updateAchievementTimeline(window.currentData.achievement_timeline);
    updateUpcomingDeadlines(window.currentData.upcoming_deadlines);
    populateCourseFilter(window.currentData.course_progress);

    initializeCharts();
});

function loadStudentReports(courseId = '', dateFrom = '', dateTo = '') {
    // If no filters, use server-side data
    if (!courseId && !dateFrom && !dateTo) {
        return;
    }

    // For filtered data, fetch from API
    let url = '../api/analytics/index.php?action=student_progress';
    const params = new URLSearchParams();
    if (courseId) params.append('course_id', courseId);
    if (dateFrom) params.append('date_from', dateFrom);
    if (dateTo) params.append('date_to', dateTo);
    if (params.toString()) url += '&' + params.toString();
    fetch(url)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                window.currentData = data.data;
                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);
                populateCourseFilter(data.data.course_progress);
            } 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 applyFilters() {
    const courseId = document.getElementById('course-filter').value;
    const dateFrom = document.getElementById('date-from').value;
    const dateTo = document.getElementById('date-to').value;
    loadStudentReports(courseId, dateFrom, dateTo);
}

function populateCourseFilter(courses) {
    const select = document.getElementById('course-filter');
    const currentValue = select.value;
    select.innerHTML = '<option value="">All Courses</option>';
    const uniqueCourses = [...new Map(courses.map(course => [course.course_id, course])).values()];
    uniqueCourses.forEach(course => {
        const option = document.createElement('option');
        option.value = course.course_id;
        option.textContent = course.title;
        select.appendChild(option);
    });
    if (currentValue && select.querySelector(`option[value="${currentValue}"]`)) {
        select.value = currentValue;
    }
}

function updateOverviewStats(data) {
    document.getElementById('enrolled-courses').textContent = data.overview.enrolled_courses || 0;
    document.getElementById('completed-courses').textContent = data.overview.completed_courses || 0;
    document.getElementById('avg-grade').textContent = (data.overview.avg_grade || 0).toFixed(1) + '%';
    document.getElementById('study-time').textContent = Math.floor((data.overview.study_time_week || 0) / 3600) + 'h';
}

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 progress trend chart
    if (data.charts && data.charts.progress_trend && progressTrendChart) {
        const labels = data.charts.progress_trend.map(item => new Date(item.date).toLocaleDateString());
        const progressData = data.charts.progress_trend.map(item => item.avg_progress);
        progressTrendChart.data.labels = labels;
        progressTrendChart.data.datasets[0].data = progressData;
        progressTrendChart.update();
    }

    // Update grade history chart
    if (data.charts && data.charts.grade_history && gradeHistoryChart) {
        const labels = data.charts.grade_history.map(item => item.exam_title);
        const gradeData = data.charts.grade_history.map(item => item.grade);
        gradeHistoryChart.data.labels = labels;
        gradeHistoryChart.data.datasets[0].data = gradeData;
        gradeHistoryChart.update();
    }

    // Update course completion chart
    if (data.charts && data.charts.course_completion && courseCompletionChart) {
        const courses = data.charts.course_completion;
        const completed = courses.filter(c => c.progress == 100).length;
        const inProgress = courses.filter(c => c.progress > 0 && c.progress < 100).length;
        const notStarted = courses.filter(c => c.progress == 0).length;
        courseCompletionChart.data.datasets[0].data = [completed, inProgress, notStarted];
        courseCompletionChart.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) {
    if (!window.currentData) {
        showToast('No data available to export', 'error');
        return;
    }

    showToast('Preparing your report...', 'success');

    if (type === 'progress') {
        exportToCSV(window.currentData.course_progress, 'course_progress');
    } else if (type === 'grades') {
        exportToCSV(window.currentData.grade_history, 'grade_history');
    } else if (type === 'certificate') {
        showToast('Certificate download feature coming soon!', 'success');
        return;
    }

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

function exportToCSV(data, filename) {
    if (!data || data.length === 0) {
        showToast('No data to export', 'error');
        return;
    }
    const headers = Object.keys(data[0]);
    const csvContent = [headers.join(',')].concat(
        data.map(row => headers.map(header => `"${row[header] || ''}"`).join(','))
    ).join('\n');
    const blob = new Blob([csvContent], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${filename}.csv`;
    a.click();
    URL.revokeObjectURL(url);
}

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>