<?php
require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../config/currency.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();
$db = getDB();
$userId = $_SESSION['user_id'];

// Get enrolled courses with progress
$stmt = $db->prepare("
    SELECT c.*, ce.enrollment_date, ce.progress_percentage, ce.status as enrollment_status,
           ce.completion_date, cat.name as category_name,
           COUNT(DISTINCT cl.id) as total_lessons,
           COUNT(DISTINCT clp.id) as completed_lessons,
           CASE
               WHEN ce.progress_percentage >= 100 THEN 'completed'
               WHEN COUNT(DISTINCT clp.id) = COUNT(DISTINCT cl.id) AND COUNT(DISTINCT cl.id) > 0 THEN 'completed'
               ELSE 'in_progress'
           END as calculated_status
    FROM course_enrollments ce
    JOIN courses c ON ce.course_id = c.id
    LEFT JOIN course_categories cat ON c.category_id = cat.id
    LEFT JOIN course_lessons cl ON c.id = cl.course_id
    LEFT JOIN course_lesson_progress clp ON cl.id = clp.lesson_id AND clp.enrollment_id = ce.id AND clp.status = 'completed'
    WHERE ce.student_id = ?
    GROUP BY ce.id, c.id
    ORDER BY ce.enrollment_date DESC
    LIMIT 6
");
$stmt->execute([$userId]);
$enrolledCourses = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Update enrollment status if calculated status differs from stored status
foreach ($enrolledCourses as $course) {
    $calculatedStatus = $course['calculated_status'];
    $storedStatus = $course['enrollment_status'];

    if ($calculatedStatus !== $storedStatus) {
        $updateStmt = $db->prepare("
            UPDATE course_enrollments
            SET status = ?, completion_date = ?
            WHERE student_id = ? AND course_id = ?
        ");
        $completionDate = ($calculatedStatus === 'completed') ? date('Y-m-d H:i:s') : null;
        $updateStmt->execute([$calculatedStatus, $completionDate, $userId, $course['id']]);
    }
}

// Get total statistics
$stmt = $db->prepare("
    SELECT
        COUNT(ce.id) as total_enrolled,
        COUNT(CASE WHEN ce.status = 'completed' THEN 1 END) as total_completed,
        AVG(ce.progress_percentage) as avg_progress,
        COUNT(CASE WHEN ce.status = 'in_progress' THEN 1 END) as in_progress
    FROM course_enrollments ce
    WHERE ce.student_id = ?
");
$stmt->execute([$userId]);
$stats = $stmt->fetch(PDO::FETCH_ASSOC);

// Get upcoming exams
$stmt = $db->prepare("
    SELECT e.*, c.title as course_title, ce.progress_percentage
    FROM exams e
    JOIN courses c ON e.course_id = c.id
    JOIN course_enrollments ce ON c.id = ce.course_id AND ce.student_id = ?
    LEFT JOIN exam_attempts ea ON e.id = ea.exam_id AND ea.student_id = ?
    WHERE e.status = 'published'
    AND (e.start_date IS NULL OR e.start_date <= NOW())
    AND (e.end_date IS NULL OR e.end_date >= NOW())
    AND (ea.id IS NULL OR ea.status != 'passed')
    GROUP BY e.id
    ORDER BY e.end_date ASC
    LIMIT 3
");
$stmt->execute([$userId, $userId]);
$upcomingExams = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get recent grades/quiz results
$stmt = $db->prepare("
    SELECT ea.*, e.title as exam_title, c.title as course_title,
           CASE
               WHEN ea.score >= e.passing_score THEN 'passed'
               ELSE 'failed'
           END as result_status
    FROM exam_attempts ea
    JOIN exams e ON ea.exam_id = e.id
    JOIN courses c ON e.course_id = c.id
    WHERE ea.student_id = ? AND ea.status = 'graded'
    ORDER BY ea.completed_at DESC
    LIMIT 5
");
$stmt->execute([$userId]);
$recentGrades = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get achievements
$stmt = $db->prepare("
    SELECT * FROM user_achievements
    WHERE user_id = ?
    ORDER BY earned_at DESC
    LIMIT 6
");
$stmt->execute([$userId]);
$achievements = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get study streak (consecutive days with activity)
$stmt = $db->prepare("
    SELECT COUNT(DISTINCT DATE(created_at)) as streak_days
    FROM user_activities
    WHERE user_id = ? AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    AND action_type IN ('lesson_completed', 'exam_attempted', 'course_enrolled')
");
$stmt->execute([$userId]);
$streakData = $stmt->fetch(PDO::FETCH_ASSOC);
$studyStreak = $streakData['streak_days'] ?? 0;

// Get recent activity
$stmt = $db->prepare("
    SELECT ua.*, c.title as course_title
    FROM user_activities ua
    LEFT JOIN courses c ON ua.action_type LIKE '%course%' AND ua.action_description LIKE CONCAT('%', c.id, '%')
    WHERE ua.user_id = ?
    ORDER BY ua.created_at DESC
    LIMIT 5
");
$stmt->execute([$userId]);
$recentActivities = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get notifications/alerts (placeholder)
$notifications = [];

// Get study goals (placeholder)
$studyGoals = [
    ['title' => 'Complete 2 courses this month', 'progress' => 50, 'target' => 2, 'current' => 1],
    ['title' => 'Study 10 hours per week', 'progress' => 75, 'target' => 40, 'current' => 30],
    ['title' => 'Score above 80% on exams', 'progress' => 90, 'target' => 80, 'current' => 85]
];

// Get learning recommendations
$stmt = $db->prepare("
    SELECT c.*, cat.name as category_name, AVG(cr.rating) as avg_rating
    FROM courses c
    LEFT JOIN course_categories cat ON c.category_id = cat.id
    LEFT JOIN course_reviews cr ON c.id = cr.course_id AND cr.status = 'approved'
    WHERE c.status = 'published'
    AND c.id NOT IN (
        SELECT course_id FROM course_enrollments WHERE student_id = ?
    )
    GROUP BY c.id
    ORDER BY c.created_at DESC
    LIMIT 3
");
$stmt->execute([$userId]);
$recommendedCourses = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Calculate overdue assignments (simplified)
$overdueCount = count(array_filter($upcomingExams, function($exam) {
    return $exam['end_date'] && strtotime($exam['end_date']) < time();
}));


// Get available courses for continue learning section (similar to homepage)
$query = "SELECT c.id, c.title, c.slug, c.description, c.short_description, c.thumbnail, c.banner_image,
                  c.price, c.currency, c.level, c.duration_hours, c.language, c.max_students, c.prerequisites,
                  c.learning_objectives, c.tags, c.status, c.is_featured, c.is_free, c.created_at, c.updated_at,
                  c.instructor_id, c.category_id,
                  cat.name as category_name, cat.icon as category_icon, cat.color as category_color,
                  u.username as instructor_name, up.first_name, up.last_name,
                  COALESCE(stats.enrollment_count, 0) as enrollment_count,
                  stats.average_rating,
                  COALESCE(stats.review_count, 0) as review_count
           FROM courses c
           LEFT JOIN course_categories cat ON c.category_id = cat.id
           LEFT JOIN users u ON c.instructor_id = u.id
           LEFT JOIN user_profiles up ON u.id = up.user_id
           LEFT JOIN (
               SELECT c2.id as course_id,
                      COUNT(DISTINCT ce.id) as enrollment_count,
                      AVG(cr.rating) as average_rating,
                      COUNT(DISTINCT cr.id) as review_count
               FROM courses c2
               LEFT JOIN course_enrollments ce ON c2.id = ce.course_id AND ce.status = 'completed'
               LEFT JOIN course_reviews cr ON c2.id = cr.course_id AND cr.status = 'approved'
               GROUP BY c2.id
           ) stats ON c.id = stats.course_id
           WHERE c.status = 'published' AND (cat.is_active = 1 OR cat.id IS NULL)
           ORDER BY c.is_featured DESC, c.created_at DESC";

$availableCourses = $db->query($query)->fetchAll();

// Get enrollment status for logged-in users
$enrolledCoursesIds = [];
if (isLoggedIn()) {
    $stmt = $db->prepare("SELECT course_id, status FROM course_enrollments WHERE student_id = ?");
    $stmt->execute([$userId]);
    $enrolledCoursesIds = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
}

// Get available exams for enrollment (not from enrolled courses)
$query = "SELECT e.id, e.title, e.slug, e.description, e.price, e.currency, e.is_free,
                 e.exam_type, e.total_points, e.passing_score, e.time_limit, e.max_attempts,
                 e.status, e.created_at,
                 c.title as course_title,
                 u.username as instructor_name, up.first_name, up.last_name,
                 COALESCE(stats.attempt_count, 0) as attempt_count
          FROM exams e
          LEFT JOIN courses c ON e.course_id = c.id
          LEFT JOIN users u ON e.instructor_id = u.id
          LEFT JOIN user_profiles up ON u.id = up.user_id
          LEFT JOIN (
              SELECT e2.id as exam_id,
                     COUNT(DISTINCT ea.student_id) as attempt_count
              FROM exams e2
              LEFT JOIN exam_attempts ea ON e2.id = ea.exam_id
              GROUP BY e2.id
          ) stats ON e.id = stats.exam_id
          WHERE e.status = 'published'
          AND (e.start_date IS NULL OR e.start_date <= NOW())
          AND (e.end_date IS NULL OR e.end_date >= NOW())
          ORDER BY e.created_at DESC
          LIMIT 6";

$availableExams = $db->query($query)->fetchAll();

// For exams, we don't need enrollment status since students can attempt exams directly
// The cart/checkout system handles exam access
$enrolledExamIds = [];
?>

<!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($user['username'] ?? 'Student'); ?>'s Dashboard | Mutalex Academy</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;
        }

        /* Available Courses Section */
        .available-courses-section {
            padding: 4rem 0;
            background: #f8fafc;
        }

        .courses-header {
            text-align: center;
            margin-bottom: 3rem;
        }

        .courses-title {
            font-size: 2.8rem;
            font-weight: 800;
            color: #1f2937;
            margin-bottom: 1rem;
            letter-spacing: -0.02em;
            line-height: 1.2;
        }

        .courses-subtitle {
            color: #6b7280;
            font-size: 1.1rem;
            margin-bottom: 2rem;
            max-width: 600px;
            margin-left: auto;
            margin-right: auto;
        }

        .view-all-courses {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            color: #3b82f6;
            text-decoration: none;
            font-weight: 600;
            font-size: 1rem;
            transition: color 0.3s ease;
        }

        .view-all-courses:hover {
            color: #2563eb;
        }

        /* Course Grid */
        .courses-grid {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 1.4rem;
            margin-bottom: 3rem;
        }

        .course-card {
            background: white;
            border-radius: 16px;
            overflow: hidden;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            border: 1px solid #e1e5e9;
            animation: cardFadeIn 0.6s ease-out both;
            animation-delay: calc(var(--card-index, 0) * 0.1s);
            transform: scale(1.2);
            transform-origin: center;
        }

        .course-card:hover {
            transform: translateY(-12px) scale(1.02);
            box-shadow: 0 25px 50px rgba(0, 0, 0, 0.15);
            border-color: #e5e7eb;
        }

        @keyframes cardFadeIn {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .course-image-container {
            position: relative;
            height: 80px;
            overflow: hidden;
        }

        .course-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.3s ease;
        }

        .course-card:hover .course-image {
            transform: scale(1.05);
        }

        .course-image-placeholder {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 3rem;
            background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
        }

        .course-badges {
            position: absolute;
            top: 12px;
            left: 12px;
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }

        .badge {
            padding: 0.375rem 0.75rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .badge-featured {
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
            color: white;
        }

        .badge-free {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
        }

        .course-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(59, 130, 246, 0.9);
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .course-card:hover .course-overlay {
            opacity: 1;
        }

        .course-link {
            color: white;
            text-decoration: none;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.75rem 1.5rem;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 8px;
            backdrop-filter: blur(10px);
            transition: background 0.3s ease;
        }

        .course-link:hover {
            background: rgba(255, 255, 255, 0.3);
        }

        /* Course Content */
        .course-content {
            padding: 0.5rem;
        }

        .course-category {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            background: #f3f4f6;
            color: #6b7280;
            padding: 0.25rem 0.75rem;
            border-radius: 12px;
            font-size: 0.6rem;
            font-weight: 500;
            margin-bottom: 0.5rem;
        }

        .course-title {
            font-size: 0.8rem;
            font-weight: 700;
            color: #1f2937;
            margin-bottom: 0.5rem;
            line-height: 1.2;
            letter-spacing: -0.01em;
        }

        .course-title a {
            color: inherit;
            text-decoration: none;
        }

        .course-title a:hover {
            color: #3b82f6;
        }

        .course-description {
            color: #6b7280;
            font-size: 0.7rem;
            line-height: 1.4;
            margin-bottom: 0.5rem;
            font-weight: 400;
        }

        .course-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 0.5rem;
        }

        .instructor-info {
            display: flex;
            align-items: center;
            gap: 0.25rem;
            color: #6b7280;
            font-size: 0.6rem;
        }

        .course-rating {
            display: flex;
            align-items: center;
            gap: 0.25rem;
            font-size: 0.6rem;
        }

        .rating-stars {
            display: flex;
            gap: 0.125rem;
        }

        .rating-stars .fa-star {
            color: #d1d5db;
        }

        .rating-stars .fa-star.filled {
            color: #f59e0b;
        }

        .rating-score {
            font-weight: 600;
            color: #1f2937;
        }

        .rating-count {
            color: #6b7280;
        }

        .no-rating {
            color: #6b7280;
            font-style: italic;
        }

        /* Course Footer */
        .course-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
        }

        .course-stats {
            display: flex;
            gap: 1rem;
        }

        .stat {
            display: flex;
            align-items: center;
            gap: 0.25rem;
            color: #6b7280;
            font-size: 0.6rem;
        }

        .course-price .price-free {
            font-size: 1.5rem;
            font-weight: 700;
            color: #10b981;
        }

        .course-price .price-amount {
            font-size: 1.5rem;
            font-weight: 700;
            color: #1e40af;
        }

        /* Course Actions */
        .course-actions {
            margin-top: 1rem;
        }

        .course-actions .btn {
            width: 100%;
            padding: 0.5rem 0.75rem;
            border-radius: 6px;
            font-weight: 600;
            font-size: 0.65rem;
            text-transform: none;
            transition: all 0.3s ease;
        }

        .course-actions .btn-primary {
            background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
            border: none;
        }

        .course-actions .btn-success {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            border: none;
        }

        .course-actions .btn-outline-primary {
            border: 2px solid #3b82f6;
            color: #3b82f6;
        }

        .course-actions .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
        }

        /* Empty State */
        .empty-courses {
            text-align: center;
            padding: 5rem 2rem;
            animation: fadeInUp 0.6s ease-out;
        }

        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .empty-courses-content {
            max-width: 450px;
            margin: 0 auto;
        }

        .empty-icon {
            font-size: 4.5rem;
            color: #d1d5db;
            margin-bottom: 1.5rem;
            opacity: 0.7;
        }

        .empty-courses h3 {
            font-size: 1.6rem;
            font-weight: 700;
            color: #1f2937;
            margin-bottom: 0.75rem;
            letter-spacing: -0.01em;
        }

        .empty-courses p {
            color: #6b7280;
            margin-bottom: 2.5rem;
            font-size: 1.1rem;
            line-height: 1.6;
        }

        /* Dashboard Calendar Widget */
        .calendar-widget {
            max-width: 280px;
            margin: 0 auto;
        }

        .calendar-widget .grid {
            font-size: 0.75rem;
        }

        /* Responsive Design */
        @media (max-width: 1024px) {
            .courses-grid {
                grid-template-columns: repeat(3, 1fr);
                gap: 1rem;
            }
            .course-card {
                transform: scale(1);
            }
        }

        @media (max-width: 768px) {
            .available-courses-section {
                padding: 2rem 0;
            }

            .courses-title {
                font-size: 1.8rem;
            }

            .courses-grid {
                grid-template-columns: repeat(2, 1fr);
                gap: 0.75rem;
            }

            .course-card {
                border-radius: 8px;
                transform: scale(1);
            }

            .course-image-container {
                height: 60px;
            }

            .course-content {
                padding: 0.3rem;
            }

            .course-footer {
                flex-direction: column;
                gap: 0.5rem;
                align-items: flex-start;
                margin-bottom: 0.5rem;
            }

            .course-stats {
                flex-wrap: wrap;
                width: 100%;
            }

            .course-actions {
                width: 100%;
            }

            .course-actions .btn {
                width: 100%;
                justify-content: center;
                font-size: 0.65rem;
                padding: 0.5rem 0.7rem;
            }
        }

        @media (max-width: 480px) {
            .available-courses-section {
                padding: 1.5rem 0;
            }

            .courses-title {
                font-size: 1.5rem;
            }

            .courses-grid {
                grid-template-columns: repeat(1, 1fr);
                gap: 0.5rem;
            }

            .course-card {
                transform: scale(1);
            }

            .course-image-container {
                height: 50px;
            }

            .course-title {
                font-size: 0.7rem;
            }

            .course-description {
                font-size: 0.6rem;
            }
        }
    </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">Student Dashboard</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 bg-primary-blue text-white font-semibold transition duration-150 shadow-md">
                        <!-- 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 text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- 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 bg-primary-blue text-white font-semibold">🏠 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 text-text-dark hover:bg-accent-subtle">✅ 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>

            <!-- Dashboard Content Grid -->
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 lg:py-12 grid grid-cols-1 lg:grid-cols-3 gap-8">

                <!-- Column 1 & 2: Main Focus -->
                <section class="lg:col-span-2 space-y-8">

                    <!-- Welcome Banner -->
                    <div class="bg-white p-6 sm:p-8 rounded-xl shadow-lg border border-accent-subtle">
                        <h2 class="text-3xl font-bold text-primary-blue mb-2">Welcome, <?php echo htmlspecialchars($user['username'] ?? 'Student'); ?>.</h2>
                        <p class="text-gray-600">You have <strong><?php echo $overdueCount; ?></strong> overdue tasks. Time to focus on your learning journey.</p>
                    </div>

                    <!-- Cart Checkout Section -->
                    <?php
                    // Get cart contents directly from database (avoid file_get_contents which doesn't pass auth)
                    $cartStmt = $db->prepare("
                        SELECT ci.*,
                               COALESCE(c.title, e.title) as title,
                               COALESCE(c.price, e.price) as price,
                               COALESCE(c.currency, e.currency) as currency,
                               COALESCE(c.is_free, e.is_free) as is_free,
                               COALESCE(c.thumbnail, NULL) as thumbnail,
                               COALESCE(c.max_students, NULL) as max_students,
                               ci.item_type
                        FROM cart_items ci
                        LEFT JOIN courses c ON ci.item_id = c.id AND ci.item_type = 'course'
                        LEFT JOIN exams e ON ci.item_id = e.id AND ci.item_type = 'exam'
                        WHERE ci.user_id = ?
                        ORDER BY ci.created_at ASC
                    ");
                    $cartStmt->execute([$userId]);
                    $cartItems = $cartStmt->fetchAll(PDO::FETCH_ASSOC);
                    
                    $cartTotal = 0.00;
                    $cartCurrency = 'USD';
                    foreach ($cartItems as $cartItem) {
                        if (!$cartItem['is_free']) {
                            $cartTotal += floatval($cartItem['price']);
                            $cartCurrency = $cartItem['currency'];
                        }
                    }
                    $cart = ['items' => $cartItems, 'total' => $cartTotal, 'currency' => $cartCurrency];
                    if (!empty($cart['items'])): ?>
                    <div class="bg-gradient-to-br from-blue-50 to-indigo-50 p-6 rounded-xl shadow-lg border border-blue-200">
                        <div class="flex items-start justify-between mb-4">
                            <div>
                                <h2 class="text-xl font-semibold mb-2 text-text-dark flex items-center">
                                    <i class="fas fa-shopping-cart mr-2 text-primary-blue"></i>Shopping Cart
                                </h2>
                                <p class="text-sm text-gray-600">You have <strong><?php echo count($cart['items']); ?></strong> item(s) in your cart</p>
                            </div>
                            <span class="inline-flex items-center justify-center bg-primary-blue text-white rounded-full h-8 w-8 font-bold text-sm">
                                <?php echo count($cart['items']); ?>
                            </span>
                        </div>
                        
                        <div class="bg-white rounded-lg p-4 mb-4 max-h-[150px] overflow-y-auto">
                            <?php foreach ($cart['items'] as $item): ?>
                                <div class="flex items-center justify-between py-2 border-b last:border-b-0">
                                    <div class="flex-1">
                                        <h4 class="text-sm font-medium text-gray-800"><?php echo htmlspecialchars($item['title'] ?? ''); ?></h4>
                                        <p class="text-xs text-gray-500"><?php echo $item['is_free'] ? 'Free' : formatCurrency($item['price'] ?? 0, $item['currency'] ?? 'USD'); ?></p>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        
                        <div class="bg-white rounded-lg p-4 mb-4">
                            <div class="flex justify-between items-center">
                                <span class="font-medium text-gray-700">Total Amount:</span>
                                <span class="text-2xl font-bold text-primary-blue"><?php echo formatCurrency($cart['total'], $cart['currency']); ?></span>
                            </div>
                        </div>

                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                            <button onclick="showDashboardCheckoutModal()" class="w-full bg-primary-blue text-white py-3 px-4 rounded-lg font-semibold hover:bg-blue-800 transition duration-200 flex items-center justify-center">
                                <i class="fas fa-credit-card mr-2"></i>Proceed to Checkout
                            </button>
                            <button onclick="toggleAvailableCourses()" class="w-full bg-white text-primary-blue border-2 border-primary-blue py-3 px-4 rounded-lg font-semibold hover:bg-blue-50 transition duration-200 flex items-center justify-center">
                                <i class="fas fa-plus-circle mr-2"></i>Add More Courses
                            </button>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Quick Stats / Key Metrics -->
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
                        <!-- Stat Card 1 -->
                        <div class="bg-white p-6 rounded-xl shadow-lg border border-accent-subtle text-center">
                            <p class="text-4xl font-extrabold text-primary-blue"><?php echo $stats['total_enrolled'] ?? 0; ?></p>
                            <p class="text-sm font-medium text-gray-500 mt-1">Courses Enrolled</p>
                        </div>
                        <!-- Stat Card 2 -->
                        <div class="bg-white p-6 rounded-xl shadow-lg border border-accent-subtle text-center">
                            <p class="text-4xl font-extrabold text-red-600"><?php echo $overdueCount; ?></p>
                            <p class="text-sm font-medium text-gray-500 mt-1">Overdue Assignments</p>
                        </div>
                    </div>

                    <!-- Enrolled Courses (Primary Section) -->
                    <div>
                        <h2 class="text-2xl font-semibold mb-4 text-text-dark">Courses In Progress</h2>
                        <div class="space-y-4" id="enrolledCourses">
                            <?php if (!empty($enrolledCourses)): ?>
                                <?php foreach ($enrolledCourses as $course): ?>
                                    <div class="course-card bg-white p-6 rounded-xl shadow-lg border-l-4 border-primary-blue hover:shadow-xl transition duration-200 cursor-pointer" data-course-id="<?php echo $course['id']; ?>">
                                        <div class="flex justify-between items-start mb-2">
                                            <h3 class="text-lg font-bold"><?php echo htmlspecialchars($course['title']); ?></h3>
                                            <span class="text-xs font-semibold text-white bg-primary-blue px-3 py-1 rounded-full"><?php echo ucfirst(str_replace('_', ' ', $course['calculated_status'])); ?></span>
                                        </div>
                                        <p class="text-sm text-gray-600 mb-4">Category: <?php echo htmlspecialchars($course['category_name'] ?? 'General'); ?></p>

                                        <div class="w-full bg-accent-subtle rounded-full h-2.5">
                                            <div class="bg-primary-blue h-2.5 rounded-full" style="width: <?php echo $course['progress_percentage']; ?>%"></div>
                                        </div>
                                        <p class="text-right text-sm font-medium text-primary-blue mt-1"><?php echo round($course['progress_percentage']); ?>% Complete (<?php echo $course['completed_lessons']; ?>/<?php echo $course['total_lessons']; ?> Lessons)</p>

                                        <?php if ($course['calculated_status'] === 'completed'): ?>
                                            <div class="mt-4 pt-4 border-t border-gray-200">
                                                <button onclick="event.stopPropagation(); openReviewModal(<?php echo $course['id']; ?>, '<?php echo addslashes($course['title']); ?>')" class="w-full bg-yellow-500 hover:bg-yellow-600 text-white font-semibold py-2 px-4 rounded-lg transition duration-200 flex items-center justify-center">
                                                    <i class="fas fa-star mr-2"></i>Write a Review
                                                </button>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <div class="bg-white p-6 rounded-xl shadow-lg text-center">
                                    <p class="text-gray-600">No courses enrolled yet.</p>
                                    <a href="../courses/catalog.php" class="text-primary-blue hover:text-primary-blue/80">Browse Courses</a>
                                </div>
                            <?php endif; ?>
                        </div>
                        <button onclick="toggleAvailableCourses()" class="mt-4 block text-primary-blue hover:text-primary-blue/80 font-semibold text-center py-2 border-t border-accent-subtle bg-white rounded-b-xl w-full">View All Courses →</button>
                    </div>

                    <!-- Available Exams Toggle Button -->
                    <button onclick="toggleAvailableExams()" class="mt-4 block text-primary-blue hover:text-primary-blue/80 font-semibold text-center py-2 border-t border-accent-subtle bg-white rounded-b-xl w-full">View All Exams →</button>
                </section>

                <!-- Column 3: Secondary Information / Utility -->
                <aside class="lg:col-span-1 space-y-8">

                    <!-- Upcoming Assignments -->
                    <div class="bg-white p-6 rounded-xl shadow-lg border border-accent-subtle">
                        <h2 class="text-xl font-semibold mb-4 text-text-dark">Upcoming Deadlines</h2>
                        <ul class="space-y-4">
                            <?php if (!empty($upcomingExams)): ?>
                                <?php foreach ($upcomingExams as $exam): ?>
                                    <li class="border-l-4 <?php echo (strtotime($exam['end_date']) < time()) ? 'border-red-500' : 'border-primary-blue'; ?> pl-3">
                                        <p class="text-sm font-bold <?php echo (strtotime($exam['end_date']) < time()) ? 'text-red-600' : 'text-text-dark'; ?>"><?php echo htmlspecialchars($exam['title']); ?></p>
                                        <p class="text-xs text-gray-500"><?php echo htmlspecialchars($exam['course_title']); ?> | Due: <?php echo $exam['end_date'] ? date('M j', strtotime($exam['end_date'])) : 'No deadline'; ?></p>
                                    </li>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <li class="text-sm text-gray-500">No upcoming deadlines</li>
                            <?php endif; ?>
                        </ul>
                        <a href="calendar.php" class="mt-4 block text-sm text-primary-blue hover:text-primary-blue/80 font-medium">View Full Calendar</a>
                    </div>

                    <!-- Calendar Widget -->
                    <div class="bg-white p-6 rounded-xl shadow-lg border border-accent-subtle">
                        <h2 class="text-xl font-semibold mb-4 text-text-dark flex items-center justify-between">
                            <span>Calendar</span>
                            <a href="calendar.php" class="text-sm text-primary-blue hover:text-primary-blue/80 font-medium">View Full →</a>
                        </h2>

                        <!-- Mini Calendar Container -->
                        <div class="calendar-widget">
                            <div id="dashboard-calendar-container">
                                <!-- Calendar will be rendered here -->
                            </div>
                        </div>

                        <!-- Upcoming Events Summary -->
                        <div class="mt-4 pt-4 border-t border-accent-subtle">
                            <h3 class="text-sm font-semibold text-text-dark mb-2">Next 7 Days</h3>
                            <div id="dashboard-upcoming-events" class="space-y-2 max-h-32 overflow-y-auto">
                                <!-- Upcoming events will be loaded here -->
                            </div>
                        </div>
                    </div>

                    <!-- Quick Actions -->
                    <div class="bg-white p-6 rounded-xl shadow-lg border border-accent-subtle">
                        <h2 class="text-xl font-semibold mb-4 text-text-dark">Quick Actions</h2>
                        <div class="grid grid-cols-2 gap-3">
                            <button onclick="toggleAvailableExams()" class="flex flex-col items-center justify-center p-4 bg-accent-subtle rounded-lg hover:bg-gray-300 transition duration-150 text-text-dark text-sm font-medium">
                                <!-- Icon Placeholder: Exam -->
                                <span>📝</span>
                                <span class="mt-1">Browse Exams</span>
                            </button>
                            <a href="../courses/catalog.php" class="flex flex-col items-center justify-center p-4 bg-accent-subtle rounded-lg hover:bg-gray-300 transition duration-150 text-text-dark text-sm font-medium">
                                <!-- Icon Placeholder: Search -->
                                <span>🔍</span>
                                <span class="mt-1">Course Search</span>
                            </a>
                            <button class="flex flex-col items-center justify-center p-4 bg-accent-subtle rounded-lg hover:bg-gray-300 transition duration-150 text-text-dark text-sm font-medium">
                                <!-- Icon Placeholder: Help -->
                                <span>❓</span>
                                <span class="mt-1">Get Help</span>
                            </button>
                            <a href="../profile.php" class="flex flex-col items-center justify-center p-4 bg-accent-subtle rounded-lg hover:bg-gray-300 transition duration-150 text-text-dark text-sm font-medium">
                                <!-- Icon Placeholder: Settings -->
                                <span>⚙️</span>
                                <span class="mt-1">Settings</span>
                            </a>
                        </div>
                    </div>
                </aside>
            </div>

            <!-- Available Courses Section (Hidden by default) -->
            <section id="available-courses-section" class="available-courses-section" style="display: none;">
                <div class="container mx-auto px-4">
                    <div class="courses-header">
                        <h2 class="courses-title">Available Courses</h2>
                        <p class="courses-subtitle">Expand your knowledge with our expertly crafted courses</p>
                    </div>

                    <?php if (!empty($availableCourses)): ?>
                        <div class="courses-grid">
                            <?php foreach ($availableCourses as $index => $course): ?>
                                 <div class="course-card" style="--card-index: <?php echo $index; ?>">
                                    <div class="course-image-container">
                                        <?php if ($course['thumbnail']): ?>
                                            <img src="<?php echo htmlspecialchars($course['thumbnail']); ?>" alt="<?php echo htmlspecialchars($course['title']); ?>" class="course-image">
                                        <?php else: ?>
                                            <div class="course-image-placeholder" style="background: linear-gradient(135deg, <?php echo htmlspecialchars($course['category_color'] ?? '#667eea'); ?> 0%, <?php echo htmlspecialchars($course['category_color'] ?? '#764ba2'); ?> 100%);">
                                                <i class="<?php echo htmlspecialchars($course['category_icon'] ?? 'fas fa-graduation-cap'); ?>"></i>
                                            </div>
                                        <?php endif; ?>

                                        <div class="course-badges">
                                            <?php if ($course['is_featured']): ?>
                                                <span class="badge badge-featured">
                                                    <i class="fas fa-star"></i> Featured
                                                </span>
                                            <?php endif; ?>
                                            <?php if ($course['is_free']): ?>
                                                <span class="badge badge-free">Free</span>
                                            <?php endif; ?>
                                        </div>

                                        <div class="course-overlay">
                                            <a href="../courses/detail.php?id=<?php echo $course['id']; ?>" class="course-link">
                                                <i class="fas fa-eye"></i>
                                                View Course
                                            </a>
                                        </div>
                                    </div>

                                    <div class="course-content">
                                        <div class="course-category">
                                            <i class="<?php echo htmlspecialchars($course['category_icon']); ?>"></i>
                                            <?php echo htmlspecialchars($course['category_name']); ?>
                                        </div>

                                        <h3 class="course-title">
                                            <a href="../courses/detail.php?id=<?php echo $course['id']; ?>">
                                                <?php echo htmlspecialchars($course['title']); ?>
                                            </a>
                                        </h3>

                                        <p class="course-description">
                                            <?php echo htmlspecialchars(substr($course['short_description'] ?? $course['description'], 0, 120)); ?>...
                                        </p>

                                        <div class="course-meta">
                                            <div class="instructor-info">
                                                <i class="fas fa-user"></i>
                                                <span><?php echo htmlspecialchars($course['first_name'] && $course['last_name'] ? $course['first_name'] . ' ' . $course['last_name'] : $course['instructor_name']); ?></span>
                                            </div>
                                            <div class="course-rating">
                                                <?php if ($course['average_rating']): ?>
                                                    <div class="rating-stars">
                                                        <?php for ($i = 1; $i <= 5; $i++): ?>
                                                            <i class="fas fa-star <?php echo $i <= round($course['average_rating']) ? 'filled' : ''; ?>"></i>
                                                        <?php endfor; ?>
                                                    </div>
                                                    <span class="rating-score"><?php echo number_format($course['average_rating'], 1); ?></span>
                                                    <span class="rating-count">(<?php echo $course['review_count']; ?>)</span>
                                                <?php else: ?>
                                                    <span class="no-rating">No reviews yet</span>
                                                <?php endif; ?>
                                            </div>
                                        </div>

                                        <div class="course-footer">
                                            <div class="course-stats">
                                                <div class="stat">
                                                    <i class="fas fa-users"></i>
                                                    <span><?php echo $course['enrollment_count']; ?></span>
                                                </div>
                                                <div class="stat">
                                                    <i class="fas fa-clock"></i>
                                                    <span><?php echo $course['duration_hours']; ?>h</span>
                                                </div>
                                                <div class="stat">
                                                    <i class="fas fa-signal"></i>
                                                    <span><?php echo ucfirst($course['level']); ?></span>
                                                </div>
                                            </div>

                                            <div class="course-price">
                                                <?php if ($course['is_free']): ?>
                                                    <span class="price-free">Free</span>
                                                <?php else: ?>
                                                    <span class="price-amount"><?php echo formatCurrency($course['price'], $course['currency']); ?></span>
                                                <?php endif; ?>
                                            </div>
                                        </div>

                                        <div class="course-actions">
                                            <?php if (isLoggedIn()): ?>
                                                <?php if (isset($enrolledCoursesIds[$course['id']])): ?>
                                                    <a href="../learn.php?id=<?php echo $course['id']; ?>" class="btn btn-success">
                                                        <i class="fas fa-play me-2"></i>Continue Learning
                                                    </a>
                                                <?php elseif (hasPermission('enroll_course')): ?>
                                                    <button class="btn btn-primary" onclick="addToCartFromDashboard(<?php echo $course['id']; ?>, '<?php echo addslashes($course['title']); ?>')">
                                                        <i class="fas fa-cart-plus me-2"></i>
                                                        <?php echo $course['is_free'] ? 'Enroll Now (Free)' : 'Add to Cart'; ?>
                                                    </button>
                                                <?php endif; ?>
                                            <?php else: ?>
                                                <a href="../login.php?redirect=student/dashboard.php" class="btn btn-outline-primary">
                                                    <i class="fas fa-sign-in-alt me-2"></i>Login to Add to Cart
                                                </a>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div class="empty-courses">
                            <div class="empty-courses-content">
                                <i class="fas fa-graduation-cap empty-icon"></i>
                                <h3>No courses available</h3>
                                <p>Courses will be available soon. Check back later!</p>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </section>

            <!-- Available Exams Section (Hidden by default) - Dynamic Loading -->
            <section id="available-exams-section" class="available-courses-section" style="display: none;">
                <div class="container mx-auto px-4">
                    <div class="courses-header">
                        <h2 class="courses-title"><?php echo htmlspecialchars(getSiteSetting('available_exams_title') ?: 'Available Exams'); ?></h2>
                        <p class="courses-subtitle"><?php echo htmlspecialchars(getSiteSetting('available_exams_subtitle') ?: 'Test your knowledge with our comprehensive exam collection'); ?></p>
                    </div>

                        <!-- Filter Controls -->
                        <div class="flex flex-wrap justify-center gap-3 mb-6">
                            <select id="examTypeFilter" class="p-3 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500 text-sm">
                                <option value="">All Types</option>
                                <option value="quiz">Quiz</option>
                                <option value="midterm">Midterm</option>
                                <option value="final">Final</option>
                                <option value="practice">Practice</option>
                                <option value="certification">Certification</option>
                            </select>
                            <select id="examSortFilter" class="p-3 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500 text-sm">
                                <option value="newest">Newest First</option>
                                <option value="popular">Most Popular</option>
                                <option value="price_low">Price: Low to High</option>
                                <option value="price_high">Price: High to Low</option>
                            </select>
                            <input type="text" id="examSearchInput" placeholder="Search exams..." class="p-3 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500 text-sm">
                            <button onclick="loadExams()" class="bg-indigo-600 hover:bg-indigo-700 text-white px-6 py-3 rounded-lg font-semibold transition duration-200">
                                <i class="fas fa-search mr-2"></i>Search
                            </button>
                        </div>
                    </div>

                    <!-- Loading State -->
                    <div id="examsLoading" class="text-center py-12">
                        <div class="inline-block animate-spin rounded-full h-12 w-12 border-4 border-indigo-600 border-t-transparent"></div>
                        <p class="mt-4 text-gray-600">Loading exams...</p>
                    </div>

                    <!-- Error State -->
                    <div id="examsError" class="hidden text-center py-12">
                        <i class="fas fa-exclamation-circle text-red-500 text-5xl mb-4"></i>
                        <p class="text-gray-600 mb-4">Failed to load exams. Please try again.</p>
                        <button onclick="loadExams()" class="bg-indigo-600 hover:bg-indigo-700 text-white px-6 py-3 rounded-lg font-semibold transition duration-200">
                            <i class="fas fa-redo mr-2"></i>Retry
                        </button>
                    </div>

                    <!-- Exams Grid Container -->
                    <div id="examsGrid" class="courses-grid hidden">
                        <!-- Dynamic exam cards will be rendered here -->
                    </div>

                    <!-- Empty State -->
                    <div id="examsEmpty" class="hidden">
                        <div class="empty-courses">
                            <div class="empty-courses-content">
                                <i class="fas fa-file-alt empty-icon"></i>
                                <h3>No exams found</h3>
                                <p>Try adjusting your search or filters to find what you're looking for.</p>
                            </div>
                        </div>
                    </div>

                    <!-- Pagination -->
                    <div id="examsPagination" class="flex justify-center mt-8 hidden">
                        <nav aria-label="Exam pagination">
                            <ul class="flex gap-2" id="examsPaginationControls">
                                <!-- Pagination will be rendered here -->
                            </ul>
                        </nav>
                    </div>
                </div>
            </section>
        </main>
    </div>

    <!-- Review Modal -->
    <div id="reviewModal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50">
        <div class="bg-white rounded-xl shadow-2xl max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
            <div class="p-6">
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-2xl font-bold text-gray-900">Write a Review</h2>
                    <button onclick="closeReviewModal()" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times text-xl"></i>
                    </button>
                </div>

                <div id="reviewModalContent">
                    <!-- Review form will be loaded here -->
                </div>
            </div>
        </div>
    </div>

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

        // Toggle available courses section
        function toggleAvailableCourses() {
            const section = document.getElementById('available-courses-section');
            if (section.style.display === 'none' || section.style.display === '') {
                section.style.display = 'block';
                section.scrollIntoView({ behavior: 'smooth' });
            } else {
                section.style.display = 'none';
            }
        }

        // Current exam page for pagination
        let currentExamPage = 1;
        let examsCache = null; // Cache for loaded exams
        
        // Toggle available exams section with dynamic loading
        function toggleAvailableExams() {
            const section = document.getElementById('available-exams-section');
            if (section.style.display === 'none' || section.style.display === '') {
                section.style.display = 'block';
                section.scrollIntoView({ behavior: 'smooth' });
                
                // Load exams if not already loaded
                if (!examsCache) {
                    loadExams();
                }
            } else {
                section.style.display = 'none';
            }
        }
        
        // Load exams from API with loading states
        function loadExams(page = 1) {
            const loadingEl = document.getElementById('examsLoading');
            const errorEl = document.getElementById('examsError');
            const gridEl = document.getElementById('examsGrid');
            const emptyEl = document.getElementById('examsEmpty');
            const paginationEl = document.getElementById('examsPagination');
            
            // Get filter values
            const examType = document.getElementById('examTypeFilter')?.value || '';
            const sortFilter = document.getElementById('examSortFilter')?.value || 'newest';
            const searchInput = document.getElementById('examSearchInput')?.value || '';
            
            // Show loading, hide others
            loadingEl.classList.remove('hidden');
            errorEl.classList.add('hidden');
            gridEl.classList.add('hidden');
            emptyEl.classList.add('hidden');
            paginationEl.classList.add('hidden');
            
            // Build API URL
            const params = new URLSearchParams({
                page: page,
                per_page: 12,
                exam_type: examType,
                sort: sortFilter,
                search: searchInput
            });
            
            fetch('../api/exams/catalog.php?' + params.toString())
                .then(response => {
                    if (!response.ok) {
                        return response.text().then(text => {
                            console.error('API catalog returned non-OK response:', text);
                            // Try to extract error message from JSON response
                            try {
                                const json = JSON.parse(text);
                                throw new Error(json.message || 'Server error: ' + response.status);
                            } catch (e) {
                                if (e instanceof SyntaxError) {
                                    throw new Error('Network response was not ok (HTTP ' + response.status + ')');
                                }
                                throw e;
                            }
                        });
                    }
                    return response.json();
                })
                .then(data => {
                    loadingEl.classList.add('hidden');
                    
                    if (data.success) {
                        if (data.data && data.data.length > 0) {
                            // Render exams
                            renderExams(data.data);
                            gridEl.classList.remove('hidden');
                            
                            // Update cache
                            examsCache = data.data;
                            currentExamPage = page;
                            
                            // Render pagination if needed
                            if (data.meta && data.meta.total_pages > 1) {
                                renderPagination(data.meta.current_page, data.meta.total_pages);
                                paginationEl.classList.remove('hidden');
                            }
                        } else {
                            emptyEl.classList.remove('hidden');
                        }
                    } else {
                        throw new Error(data.error || 'Failed to load exams');
                    }
                })
                .catch(error => {
                    console.error('Error loading exams:', error);
                    loadingEl.classList.add('hidden');
                    errorEl.classList.remove('hidden');
                });
        }
        
        // Render exam cards
        function renderExams(exams) {
            const gridEl = document.getElementById('examsGrid');
            
            const html = exams.map((exam, index) => {
                const instructorName = exam.first_name && exam.last_name 
                    ? exam.first_name + ' ' + exam.last_name 
                    : exam.instructor_name;
                
                // Determine button action based on user access
                let actionButton = '';
                let actionOnclick = '';
                
                if (exam.user_attempt) {
                    // User has attempted this exam
                    actionButton = '<i class="fas fa-check me-2"></i>Attempted';
                    actionOnclick = 'window.location.href="exams.php"';
                } else if (exam.user_has_access || exam.is_free) {
                    // User has access or exam is free
                    actionButton = exam.is_free 
                        ? '<i class="fas fa-play me-2"></i>Take Exam (Free)'
                        : '<i class="fas fa-play me-2"></i>Take Exam';
                    actionOnclick = 'window.location.href="../exams/take.php?id=' + exam.id + '"';
                } else {
                    // User needs to purchase
                    actionButton = '<i class="fas fa-cart-plus me-2"></i>Add to Cart';
                    actionOnclick = 'addExamToCart(' + exam.id + ', "' + exam.title.replace(/"/g, '\\"') + '")';
                }
                
                return `
                    <div class="course-card" style="--card-index: ${index}">
                        <div class="course-image-container">
                            <div class="course-image-placeholder" style="background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);">
                                <i class="fas fa-file-alt"></i>
                            </div>
                            
                            <div class="course-badges">
                                ${exam.is_free ? '<span class="badge badge-free">Free</span>' : ''}
                            </div>
                            
                            <div class="course-overlay">
                                <a href="#" onclick="${actionOnclick}; return false;" class="course-link">
                                    <i class="fas fa-eye"></i>
                                    View Exam
                                </a>
                            </div>
                        </div>
                        
                        <div class="course-content">
                            <div class="course-category">
                                <i class="fas fa-graduation-cap"></i>
                                ${exam.exam_type.charAt(0).toUpperCase() + exam.exam_type.slice(1)}
                            </div>
                            
                            <h3 class="course-title">
                                <a href="#" onclick="${actionOnclick}; return false;">
                                    ${exam.title}
                                </a>
                            </h3>
                            
                            <p class="course-description">
                                ${exam.description_short || 'Test your knowledge with this exam'}
                            </p>
                            
                            <div class="course-meta">
                                <div class="instructor-info">
                                    <i class="fas fa-user"></i>
                                    <span>${instructorName || 'Unknown'}</span>
                                </div>
                                <div class="course-rating">
                                    <span class="no-rating">${exam.attempt_count} attempts</span>
                                </div>
                            </div>
                            
                            <div class="course-footer">
                                <div class="course-stats">
                                    <div class="stat">
                                        <i class="fas fa-clock"></i>
                                        <span>${exam.time_limit ? exam.time_limit + ' min' : 'No limit'}</span>
                                    </div>
                                    <div class="stat">
                                        <i class="fas fa-trophy"></i>
                                        <span>${exam.passing_score}%</span>
                                    </div>
                                    <div class="stat">
                                        <i class="fas fa-question-circle"></i>
                                        <span>${exam.total_points} pts</span>
                                    </div>
                                </div>
                                
                                <div class="course-price">
                                    ${exam.is_free 
                                        ? '<span class="price-free">Free</span>' 
                                        : '<span class="price-amount">' + exam.formatted_price + '</span>'}
                                </div>
                            </div>
                            
                            <div class="course-actions">
                                <button class="btn btn-primary" onclick="${actionOnclick}">
                                    ${actionButton}
                                </button>
                            </div>
                        </div>
                    </div>
                `;
            }).join('');
            
            gridEl.innerHTML = html;
        }
        
        // Render pagination controls
        function renderPagination(currentPage, totalPages) {
            const paginationControls = document.getElementById('examsPaginationControls');
            let html = '';
            
            // Previous button
            if (currentPage > 1) {
                html += `<li>
                    <button onclick="loadExams(${currentPage - 1})" class="flex items-center justify-center w-10 h-10 border-2 border-gray-300 bg-white text-gray-600 rounded-lg hover:border-indigo-500 hover:text-indigo-500 transition">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M15 18l-6-6 6-6"/></svg>
                    </button>
                </li>`;
            }
            
            // Page numbers
            for (let i = Math.max(1, currentPage - 2); i <= Math.min(totalPages, currentPage + 2); i++) {
                const isActive = i === currentPage;
                html += `<li>
                    <button onclick="loadExams(${i})" class="flex items-center justify-center w-10 h-10 border-2 rounded-lg transition ${isActive ? 'bg-indigo-600 border-indigo-600 text-white' : 'border-gray-300 bg-white text-gray-600 hover:border-indigo-500 hover:text-indigo-500'}">
                        ${i}
                    </button>
                </li>`;
            }
            
            // Next button
            if (currentPage < totalPages) {
                html += `<li>
                    <button onclick="loadExams(${currentPage + 1})" class="flex items-center justify-center w-10 h-10 border-2 border-gray-300 bg-white text-gray-600 rounded-lg hover:border-indigo-500 hover:text-indigo-500 transition">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 18l6-6-6-6"/></svg>
                    </button>
                </li>`;
            }
            
            paginationControls.innerHTML = html;
        }
        
        // Add exam to cart from dashboard
        function addExamToCart(examId, examTitle) {
            fetch('../api/cart.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ item_id: examId, item_type: 'exam' })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Show success message
                    let message = examTitle + ' has been added to your cart!';
                    if (data.already_in_cart) {
                        message = examTitle + ' is already in your cart!';
                    }
                    showToast(message, 'success');
                    // Update cart count
                    loadCartContent();
                } else {
                    showToast('Error: ' + data.error, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('An error occurred. Please try again.', 'error');
            });
        }
        
        // Add course to cart from dashboard
        function addToCartFromDashboard(courseId, courseTitle) {
            fetch('../api/cart.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ course_id: courseId })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Show success message
                    let message = courseTitle + ' has been added to your cart!';
                    if (data.already_in_cart) {
                        message = courseTitle + ' is already in your cart!';
                    }
                    showToast(message, 'success');
                    // Update cart count
                    loadCartContent();
                } else {
                    showToast('Error: ' + data.error, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('An error occurred. Please try again.', 'error');
            });
        }

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

        // Initialize cart and calendar on page load
        document.addEventListener('DOMContentLoaded', function() {
            loadCartContent();
            initDashboardCalendar();

            // Add click event to course cards
            const courseCards = document.querySelectorAll('.course-card[data-course-id]');
            courseCards.forEach(card => {
                card.addEventListener('click', function(e) {
                    // Don't redirect if clicking on a button
                    if (e.target.closest('button')) {
                        return;
                    }
                    const courseId = this.getAttribute('data-course-id');
                    if (courseId) {
                        window.location.href = 'learn.php?id=' + courseId;
                    }
                });
            });
            
            // Add Enter key support for exam search
            const examSearchInput = document.getElementById('examSearchInput');
            if (examSearchInput) {
                examSearchInput.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        loadExams();
                    }
                });
            }
        });

        // Load cart content
        function loadCartContent() {
            fetch('../api/cart.php')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Update cart count badge
                    const cartBadge = document.getElementById('dashboard-cart-count');
                    if (cartBadge) {
                        const count = data.cart.item_count || 0;
                        cartBadge.textContent = count;
                        cartBadge.classList.toggle('hidden', count === 0);
                    }

                    if (data.cart.items.length > 0) {
                        // Cart has items, checkout modal can be shown when needed
                        console.log('Cart loaded:', data.cart);
                    }
                }
            })
            .catch(error => console.error('Error loading cart:', error));
        }

        // Remove item from cart
        function removeFromCart(itemId) {
            fetch(`../api/cart.php?course_id=${itemId}`, {
                method: 'DELETE'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast('Item removed from cart', 'success');
                    loadCheckoutContent(); // Reload the checkout modal
                    loadCartContent(); // Update cart count badge
                } else {
                    showToast('Error removing item: ' + data.error, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('An error occurred. Please try again.', 'error');
            });
        }

        // Format currency for JavaScript
        function formatCurrency(amount, currency = 'USD') {
            const formatter = new Intl.NumberFormat('en-US', {
                style: 'currency',
                currency: currency,
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            });
            return formatter.format(amount);
        }

        // Show checkout modal from dashboard
        function showDashboardCheckoutModal() {
            // Create modal HTML
            const modalHtml = `
                <div id="dashboard-checkout-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
                    <div class="bg-white rounded-xl shadow-2xl max-w-md w-full mx-4 max-h-[90vh] overflow-y-auto">
                        <div class="p-6">
                            <div class="flex justify-between items-center mb-6">
                                <h2 class="text-xl font-bold text-gray-900">Complete Checkout</h2>
                                <button onclick="closeDashboardCheckoutModal()" class="text-gray-400 hover:text-gray-600">
                                    <i class="fas fa-times text-xl"></i>
                                </button>
                            </div>

                            <div id="checkout-content">
                                <!-- Content will be loaded here -->
                                <div class="text-center py-8">
                                    <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-blue mx-auto mb-4"></div>
                                    <p class="text-gray-600">Loading checkout...</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;

            document.body.insertAdjacentHTML('beforeend', modalHtml);

            // Add event listeners for closing modal
            const modal = document.getElementById('dashboard-checkout-modal');

            // Close modal when clicking outside
            modal.addEventListener('click', function(e) {
                if (e.target === modal) {
                    closeDashboardCheckoutModal();
                }
            });

            // Close modal when pressing ESC key
            const handleEscapeKey = function(e) {
                if (e.key === 'Escape') {
                    closeDashboardCheckoutModal();
                }
            };
            document.addEventListener('keydown', handleEscapeKey);

            // Store the escape handler to remove it later
            modal._escapeHandler = handleEscapeKey;

            loadCheckoutContent();
        }

        // Close checkout modal
        function closeDashboardCheckoutModal() {
            const modal = document.getElementById('dashboard-checkout-modal');
            if (modal) {
                // Remove escape key event listener
                if (modal._escapeHandler) {
                    document.removeEventListener('keydown', modal._escapeHandler);
                }
                modal.remove();
            }
        }

        // Load checkout content
        function loadCheckoutContent() {
            fetch('../api/cart.php')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const cart = data.cart;
                    renderCheckoutContent(cart);
                } else {
                    document.getElementById('checkout-content').innerHTML = '<div class="text-center py-8"><p class="text-red-600">Error loading cart</p></div>';
                }
            })
            .catch(error => {
                console.error('Error loading checkout:', error);
                document.getElementById('checkout-content').innerHTML = '<div class="text-center py-8"><p class="text-red-600">Error loading checkout</p></div>';
            });
        }

        // Render checkout content
        function renderCheckoutContent(cart) {
            if (!cart.items || cart.items.length === 0) {
                document.getElementById('checkout-content').innerHTML = `
                    <div class="text-center py-8">
                        <i class="fas fa-shopping-cart fa-3x text-gray-300 mb-4"></i>
                        <h5 class="text-gray-600 mb-2">Your cart is empty</h5>
                        <p class="text-sm text-gray-500 mb-6">Add some courses to get started with your learning journey</p>
                        <div class="flex flex-col sm:flex-row gap-3 justify-center">
                            <button onclick="closeDashboardCheckoutModal(); toggleAvailableCourses();" class="bg-primary text-white px-6 py-2 rounded-lg hover:bg-indigo-700 font-medium">
                                <i class="fas fa-graduation-cap mr-2"></i>Browse Courses
                            </button>
                            <a href="../courses/catalog.php" class="bg-white text-primary border border-primary px-6 py-2 rounded-lg hover:bg-blue-50 font-medium">
                                <i class="fas fa-external-link-alt mr-2"></i>View Full Catalog
                            </a>
                        </div>
                    </div>
                `;
                return;
            }

            let itemsHtml = '';
            cart.items.forEach(item => {
                itemsHtml += `
                    <div class="bg-gray-50 rounded-lg p-4 mb-3 border border-gray-200">
                        <div class="flex items-start justify-between">
                            <div class="flex items-start space-x-3 flex-1">
                                ${item.thumbnail ? `<img src="${item.thumbnail}" alt="${item.title}" class="w-16 h-12 object-cover rounded border">` : '<div class="w-16 h-12 bg-gray-300 rounded flex items-center justify-center"><i class="fas fa-graduation-cap text-gray-600"></i></div>'}
                                <div class="flex-1">
                                    <h6 class="font-semibold text-gray-900 text-sm mb-1">${item.title}</h6>
                                    <p class="text-xs text-gray-600 mb-2">${item.is_free ? '<span class="text-green-600 font-medium">Free Course</span>' : '<span class="text-blue-600 font-medium">' + formatCurrency(item.price, item.currency) + '</span>'}</p>
                                    <div class="flex items-center space-x-2">
                                        <a href="../courses/detail.php?id=${item.item_id}" target="_blank" class="text-xs text-blue-600 hover:text-blue-800 font-medium flex items-center">
                                            <i class="fas fa-external-link-alt mr-1"></i>View Details
                                        </a>
                                        <span class="text-gray-400">|</span>
                                        <button onclick="removeFromCart(${item.item_id})" class="text-xs text-red-600 hover:text-red-800 font-medium flex items-center">
                                            <i class="fas fa-trash mr-1"></i>Remove
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            });

            const checkoutHtml = `
                <div class="mb-6">
                    <div class="flex justify-between items-center mb-4">
                        <h3 class="font-medium text-gray-800">Cart Items (${cart.items.length})</h3>
                        <div class="flex items-center space-x-3">
                            <button onclick="closeDashboardCheckoutModal(); toggleAvailableCourses();" class="text-sm text-blue-600 hover:text-blue-800 font-medium flex items-center">
                                <i class="fas fa-plus mr-1"></i>Add More Courses
                            </button>
                            <button onclick="clearCart()" class="text-xs text-gray-500 hover:text-red-600 font-medium flex items-center ml-4 px-2 py-1 border border-gray-300 rounded">
                                <i class="fas fa-trash mr-1"></i>Clear All
                            </button>
                        </div>
                    </div>
                    ${itemsHtml}
                </div>

                <div class="bg-gray-50 p-4 rounded-lg mb-6">
                    <div class="flex justify-between items-center">
                        <span class="font-medium text-gray-700">Total:</span>
                        <span class="text-xl font-bold text-primary">${formatCurrency(cart.total, cart.currency)}</span>
                    </div>
                </div>

                ${cart.total == 0 ?
                    // Free checkout
                    `<div class="text-center">
                        <div class="bg-green-50 border border-green-200 rounded-lg p-4 mb-4">
                            <i class="fas fa-check-circle text-green-600 text-2xl mb-2"></i>
                            <p class="text-green-800">All items are free! Click below to enroll immediately.</p>
                        </div>
                        <button onclick="processFreeEnrollment()" class="w-full bg-green-600 text-white py-3 px-4 rounded-lg font-semibold hover:bg-green-700 transition duration-200">
                            <i class="fas fa-graduation-cap mr-2"></i>Enroll Now
                        </button>
                    </div>` :

                    // Paid checkout
                    `<form id="dashboard-payment-form">
                        <input type="hidden" name="item_type" value="cart">
                        <input type="hidden" name="cart_total" value="${cart.total}">
                        <input type="hidden" name="currency" value="${cart.currency}">

                        <div class="mb-4">
                            <label class="block text-sm font-medium text-gray-700 mb-2">Discount Code (Optional)</label>
                            <input type="text" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent" name="discount_code" placeholder="Enter discount code">
                            <div id="dashboard-discount-message" class="text-sm mt-1"></div>
                        </div>

                        <div class="mb-4">
                            <label class="block text-sm font-medium text-gray-700 mb-2">Payment Method</label>
                            <div class="space-y-2">
                                <div class="flex items-center">
                                    <input class="w-4 h-4 text-primary bg-gray-100 border-gray-300 focus:ring-primary" type="radio" name="gateway" value="paynow" id="dashboard-paynow" checked>
                                    <label class="ml-3 text-sm font-medium text-gray-700" for="dashboard-paynow">
                                        <i class="fas fa-mobile-alt mr-2 text-blue-500"></i>Paynow (Mobile Money)
                                    </label>
                                </div>
                                <div class="flex items-center">
                                    <input class="w-4 h-4 text-primary bg-gray-100 border-gray-300 focus:ring-primary" type="radio" name="gateway" value="paypal" id="dashboard-paypal">
                                    <label class="ml-3 text-sm font-medium text-gray-700" for="dashboard-paypal">
                                        <i class="fab fa-paypal mr-2 text-blue-500"></i>PayPal
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div id="dashboard-final-amount" class="bg-blue-50 border border-blue-200 rounded-lg p-3 mb-4">
                            <strong class="text-blue-900">Final Amount: ${formatCurrency(cart.total, cart.currency)}</strong>
                        </div>

                        <div class="text-center space-y-3">
                            <!-- Paynow Button (shown when Paynow is selected) -->
                            <div id="paynow-button-container" class="hidden">
                                <a id="paynow-payment-link" href="https://www.paynow.co.zw/Payment/Link/?q=c2VhcmNoPW11dGFsZXh6dyU0MGdtYWlsLmNvbSZhbW91bnQ=${cart.total}.00ZyZWZlcmVuY2U9Jmw9MQ%3d%3d" target="_blank" class="inline-block">
                                    <img src="https://www.paynow.co.zw/Content/Buttons/Medium_buttons/button_pay-now_medium.png" style="border:0" alt="Pay with Paynow" />
                                </a>
                            </div>

                            <!-- Standard Pay Button -->
                            <button type="submit" class="w-full bg-primary text-white py-3 px-4 rounded-lg font-semibold hover:bg-indigo-700 transition duration-200" id="dashboard-pay-button">
                                <i class="fas fa-credit-card mr-2"></i>Pay ${formatCurrency(cart.total, cart.currency)}
                            </button>
                        </div>
                    </form>`
                }
            `;

            document.getElementById('checkout-content').innerHTML = checkoutHtml;

            // Add event listeners
            const discountInput = document.querySelector('#dashboard-payment-form input[name="discount_code"]');
            if (discountInput) {
                discountInput.addEventListener('blur', function() {
                    validateDashboardDiscountCode(this.value, cart.total, cart.currency);
                });
            }

            // Handle payment method selection
            const paymentMethodRadios = document.querySelectorAll('#dashboard-payment-form input[name="gateway"]');
            paymentMethodRadios.forEach(radio => {
                radio.addEventListener('change', function() {
                    const paynowContainer = document.getElementById('paynow-button-container');
                    if (this.value === 'paynow') {
                        paynowContainer.classList.remove('hidden');
                    } else {
                        paynowContainer.classList.add('hidden');
                    }
                });
            });

            const paymentForm = document.getElementById('dashboard-payment-form');
            if (paymentForm) {
                paymentForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    processDashboardPayment(new FormData(this));
                });
            }
        }

        // Validate discount code in dashboard checkout
        function validateDashboardDiscountCode(code, originalPrice, currency) {
            if (!code.trim()) {
                document.getElementById('dashboard-discount-message').innerHTML = '';
                updateDashboardFinalAmount(originalPrice, 0, currency);
                return;
            }

            document.getElementById('dashboard-discount-message').innerHTML = '<small class="text-gray-500">Validating discount code...</small>';

            setTimeout(() => {
                if (code.toUpperCase().startsWith('TEST')) {
                    const discountAmount = originalPrice * 0.1;
                    document.getElementById('dashboard-discount-message').innerHTML = '<small class="text-green-600">10% discount applied!</small>';
                    updateDashboardFinalAmount(originalPrice, discountAmount, currency);
                } else {
                    document.getElementById('dashboard-discount-message').innerHTML = '<small class="text-red-600">Invalid discount code</small>';
                    updateDashboardFinalAmount(originalPrice, 0, currency);
                }
            }, 500);
        }

        // Update final amount in dashboard checkout
        function updateDashboardFinalAmount(originalPrice, discountAmount, currency) {
            const finalAmount = originalPrice - discountAmount;
            document.getElementById('dashboard-final-amount').innerHTML = `<strong>Final Amount: ${formatCurrency(finalAmount, currency)}</strong>`;
            document.getElementById('dashboard-pay-button').innerHTML = `<i class="fas fa-credit-card mr-2"></i>Pay ${formatCurrency(finalAmount, currency)}`;

            // Update Paynow URL with final amount
            const paynowLink = document.getElementById('paynow-payment-link');
            if (paynowLink) {
                const baseUrl = paynowLink.href.replace(/amount=\d+\.\d+/, `amount=${finalAmount.toFixed(2)}`);
                paynowLink.href = baseUrl;
            }
        }

        // Process payment from dashboard
        function processDashboardPayment(formData) {
            const payButton = document.getElementById('dashboard-pay-button');
            const originalText = payButton.innerHTML;

            payButton.disabled = true;
            payButton.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Processing...';

            const paymentData = {
                item_type: 'cart',
                gateway: formData.get('gateway') || 'paynow',
                discount_code: formData.get('discount_code') || null
            };

            fetch('../api/payments.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(paymentData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    if (data.redirect_url) {
                        window.location.href = data.redirect_url;
                    } else {
                        showToast('Payment initiated successfully!', 'success');
                        closeDashboardCheckoutModal();
                        loadCartContent(); // Reload cart count
                        setTimeout(() => {
                            location.reload(); // Reload page to show enrolled courses
                        }, 1500);
                    }
                } else {
                    showToast('Payment failed: ' + (data.error || 'Unknown error'), 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('An error occurred. Please try again.', 'error');
            })
            .finally(() => {
                payButton.disabled = false;
                payButton.innerHTML = originalText;
            });
        }

        // Clear entire cart
        function clearCart() {
            if (confirm('Are you sure you want to clear your entire cart?')) {
                fetch('../api/cart.php', {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showToast('Cart cleared successfully', 'success');
                        loadCheckoutContent(); // Reload the checkout modal
                        loadCartContent(); // Update cart count badge
                    } else {
                        showToast('Error clearing cart: ' + data.error, 'error');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showToast('An error occurred. Please try again.', 'error');
                });
            }
        }

        // Process free enrollment from dashboard
        function processFreeEnrollment() {
            fetch('../api/cart.php', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    if (data.payment_required) {
                        showToast('Payment required. Redirecting to checkout...', 'success');
                        closeDashboardCheckoutModal();
                        setTimeout(() => {
                            window.location.href = 'checkout.php';
                        }, 1000);
                    } else {
                        showToast('Successfully enrolled in courses!', 'success');
                        closeDashboardCheckoutModal();
                        loadCartContent();
                        setTimeout(() => {
                            location.reload();
                        }, 1500);
                    }
                } else {
                    showToast('Error: ' + (data.error || 'Enrollment failed'), 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('An error occurred. Please try again.', 'error');
            });
        }

        // Dashboard Calendar Widget Functions
        let dashboardCalendarEvents = [];
        let dashboardCurrentDate = new Date();

        // Initialize dashboard calendar
        function initDashboardCalendar() {
            loadDashboardCalendarEvents();
        }

        // Load events for dashboard calendar
        async function loadDashboardCalendarEvents() {
            try {
                const response = await fetch('../api/calendar.php');
                const data = await response.json();

                if (data.success) {
                    dashboardCalendarEvents = data.events.map(event => ({
                        id: event.id,
                        title: event.title,
                        description: event.description,
                        date: event.event_date,
                        creator: event.creator_name || 'Admin',
                        time: event.event_time || '09:00'
                    }));

                    // Add sample events if no events exist
                    if (dashboardCalendarEvents.length === 0) {
                        const today = new Date();
                        const sampleEvents = [
                            {
                                id: 'sample-1',
                                title: 'Welcome Meeting',
                                description: 'Welcome to the new semester',
                                date: new Date(today.getTime() + 2 * 24 * 60 * 60 * 1000).toISOString().split('T')[0], // 2 days from now
                                creator: 'Admin',
                                time: '10:00'
                            },
                            {
                                id: 'sample-2',
                                title: 'Study Group',
                                description: 'Group study session',
                                date: new Date(today.getTime() + 5 * 24 * 60 * 60 * 1000).toISOString().split('T')[0], // 5 days from now
                                creator: 'Admin',
                                time: '14:00'
                            },
                            {
                                id: 'sample-3',
                                title: 'Assignment Due',
                                description: 'Submit your assignments',
                                date: new Date(today.getTime() + 10 * 24 * 60 * 60 * 1000).toISOString().split('T')[0], // 10 days from now
                                creator: 'Admin',
                                time: '23:59'
                            }
                        ];
                        dashboardCalendarEvents = sampleEvents;
                    }

                    renderDashboardCalendar();
                    renderDashboardUpcomingEvents();
                } else {
                    console.error("Failed to load calendar events:", data.error);
                    document.getElementById('dashboard-calendar-container').innerHTML = '<p class="text-sm text-gray-500">Unable to load calendar</p>';
                }
            } catch (error) {
                console.error("Error loading dashboard calendar:", error);
                document.getElementById('dashboard-calendar-container').innerHTML = '<p class="text-sm text-gray-500">Error loading calendar</p>';
            }
        }

        // Render mini calendar for dashboard
        function renderDashboardCalendar() {
            const container = document.getElementById('dashboard-calendar-container');
            const year = dashboardCurrentDate.getFullYear();
            const month = dashboardCurrentDate.getMonth();

            // Get days in month and first day
            const daysInMonth = new Date(year, month + 1, 0).getDate();
            const firstDay = new Date(year, month, 1).getDay();

            // Create calendar HTML
            let html = `
                <div class="text-center mb-3">
                    <div class="flex justify-between items-center">
                        <button onclick="changeDashboardMonth(-1)" class="text-primary-blue hover:text-blue-700 p-1">
                            <i class="fas fa-chevron-left text-sm"></i>
                        </button>
                        <h4 class="text-sm font-semibold text-gray-800">
                            ${new Date(year, month).toLocaleDateString('en-US', { month: 'short', year: 'numeric' })}
                        </h4>
                        <button onclick="changeDashboardMonth(1)" class="text-primary-blue hover:text-blue-700 p-1">
                            <i class="fas fa-chevron-right text-sm"></i>
                        </button>
                    </div>
                </div>

                <!-- Day headers -->
                <div class="grid grid-cols-7 gap-1 mb-2">
                    <div class="text-center text-xs font-medium text-gray-500">S</div>
                    <div class="text-center text-xs font-medium text-gray-500">M</div>
                    <div class="text-center text-xs font-medium text-gray-500">T</div>
                    <div class="text-center text-xs font-medium text-gray-500">W</div>
                    <div class="text-center text-xs font-medium text-gray-500">T</div>
                    <div class="text-center text-xs font-medium text-gray-500">F</div>
                    <div class="text-center text-xs font-medium text-gray-500">S</div>
                </div>

                <!-- Calendar days -->
                <div class="grid grid-cols-7 gap-1">
            `;

            // Empty cells for days before month starts
            for (let i = 0; i < firstDay; i++) {
                html += '<div class="h-6"></div>';
            }

            // Days of the month
            for (let day = 1; day <= daysInMonth; day++) {
                const date = new Date(year, month, day);
                const dateKey = date.toISOString().split('T')[0];
                const isToday = dateKey === new Date().toISOString().split('T')[0];
                const dayEvents = dashboardCalendarEvents.filter(e => e.date === dateKey);

                let cellClasses = 'h-6 w-6 text-xs flex items-center justify-center rounded cursor-pointer transition-colors ';
                if (isToday) {
                    cellClasses += 'bg-indigo-50/30';
                } else if (dayEvents.length > 0) {
                    cellClasses += 'bg-blue-100 text-primary-blue hover:bg-blue-200';
                } else {
                    cellClasses += 'text-gray-600 hover:bg-gray-100';
                }

                let dayClasses = 'w-4 h-4 flex items-center justify-center rounded-full ';
                if (isToday) {
                    dayClasses += 'bg-indigo-600 text-white shadow-md';
                } else {
                    dayClasses += 'text-current';
                }

                html += `
                    <div class="${cellClasses}" title="${dayEvents.length > 0 ? dayEvents.length + ' event(s)' : ''}">
                        <span class="${dayClasses}">${day}</span>
                        ${dayEvents.length > 0 ? '<div class="w-1 h-1 bg-blue-500 rounded-full mt-0.5"></div>' : ''}
                    </div>
                `;
            }

            html += '</div>';
            container.innerHTML = html;
        }

        // Change dashboard calendar month
        function changeDashboardMonth(delta) {
            dashboardCurrentDate.setMonth(dashboardCurrentDate.getMonth() + delta);
            renderDashboardCalendar();
        }

        // Render upcoming events for dashboard
        function renderDashboardUpcomingEvents() {
            const container = document.getElementById('dashboard-upcoming-events');
            const today = new Date();

            const upcomingEvents = dashboardCalendarEvents
                .filter(event => {
                    const eventDate = new Date(event.date);
                    return eventDate >= today;
                })
                .sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime())
                .slice(0, 3); // Show only next 3 events

            if (upcomingEvents.length === 0) {
                container.innerHTML = '<p class="text-xs text-gray-500">No upcoming events</p>';
                return;
            }

            let html = '';
            upcomingEvents.forEach(event => {
                const eventDate = new Date(event.date);
                const isToday = event.date === today.toISOString().split('T')[0];
                const dateText = isToday ? 'Today' : eventDate.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });

                html += `
                    <div class="flex items-start space-x-2">
                        <div class="flex-shrink-0 w-2 h-2 bg-primary-blue rounded-full mt-1.5"></div>
                        <div class="flex-1 min-w-0">
                            <p class="text-xs font-medium text-gray-800 truncate">${event.title}</p>
                            <p class="text-xs text-gray-500">${dateText} at ${event.time}</p>
                        </div>
                    </div>
                `;
            });

            container.innerHTML = html;
        }

        // Review Modal Functions
        function openReviewModal(courseId, courseTitle) {
            const modal = document.getElementById('reviewModal');
            const modalContent = document.getElementById('reviewModalContent');

            // Create review form HTML
            const reviewFormHtml = `
                <form id="dashboardReviewForm">
                    <input type="hidden" name="type" value="course">
                    <input type="hidden" name="item_id" value="${courseId}">

                    <div class="mb-6">
                        <h3 class="text-lg font-semibold text-gray-900 mb-2">Reviewing: ${courseTitle}</h3>
                        <p class="text-sm text-gray-600">Share your experience with this course</p>
                    </div>

                    <!-- Rating Section -->
                    <div class="mb-6">
                        <label class="block text-gray-700 font-semibold mb-3">Your Rating</label>
                        <div id="dashboardRatingContainer" class="flex space-x-1 cursor-pointer text-3xl" onmouseout="resetDashboardVisualRating()">
                            <div data-rating="1" class="dashboard-rating-star transition-colors duration-150" onmouseover="visualizeDashboardRating(1)" onclick="setDashboardRating(1)">
                                <svg class="w-8 h-8 fill-current text-gray-300" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M12 2l3.09 6.26l6.91 1l-5 4.87l1.18 6.88l-6.18-3.25l-6.18 3.25l1.18-6.88l-5-4.87l6.91-1L12 2z"/>
                                </svg>
                            </div>
                            <div data-rating="2" class="dashboard-rating-star transition-colors duration-150" onmouseover="visualizeDashboardRating(2)" onclick="setDashboardRating(2)">
                                <svg class="w-8 h-8 fill-current text-gray-300" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M12 2l3.09 6.26l6.91 1l-5 4.87l1.18 6.88l-6.18-3.25l-6.18 3.25l1.18-6.88l-5-4.87l6.91-1L12 2z"/>
                                </svg>
                            </div>
                            <div data-rating="3" class="dashboard-rating-star transition-colors duration-150" onmouseover="visualizeDashboardRating(3)" onclick="setDashboardRating(3)">
                                <svg class="w-8 h-8 fill-current text-gray-300" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M12 2l3.09 6.26l6.91 1l-5 4.87l1.18 6.88l-6.18-3.25l-6.18 3.25l1.18-6.88l-5-4.87l6.91-1L12 2z"/>
                                </svg>
                            </div>
                            <div data-rating="4" class="dashboard-rating-star transition-colors duration-150" onmouseover="visualizeDashboardRating(4)" onclick="setDashboardRating(4)">
                                <svg class="w-8 h-8 fill-current text-gray-300" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M12 2l3.09 6.26l6.91 1l-5 4.87l1.18 6.88l-6.18-3.25l-6.18 3.25l1.18-6.88l-5-4.87l6.91-1L12 2z"/>
                                </svg>
                            </div>
                            <div data-rating="5" class="dashboard-rating-star transition-colors duration-150" onmouseover="visualizeDashboardRating(5)" onclick="setDashboardRating(5)">
                                <svg class="w-8 h-8 fill-current text-gray-300" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M12 2l3.09 6.26l6.91 1l-5 4.87l1.18 6.88l-6.18-3.25l-6.18 3.25l1.18-6.88l-5-4.87l6.91-1L12 2z"/>
                                </svg>
                            </div>
                        </div>
                        <p class="text-sm text-gray-500 mt-2">Click to rate this course</p>
                        <input type="hidden" name="rating" id="dashboardRatingValue" value="0" required>
                    </div>

                    <!-- Review Title -->
                    <div class="mb-4">
                        <label for="dashboardReviewTitle" class="block text-gray-700 font-semibold mb-2">Review Title (Optional)</label>
                        <input type="text" id="dashboardReviewTitle" name="review_title" placeholder="Summarize your experience..." class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-blue focus:border-transparent outline-none transition-shadow" maxlength="100">
                    </div>

                    <!-- Review Text -->
                    <div class="mb-6">
                        <label for="dashboardReviewText" class="block text-gray-700 font-semibold mb-2">Your Review</label>
                        <textarea id="dashboardReviewText" name="review_text" placeholder="Share your experience with this course..." rows="4" class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-blue focus:border-transparent outline-none resize-none transition-shadow" required></textarea>
                    </div>

                    <!-- Submit Button -->
                    <div class="flex justify-end space-x-3">
                        <button type="button" onclick="closeReviewModal()" class="px-4 py-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">
                            Cancel
                        </button>
                        <button type="submit" class="px-6 py-2 bg-primary-blue text-white rounded-lg hover:bg-blue-700 transition-colors font-semibold">
                            <i class="fas fa-paper-plane mr-2"></i>Submit Review
                        </button>
                    </div>
                </form>
            `;

            modalContent.innerHTML = reviewFormHtml;
            modal.classList.remove('hidden');
            modal.classList.add('flex');

            // Add form submission handler
            const reviewForm = document.getElementById('dashboardReviewForm');
            reviewForm.addEventListener('submit', function(e) {
                e.preventDefault();
                submitDashboardReview(new FormData(this));
            });

            // Add escape key handler
            const handleEscapeKey = function(e) {
                if (e.key === 'Escape') {
                    closeReviewModal();
                }
            };
            document.addEventListener('keydown', handleEscapeKey);

            // Add click outside to close
            modal.addEventListener('click', function(e) {
                if (e.target === modal) {
                    closeReviewModal();
                }
            });

            // Store the escape handler to remove it later
            modal._escapeHandler = handleEscapeKey;
        }

        function closeReviewModal() {
            const modal = document.getElementById('reviewModal');
            if (modal) {
                modal.classList.add('hidden');
                modal.classList.remove('flex');

                // Remove escape key event listener
                if (modal._escapeHandler) {
                    document.removeEventListener('keydown', modal._escapeHandler);
                }
            }
        }

        // Dashboard Rating Functions
        function visualizeDashboardRating(rating) {
            const stars = document.querySelectorAll('#dashboardRatingContainer .dashboard-rating-star');
            stars.forEach((star, index) => {
                if (index < rating) {
                    star.classList.remove('text-gray-300');
                    star.classList.add('text-yellow-400');
                } else {
                    star.classList.remove('text-yellow-400');
                    star.classList.add('text-gray-300');
                }
            });
        }

        function setDashboardRating(rating) {
            const ratingValue = document.getElementById('dashboardRatingValue');
            ratingValue.value = rating;

            const stars = document.querySelectorAll('#dashboardRatingContainer .dashboard-rating-star');
            stars.forEach((star, index) => {
                if (index < rating) {
                    star.classList.remove('text-gray-300');
                    star.classList.add('text-yellow-400', 'filled');
                } else {
                    star.classList.remove('text-yellow-400', 'filled');
                    star.classList.add('text-gray-300');
                }
            });
        }

        function resetDashboardVisualRating() {
            const ratingValue = document.getElementById('dashboardRatingValue');
            const currentRating = parseInt(ratingValue.value) || 0;
            const stars = document.querySelectorAll('#dashboardRatingContainer .dashboard-rating-star');

            stars.forEach((star, index) => {
                if (index < currentRating) {
                    star.classList.remove('text-gray-300');
                    star.classList.add('text-yellow-400');
                } else {
                    star.classList.remove('text-yellow-400');
                    star.classList.add('text-gray-300');
                }
            });
        }

        function submitDashboardReview(formData) {
            const submitBtn = document.querySelector('#dashboardReviewForm button[type="submit"]');
            const originalText = submitBtn.innerHTML;

            // Validate rating
            const ratingValue = document.getElementById('dashboardRatingValue').value;
            if (!ratingValue || ratingValue === '0') {
                showToast('Please select a rating', 'error');
                return;
            }

            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Submitting...';

            fetch('../api/reviews.php', {
                method: 'POST',
                body: JSON.stringify({
                    type: formData.get('type'),
                    item_id: formData.get('item_id'),
                    rating: formData.get('rating'),
                    review_title: formData.get('review_title'),
                    review_text: formData.get('review_text')
                }),
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast(data.message, 'success');
                    closeReviewModal();
                    setTimeout(() => {
                        location.reload(); // Reload to show updated course status
                    }, 2000);
                } else {
                    showToast(data.error || 'Failed to submit review', 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('An error occurred. Please try again.', 'error');
            })
            .finally(() => {
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
            });
        }
    </script>
</body>
</html>
