<?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 - Fixed for realistic data
$stmt = $db->prepare("SELECT COUNT(*) as enrolled_courses FROM course_enrollments WHERE student_id = ? AND (status IN ('enrolled', 'in_progress', 'active') OR status IS NULL OR status = '')");
$stmt->execute([$studentId]);
$enrolledCourses = $stmt->fetch(PDO::FETCH_ASSOC)['enrolled_courses'] ?? 0;

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

$stmt = $db->prepare("
    SELECT AVG(COALESCE(ea.percentage, 0)) as avg_grade
    FROM exam_attempts ea 
    WHERE ea.student_id = ? AND ea.status IN ('completed', 'graded', 'submitted')
");
$stmt->execute([$studentId]);
$avgGrade = round($stmt->fetch(PDO::FETCH_ASSOC)['avg_grade'] ?? 0, 2);

$stmt = $db->prepare("
    SELECT SUM(COALESCE(clp.time_spent, 0)) as study_time_week,
           SUM(COALESCE(clp.time_spent, 0)) as study_time_total
    FROM course_lesson_progress clp
    JOIN course_enrollments ce ON clp.enrollment_id = ce.id
    WHERE ce.student_id = ?
");
$stmt->execute([$studentId]);
$studyRow = $stmt->fetch(PDO::FETCH_ASSOC);
$studyTime = ($studyRow['study_time_week'] ?? 0) ?: $studyRow['study_time_total'] ?? 0;

$totalAttempts = $db->prepare("SELECT COUNT(*) as total FROM exam_attempts WHERE student_id = ?");
$totalAttempts->execute([$studentId]);
$totalAttemptsCount = $totalAttempts->fetch(PDO::FETCH_ASSOC)['total'] ?? 0;

$passedAttempts = $db->prepare("SELECT COUNT(*) as passed FROM exam_attempts WHERE student_id = ? AND (is_passed = 1 OR percentage >= 60)");
$passedAttempts->execute([$studentId]);
$passedCount = $passedAttempts->fetch(PDO::FETCH_ASSOC)['passed'] ?? 0;

$overview = [
    'enrolled_courses' => (int)$enrolledCourses,
    'completed_courses' => (int)$completedCourses,
    'avg_grade' => $avgGrade,
    'study_time_week' => (int)$studyTime,
    'total_exams' => (int)$totalAttemptsCount,
    'pass_rate' => $totalAttemptsCount > 0 ? round(($passedCount / $totalAttemptsCount) * 100, 1) : 0
];


// 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 - Simplified for reliability
$stmt = $db->prepare("
    SELECT 
        e.title as exam_title, 
        COALESCE(c.title, 'Standalone Exam') as course_title, 
        ea.percentage, 
        CASE WHEN ea.is_passed = 1 OR ea.percentage >= 60 THEN 1 ELSE 0 END as is_passed,
        ea.status,
        ea.completed_at,
        ea.attempt_number
    FROM exam_attempts ea
    LEFT JOIN exams e ON ea.exam_id = e.id
    LEFT JOIN courses c ON e.course_id = c.id
    WHERE ea.student_id = ? AND ea.status IN ('completed', 'graded', 'submitted')
    ORDER BY ea.completed_at DESC 
    LIMIT 50
");
$stmt->execute([$studentId]);
$gradeHistory = $stmt->fetchAll(PDO::FETCH_ASSOC);


// Achievement timeline - Fallback if table missing
$achievementTimeline = [];
try {
    $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);
} catch (PDOException $e) {
    // Generate synthetic achievements from real data
    $achievements = [];
    if (count($gradeHistory) > 0) {
        $achievements[] = [
            'action_description' => 'Completed first exam',
            'created_at' => $gradeHistory[0]['completed_at'],
            'metadata' => json_encode(['exam' => $gradeHistory[0]['exam_title']])
        ];
    }
    if ($completedCourses > 0) {
        $achievements[] = [
            'action_description' => 'Completed course',
            'created_at' => date('Y-m-d H:i:s', strtotime('-1 month')),
            'metadata' => '{}'
        ];
    }
    $achievementTimeline = $achievements;
}


// 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 - Enhanced with fallbacks
// Progress trend (30 days)
$progressTrend = [];
try {
    $stmt = $db->prepare("
        SELECT DATE(clp.last_accessed) as date, AVG(COALESCE(clp.progress_percentage, 0)) 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 ASC
    ");
    $stmt->execute([$studentId]);
    $progressTrend = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $progressTrend = array_fill(0, 7, ['date' => date('Y-m-d'), 'avg_progress' => 0]);
}

// Grade history chart (recent 20)
$gradeHistoryChart = [];
try {
    $stmt = $db->prepare("
        SELECT DATE(ea.completed_at) as date, ea.percentage as grade, COALESCE(e.title, 'Exam') as exam_title
        FROM exam_attempts ea 
        LEFT JOIN exams e ON ea.exam_id = e.id
        WHERE ea.student_id = ? AND ea.status IN ('completed','graded','submitted')
        ORDER BY ea.completed_at DESC LIMIT 20
    ");
    $stmt->execute([$studentId]);
    $gradeHistoryChart = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {}

// ============================================
// GRADING REPORT CARD DATA
// ============================================

// Get grade scale from database
$gradeScale = [];
try {
    $stmt = $db->query("SELECT grade_letter, grade_points, min_percentage, max_percentage FROM grade_scale WHERE is_active = 1 ORDER BY min_percentage DESC");
    $gradeScale = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    // Default grade scale if table doesn't exist or has issues
    $gradeScale = [
        ['grade_letter' => 'A', 'grade_points' => 4.00, 'min_percentage' => 90],
        ['grade_letter' => 'B', 'grade_points' => 3.00, 'min_percentage' => 80],
        ['grade_letter' => 'C', 'grade_points' => 2.00, 'min_percentage' => 70],
        ['grade_letter' => 'D', 'grade_points' => 1.00, 'min_percentage' => 60],
        ['grade_letter' => 'F', 'grade_points' => 0.00, 'min_percentage' => 0]
    ];
}

// Function to convert percentage to letter grade and grade points
function getGradeInfo($percentage, $gradeScale) {
    if ($percentage === null || $percentage === '') {
        return ['grade_letter' => '-', 'grade_points' => 0, 'percentage' => 0];
    }
    $percentage = floatval($percentage);
    foreach ($gradeScale as $grade) {
        if ($percentage >= $grade['min_percentage']) {
            return [
                'grade_letter' => $grade['grade_letter'],
                'grade_points' => floatval($grade['grade_points']),
                'percentage' => $percentage
            ];
        }
    }
    return ['grade_letter' => 'F', 'grade_points' => 0.00, 'percentage' => $percentage];
}

// Fetch grading report card data - courses with exams and grades
$stmt = $db->prepare("
    SELECT 
        c.id as course_id,
        c.title as course_name,
        COALESCE(c.credit_hours, 3.0) as credit_hours,
        COALESCE(e.title, 'Final Exam') as exam_name,
        ea.percentage,
        ea.score,
        ea.max_score,
        ea.grade as letter_grade,
        ea.completed_at,
        CASE WHEN ea.status IN ('completed', 'graded', 'submitted') AND ea.percentage IS NOT NULL THEN 1 ELSE 0 END as has_grade
    FROM course_enrollments ce
    JOIN courses c ON ce.course_id = c.id
    LEFT JOIN exams e ON e.course_id = c.id
    LEFT JOIN exam_attempts ea ON ea.exam_id = e.id AND ea.student_id = ce.student_id 
        AND ea.status IN ('completed', 'graded', 'submitted')
    WHERE ce.student_id = ?
    ORDER BY c.title, ea.completed_at DESC
");
$stmt->execute([$studentId]);
$rawGrades = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Process grades and deduplicate by course (take best/latest grade)
$coursesGrades = [];
foreach ($rawGrades as $grade) {
    $courseId = $grade['course_id'];
    if (!isset($coursesGrades[$courseId])) {
        $coursesGrades[$courseId] = $grade;
    } elseif ($grade['has_grade'] && (!$coursesGrades[$courseId]['has_grade'] || $grade['percentage'] > $coursesGrades[$courseId]['percentage'])) {
        $coursesGrades[$courseId] = $grade;
    }
}

// Calculate GPA
$totalQualityPoints = 0;
$totalCreditHours = 0;
$gradedCourses = [];

foreach ($coursesGrades as $courseId => $grade) {
    if ($grade['has_grade'] && $grade['percentage'] !== null) {
        $gradeInfo = getGradeInfo($grade['percentage'], $gradeScale);
        $creditHours = floatval($grade['credit_hours']);
        $qualityPoints = $gradeInfo['grade_points'] * $creditHours;
        
        $totalQualityPoints += $qualityPoints;
        $totalCreditHours += $creditHours;
        
        $gradedCourses[] = [
            'course_id' => $courseId,
            'course_name' => $grade['course_name'],
            'credit_hours' => $creditHours,
            'exam_name' => $grade['exam_name'],
            'percentage' => $grade['percentage'],
            'letter_grade' => $gradeInfo['grade_letter'],
            'grade_points' => $gradeInfo['grade_points'],
            'quality_points' => $qualityPoints,
            'completed_at' => $grade['completed_at']
        ];
    }
}

$gpa = $totalCreditHours > 0 ? round($totalQualityPoints / $totalCreditHours, 2) : 0;

$gradingReport = [
    'courses' => $gradedCourses,
    'gpa' => $gpa,
    'total_credits' => $totalCreditHours,
    'total_courses' => count($gradedCourses),
    'cumulative_quality_points' => round($totalQualityPoints, 2)
];

$courseCompletion = $courseProgress; // Reuse

// Upcoming deadlines fallback
$upcomingDeadlines = [];
try {
    $stmt = $db->prepare("
        SELECT e.title, e.end_date, COALESCE(c.title, 'General') as course_title
        FROM exams e
        LEFT JOIN courses c ON e.course_id = c.id
        WHERE e.end_date > NOW() AND e.status = 'published'
        ORDER BY e.end_date ASC LIMIT 5
    ");
    $stmt->execute([$studentId]);
    $upcomingDeadlines = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {}

// Prepare data for JavaScript
$reportData = [
    'overview' => $overview,
    'course_progress' => $courseProgress,
    'grade_history' => $gradeHistory,
    'achievement_timeline' => $achievementTimeline,
    'upcoming_deadlines' => $upcomingDeadlines,
    'grading_report' => $gradingReport,
    'charts' => [
        'progress_trend' => $progressTrend,
        'grade_history' => array_reverse($gradeHistoryChart), // Chronological
        '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 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-1 gap-8 mb-10">
                    <!-- 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="award" class="w-5 h-5 mr-2 text-green-500"></i>
                            Recent Grades
                        </h3>
                        <div id="grade-history" class="space-y-4 max-h-80 overflow-y-auto">
                            <?php if (count($gradeHistory) > 0): ?>
                                <?php foreach ($gradeHistory as $grade): ?>
                                    <div class="bg-gray-50 p-4 rounded-lg">
                                        <div class="flex justify-between items-start">
                                            <div>
                                                <h5 class="font-semibold text-gray-800"><?php echo htmlspecialchars($grade['exam_title']); ?></h5>
                                                <p class="text-sm text-gray-500"><?php echo htmlspecialchars($grade['course_title']); ?></p>
                                            </div>
                                            <div class="text-right">
                                                <span class="text-2xl font-bold <?php echo $grade['percentage'] >= 60 ? 'text-green-600' : 'text-red-600'; ?>">
                                                    <?php echo number_format($grade['percentage'], 1); ?>%
                                                </span>
                                                <p class="text-xs text-gray-500"><?php echo $grade['attempt_number'] ?? 1; ?> attempt(s)</p>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <div class="text-center py-8">
                                    <i data-lucide="award" class="w-12 h-12 text-gray-300 mx-auto mb-3"></i>
                                    <p class="text-gray-500">No grades available yet.</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- Grading Report Card Section -->
                <div class="bg-white p-6 rounded-xl shadow-lg mb-10">
                    <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-indigo-500"></i>
                        Grading Report Card
                    </h3>
                    
                    <!-- GPA Summary -->
                    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
                        <div class="bg-gradient-to-br from-indigo-500 to-indigo-600 p-4 rounded-lg text-white">
                            <p class="text-sm opacity-90">Current GPA</p>
                            <p class="text-3xl font-bold"><?php echo number_format($gradingReport['gpa'], 2); ?></p>
                            <p class="text-xs opacity-75">out of 4.00</p>
                        </div>
                        <div class="bg-gradient-to-br from-green-500 to-green-600 p-4 rounded-lg text-white">
                            <p class="text-sm opacity-90">Total Credits</p>
                            <p class="text-3xl font-bold"><?php echo number_format($gradingReport['total_credits'], 1); ?></p>
                            <p class="text-xs opacity-75">credit hours</p>
                        </div>
                        <div class="bg-gradient-to-br from-blue-500 to-blue-600 p-4 rounded-lg text-white">
                            <p class="text-sm opacity-90">Graded Courses</p>
                            <p class="text-3xl font-bold"><?php echo $gradingReport['total_courses']; ?></p>
                            <p class="text-xs opacity-75">courses completed</p>
                        </div>
                        <div class="bg-gradient-to-br from-purple-500 to-purple-600 p-4 rounded-lg text-white">
                            <p class="text-sm opacity-90">Quality Points</p>
                            <p class="text-3xl font-bold"><?php echo number_format($gradingReport['cumulative_quality_points'], 2); ?></p>
                            <p class="text-xs opacity-75">cumulative</p>
                        </div>
                    </div>

                    <!-- Grades Table -->
                    <div class="overflow-x-auto">
                        <table class="w-full text-sm text-left">
                            <thead class="text-xs text-gray-700 uppercase bg-gray-100">
                                <tr>
                                    <th class="px-4 py-3 rounded-tl-lg">Course</th>
                                    <th class="px-4 py-3">Credit Hours</th>
                                    <th class="px-4 py-3">Exam</th>
                                    <th class="px-4 py-3">Percentage</th>
                                    <th class="px-4 py-3">Grade</th>
                                    <th class="px-4 py-3">Grade Points</th>
                                    <th class="px-4 py-3 rounded-tr-lg">Quality Points</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (count($gradingReport['courses']) > 0): ?>
                                    <?php foreach ($gradingReport['courses'] as $course): ?>
                                        <tr class="border-b hover:bg-gray-50">
                                            <td class="px-4 py-3 font-medium text-gray-900">
                                                <?php echo htmlspecialchars($course['course_name']); ?>
                                            </td>
                                            <td class="px-4 py-3 text-gray-600">
                                                <?php echo number_format($course['credit_hours'], 1); ?>
                                            </td>
                                            <td class="px-4 py-3 text-gray-600">
                                                <?php echo htmlspecialchars($course['exam_name']); ?>
                                            </td>
                                            <td class="px-4 py-3">
                                                <span class="font-medium <?php echo $course['percentage'] >= 60 ? 'text-green-600' : 'text-red-600'; ?>">
                                                    <?php echo number_format($course['percentage'], 1); ?>%
                                                </span>
                                            </td>
                                            <td class="px-4 py-3">
                                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium
                                                    <?php
                                                    $gradeClass = 'bg-gray-100 text-gray-800';
                                                    if (in_array($course['letter_grade'], ['A', 'A+'])) $gradeClass = 'bg-green-100 text-green-800';
                                                    elseif (in_array($course['letter_grade'], ['A-', 'B+', 'B'])) $gradeClass = 'bg-blue-100 text-blue-800';
                                                    elseif (in_array($course['letter_grade'], ['B-', 'C+', 'C'])) $gradeClass = 'bg-yellow-100 text-yellow-800';
                                                    elseif (in_array($course['letter_grade'], ['C-', 'D+', 'D'])) $gradeClass = 'bg-orange-100 text-orange-800';
                                                    elseif ($course['letter_grade'] === 'F') $gradeClass = 'bg-red-100 text-red-800';
                                                    echo $gradeClass;
                                                    ?>">
                                                    <?php echo htmlspecialchars($course['letter_grade']); ?>
                                                </span>
                                            </td>
                                            <td class="px-4 py-3 text-gray-600">
                                                <?php echo number_format($course['grade_points'], 2); ?>
                                            </td>
                                            <td class="px-4 py-3 font-medium text-gray-900">
                                                <?php echo number_format($course['quality_points'], 2); ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                    <!-- Summary Row -->
                                    <tr class="bg-gray-100 font-semibold">
                                        <td class="px-4 py-3 rounded-bl-lg">TOTAL</td>
                                        <td class="px-4 py-3"><?php echo number_format($gradingReport['total_credits'], 1); ?></td>
                                        <td class="px-4 py-3"></td>
                                        <td class="px-4 py-3"></td>
                                        <td class="px-4 py-3"></td>
                                        <td class="px-4 py-3">GPA: <?php echo number_format($gradingReport['gpa'], 2); ?></td>
                                        <td class="px-4 py-3 rounded-br-lg"><?php echo number_format($gradingReport['cumulative_quality_points'], 2); ?></td>
                                    </tr>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="7" class="px-4 py-8 text-center text-gray-500">
                                            <i data-lucide="graduation-cap" class="w-12 h-12 text-gray-300 mx-auto mb-3"></i>
                                            <p>No graded courses yet. Complete exams to see your grades here.</p>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- Grade Scale Reference -->
                    <div class="mt-6 p-4 bg-gray-50 rounded-lg">
                        <h4 class="text-sm font-semibold text-gray-700 mb-3">Grade Scale Reference</h4>
                        <div class="flex flex-wrap gap-2">
                            <span class="inline-flex items-center px-2 py-1 rounded text-xs font-medium bg-green-100 text-green-800">A (90-100%): 4.00</span>
                            <span class="inline-flex items-center px-2 py-1 rounded text-xs font-medium bg-blue-100 text-blue-800">B (80-89%): 3.00</span>
                            <span class="inline-flex items-center px-2 py-1 rounded text-xs font-medium bg-yellow-100 text-yellow-800">C (70-79%): 2.00</span>
                            <span class="inline-flex items-center px-2 py-1 rounded text-xs font-medium bg-orange-100 text-orange-800">D (60-69%): 1.00</span>
                            <span class="inline-flex items-center px-2 py-1 rounded text-xs font-medium bg-red-100 text-red-800">F (0-59%): 0.00</span>
                        </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('grades_card')" class="flex items-center gap-3 bg-indigo-600 text-white px-6 py-3 rounded-lg font-semibold hover:bg-indigo-700 transition duration-200">
                            <i data-lucide="graduation-cap" class="w-5 h-5"></i>
                            Report Card
                        </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 courseCompletionChart;

document.addEventListener('DOMContentLoaded', function() {
    // Skip Lucide icons (not loaded) - use emoji/HTML icons


    // 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);
    populateCourseFilter(window.currentData.course_progress);

    initializeCharts();
});

// Disabled filters - uses server-side data only (API not implemented)
function loadStudentReports(courseId = '', dateFrom = '', dateTo = '') {
    showToast('Filters applied using current data (API coming soon)', 'success');
    // Uses window.currentData - no API call needed
}

function applyFilters() {
    showToast('Filters will refresh data when API is available', 'info');
}


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() {
    // Course Completion Chart - Dynamic from data
    const courseCompletionCtx = document.getElementById('course-completion-chart').getContext('2d');
    const courses = window.currentData.charts.course_completion || [];
    const completed = courses.filter(c => (c.progress || 0) >= 100).length;
    const inProgress = courses.filter(c => (c.progress || 0) > 0 && (c.progress || 0) < 100).length;
    const notStarted = courses.filter(c => (c.progress || 0) === 0).length;
    courseCompletionChart = new Chart(courseCompletionCtx, {
        type: 'doughnut',
        data: {
            labels: ['Completed', 'In Progress', 'Not Started'],
            datasets: [{
                data: [completed, inProgress, notStarted],
                backgroundColor: ['#28a745', '#ffc107', '#dc3545'],
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            plugins: { legend: { position: 'bottom' } }
        }
    });
}


function updateCharts(data) {
    // 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 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 === 'grades_card') {
        // Export grading report card
        if (window.currentData.grading_report && window.currentData.grading_report.courses) {
            exportToCSV(window.currentData.grading_report.courses, 'grading_report_card');
        } else {
            showToast('No grading report data available', 'error');
            return;
        }
    } 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>