<?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 = 'completed'
    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
           LIMIT 6";

$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);
}
?>

<!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(auto-fill, minmax(250px, 1fr));
            gap: 2rem;
            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);
        }

        .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: 200px;
            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: 1.75rem;
        }

        .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.8rem;
            font-weight: 500;
            margin-bottom: 1rem;
        }

        .course-title {
            font-size: 1.3rem;
            font-weight: 700;
            color: #1f2937;
            margin-bottom: 0.875rem;
            line-height: 1.3;
            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.95rem;
            line-height: 1.6;
            margin-bottom: 1.25rem;
            font-weight: 400;
        }

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

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

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

        .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.8rem;
        }

        .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.75rem 1rem;
            border-radius: 8px;
            font-weight: 600;
            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;
        }

        /* Responsive Design */
        @media (max-width: 1024px) {
            .courses-grid {
                grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
                gap: 1.75rem;
            }
        }

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

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

            .courses-grid {
                grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
                gap: 1.5rem;
            }

            .course-card {
                border-radius: 12px;
            }

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

            .course-content {
                padding: 1.5rem;
            }

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

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

            .course-actions {
                width: 100%;
            }

            .course-actions .btn {
                width: 100%;
                justify-content: center;
            }
        }

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

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

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

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

            .course-description {
                font-size: 0.9rem;
            }
        }
    </style>
</head>
<body class="bg-background-light font-sans text-text-dark min-h-screen">

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

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

                <!-- Navigation Links -->
                <nav class="space-y-2 flex-grow">
                    <a href="dashboard.php" class="flex items-center space-x-3 p-3 rounded-lg 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="courses.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Book -->
                        <span class="w-5 h-5">📚</span>
                        <span>My Courses</span>
                    </a>
                    <a href="reports.php" class="flex items-center space-x-3 p-3 rounded-lg 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="#" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Calendar -->
                        <span class="w-5 h-5">📅</span>
                        <span>Calendar</span>
                    </a>
                </nav>

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

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

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

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

            <!-- Mobile Navigation Overlay (Hidden by default) -->
            <div id="mobileMenu" class="fixed inset-0 bg-white z-20 p-6 transform -translate-x-full transition-transform duration-300 lg:hidden">
                <div class="flex justify-between items-center mb-10">
                    <div class="text-xl font-extrabold text-primary-blue tracking-wider">MUTALEX ACADEMY</div>
                    <button id="closeMobileMenu" class="text-3xl text-text-dark">&times;</button>
                </div>
                <nav class="space-y-4">
                    <!-- Links repeated from sidebar -->
                    <a href="dashboard.php" class="block p-3 rounded-lg bg-primary-blue text-white font-semibold">🏠 Dashboard</a>
                    <a href="courses.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📚 My Courses</a>
                    <a href="reports.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">✅ Grades & Reports</a>
                    <a href="#" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📅 Calendar</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 for checkout
                    $cartResponse = json_decode(file_get_contents('../api/cart.php'), true);
                    $cart = $cartResponse['cart'] ?? ['items' => [], 'total' => 0.00, 'currency' => 'USD'];
                    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">
                                        <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>
                                    </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>
                </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="#" class="mt-4 block text-sm text-primary-blue hover:text-primary-blue/80 font-medium">View Full Calendar</a>
                    </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 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: Mail -->
                                <span>📧</span>
                                <span class="mt-1">Email Instructor</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="../courses/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>
        </main>
    </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';
            }
        }

        // Add 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 on page load
        document.addEventListener('DOMContentLoaded', function() {
            loadCartContent();
        });

        // 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...';

            fetch('../api/payments.php', {
                method: 'POST',
                body: formData
            })
            .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) {
                    showToast('Successfully enrolled in courses!', 'success');
                    closeDashboardCheckoutModal();
                    loadCartContent(); // Reload cart count
                    setTimeout(() => {
                        location.reload(); // Reload page to show enrolled courses
                    }, 1500);
                } else {
                    showToast('Error: ' + (data.error || 'Enrollment failed'), 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('An error occurred. Please try again.', 'error');
            });
        }
    </script>
</body>
</html>
