<?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 filter parameters
$category = $_GET['category'] ?? '';
$level = $_GET['level'] ?? '';
$search = $_GET['search'] ?? '';
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 12;

// Get enrolled course IDs for the current user to exclude them
$stmt = $db->prepare("SELECT course_id FROM course_enrollments WHERE student_id = ?");
$stmt->execute([$userId]);
$enrolledCourseIds = $stmt->fetchAll(PDO::FETCH_COLUMN);

// Build query for available courses (published, not enrolled)
$query = "SELECT DISTINCT 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 course_lessons cl ON c.id = cl.course_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)";

$params = [];

// Exclude enrolled courses
if (!empty($enrolledCourseIds)) {
    $placeholders = str_repeat('?,', count($enrolledCourseIds) - 1) . '?';
    $query .= " AND c.id NOT IN ($placeholders)";
    $params = array_merge($params, $enrolledCourseIds);
}

// Add filters
if (!empty($category)) {
    $query .= " AND cat.slug = ?";
    $params[] = $category;
}

if (!empty($level)) {
    $query .= " AND c.level = ?";
    $params[] = $level;
}

if (!empty($search)) {
    $query .= " AND (c.title LIKE ? OR c.description LIKE ? OR c.tags LIKE ? OR cl.content LIKE ?)";
    $searchTerm = "%$search%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

// Add sorting (default newest)
$query .= " ORDER BY c.created_at DESC";

// Get total count for pagination
$countQuery = "SELECT COUNT(DISTINCT c.id) as total
               FROM courses c
               LEFT JOIN course_categories cat ON c.category_id = cat.id
               LEFT JOIN course_lessons cl ON c.id = cl.course_id
               WHERE c.status = 'published' AND (cat.is_active = 1 OR cat.id IS NULL)";

$countParams = $params; // Same filters

if (!empty($enrolledCourseIds)) {
    $placeholders = str_repeat('?,', count($enrolledCourseIds) - 1) . '?';
    $countQuery .= " AND c.id NOT IN ($placeholders)";
    // $countParams already has the enrolledCourseIds from $params
}

$stmt = $db->prepare($countQuery);
$stmt->execute($countParams);
$totalCourses = $stmt->fetch()['total'];
$totalPages = ceil($totalCourses / $perPage);

// Add pagination
$offset = ($page - 1) * $perPage;
$query .= " LIMIT $perPage OFFSET $offset";

// Execute main query
$stmt = $db->prepare($query);
$stmt->execute($params);
$courses = $stmt->fetchAll();

// Get categories for filter
$stmt = $db->query("SELECT * FROM course_categories WHERE is_active = 1 ORDER BY name");
$categories = $stmt->fetchAll();

$page_title = 'Available Courses | ' . htmlspecialchars($user['username'] ?? 'Student') . ' - Mutalex Academy';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?></title>
    <!-- Load Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Set up Tailwind configuration for Inter font and a professional color palette -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'primary-blue': '#1E3A8A', // Deep Indigo/Navy
                        'background-light': '#F8FAFC', // Slate 50
                        'text-dark': '#1F2937', // Gray 800
                        'accent-subtle': '#E5E7EB', // Gray 200
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style>
        /* Ensuring full page height and scrolling */
        html, body {
            height: 100%;
        }
        /* Custom scrollbar for a cleaner look */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        ::-webkit-scrollbar-thumb {
            background-color: #D1D5DB; /* Gray 300 */
            border-radius: 4px;
        }
        ::-webkit-scrollbar-track {
            background-color: transparent;
        }
    
        /* Course Grid */
        .courses-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 1.5rem;
            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: 160px;
            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: 1rem;
        }
    
        .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.1rem;
            font-weight: 700;
            color: #1f2937;
            margin-bottom: 0.875rem;
            line-height: 1.3;
            letter-spacing: -0.01em;
            overflow-wrap: break-word;
            word-wrap: break-word;
        }
    
        .course-title a {
            color: inherit;
            text-decoration: none;
        }
    
        .course-title a:hover {
            color: #3b82f6;
        }
    
        .course-description {
            color: #6b7280;
            font-size: 0.85rem;
            line-height: 1.4;
            margin-bottom: 1rem;
            font-weight: 400;
            overflow: hidden;
            display: -webkit-box;
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
            text-overflow: ellipsis;
        }
    
        .course-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 0.75rem;
        }
    
        .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: 1rem;
        }
    
        .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.4rem 0.6rem;
            border-radius: 8px;
            font-size: 0.8rem;
            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);
        }
    
        /* Responsive Design */
        @media (max-width: 1024px) {
            .courses-grid {
                grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
                gap: 1.75rem;
            }
        }
    
        @media (max-width: 768px) {
            .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: 1rem;
            }
    
            .course-footer {
                flex-direction: column;
                gap: 1rem;
                align-items: flex-start;
                margin-bottom: 0.75rem;
            }
    
            .course-stats {
                flex-wrap: wrap;
                width: 100%;
            }
    
            .course-actions {
                width: 100%;
            }
    
            .course-actions .btn {
                width: 100%;
                justify-content: center;
            }
        }
    
        @media (max-width: 480px) {
            .course-image-container {
                height: 200px;
            }
    
            .course-title {
                font-size: 1.2rem;
            }
    
            .course-description {
                font-size: 0.9rem;
            }
        }
    
        /* 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;
        }
    </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-16 h-screen">
            <div class="flex flex-col h-full">
                <!-- Logo/Title -->
                <div class="text-xl font-extrabold text-primary-blue mb-10 tracking-wider">
                </div>

                <!-- Navigation Links -->
                <nav class="space-y-2 flex-grow">
                    <a href="dashboard.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Home -->
                        <span class="w-5 h-5">🏠</span>
                        <span>Dashboard</span>
                    </a>
                    <a href="available_courses.php" class="flex items-center space-x-3 p-3 rounded-lg bg-primary-blue text-white font-semibold transition duration-150 shadow-md">
                        <!-- 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">

        <!-- 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">Available Courses</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>

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

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

                <!-- Search and Filters -->
                <div class="bg-white p-6 rounded-xl shadow-md mb-8">
                    <form method="GET" class="flex flex-col md:flex-row gap-4">
                        <div class="flex-1">
                            <input type="text" name="search" placeholder="Search courses..." class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-blue focus:border-transparent" value="<?php echo htmlspecialchars($search); ?>">
                        </div>
                        <div class="md:w-48">
                            <select name="category" class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-blue focus:border-transparent">
                                <option value="">All Categories</option>
                                <?php foreach ($categories as $cat): ?>
                                    <option value="<?php echo htmlspecialchars($cat['slug']); ?>" <?php echo $category === $cat['slug'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($cat['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="md:w-48">
                            <select name="level" class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-blue focus:border-transparent">
                                <option value="">All Levels</option>
                                <option value="beginner" <?php echo $level === 'beginner' ? 'selected' : ''; ?>>Beginner</option>
                                <option value="intermediate" <?php echo $level === 'intermediate' ? 'selected' : ''; ?>>Intermediate</option>
                                <option value="advanced" <?php echo $level === 'advanced' ? 'selected' : ''; ?>>Advanced</option>
                            </select>
                        </div>
                        <button type="submit" class="bg-primary-blue text-white px-6 py-3 rounded-lg font-semibold hover:bg-indigo-700">
                            Search
                        </button>
                    </form>
                </div>

                <!-- Results Header -->
                <div class="mb-6">
                    <h2 class="text-2xl font-bold text-gray-800 mb-2">Available Courses</h2>
                    <p class="text-gray-600">
                        Showing <?php echo count($courses); ?> of <?php echo $totalCourses; ?> courses
                        <?php if (!empty($search)): ?>
                            for "<strong><?php echo htmlspecialchars($search); ?></strong>"
                        <?php endif; ?>
                    </p>
                </div>

                <!-- Courses Grid -->
                <?php if (!empty($courses)): ?>
                    <div class="courses-grid">
                        <?php foreach ($courses 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/index.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/index.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, 80)); ?>...
                                    </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>

                                        <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">
                                        <button class="btn btn-primary" onclick="addToCart(<?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' : 'Add to Cart'; ?>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>

                    <!-- Pagination -->
                    <?php if ($totalPages > 1): ?>
                        <div class="flex justify-center mt-8">
                            <nav aria-label="Course pagination">
                                <ul class="flex gap-2">
                                    <?php if ($page > 1): ?>
                                        <li>
                                            <a class="flex items-center justify-center w-10 h-10 border-2 border-gray-300 bg-white text-gray-600 rounded-lg hover:border-primary-blue hover:text-primary-blue transition" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>">
                                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 18l-6-6 6-6"/></svg>
                                            </a>
                                        </li>
                                    <?php endif; ?>

                                    <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
                                        <li>
                                            <a class="flex items-center justify-center w-10 h-10 border-2 rounded-lg transition <?php echo $i === $page ? 'bg-primary-blue border-primary-blue text-white' : 'border-gray-300 bg-white text-gray-600 hover:border-primary-blue hover:text-primary-blue'; ?>" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>"><?php echo $i; ?></a>
                                        </li>
                                    <?php endfor; ?>

                                    <?php if ($page < $totalPages): ?>
                                        <li>
                                            <a class="flex items-center justify-center w-10 h-10 border-2 border-gray-300 bg-white text-gray-600 rounded-lg hover:border-primary-blue hover:text-primary-blue transition" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>">
                                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 18l6-6-6-6"/></svg>
                                            </a>
                                        </li>
                                    <?php endif; ?>
                                </ul>
                            </nav>
                        </div>
                    <?php endif; ?>
                <?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>
        </main>
    </div>

    <!-- Cart Modal -->
    <div id="cartModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden">
        <div class="flex items-center justify-center min-h-screen p-4">
            <div class="bg-white rounded-xl shadow-2xl max-w-md w-full max-h-[90vh] overflow-hidden">
                <!-- Modal Header -->
                <div class="flex items-center justify-between p-6 border-b border-gray-200">
                    <h2 class="text-xl font-bold text-gray-900">Shopping Cart</h2>
                    <button onclick="closeCartModal()" class="text-gray-400 hover:text-gray-600">
                        <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"><path d="M18 6L6 18M6 6l12 12"/></svg>
                    </button>
                </div>

                <!-- Modal Body -->
                <div id="cartContent" class="p-6 max-h-96 overflow-y-auto">
                    <!-- Cart items will be loaded here -->
                    <div class="text-center py-8">
                        <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" class="mx-auto text-gray-300 mb-4"><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>
                        <p class="text-gray-500">Your cart is empty</p>
                    </div>
                </div>

                <!-- Modal Footer -->
                <div id="cartFooter" class="border-t border-gray-200 p-6 hidden">
                    <div class="flex justify-between items-center mb-4">
                        <span class="text-lg font-semibold text-gray-900">Total:</span>
                        <span id="cartTotal" class="text-lg font-bold text-primary-blue">$0.00</span>
                    </div>
                    <button onclick="checkoutCart()" class="w-full bg-primary-blue hover:bg-indigo-700 text-white font-semibold py-3 px-4 rounded-lg transition duration-200">
                        Proceed to Checkout
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        function addToCart(courseId, courseTitle) {
            fetch('../api/cart.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'same-origin',
                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');
                    updateCartCount();
                } else {
                    showToast('Error: ' + data.error, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('An error occurred. Please try again.', 'error');
            });
        }

        function updateCartCount() {
            fetch('../api/cart.php')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const cartBadge = document.getElementById('cartCount');
                    if (cartBadge) {
                        const count = data.cart.item_count || 0;
                        cartBadge.textContent = count;
                        cartBadge.classList.toggle('hidden', count === 0);
                    }
                }
            })
            .catch(error => {
                console.error('Error updating cart count:', error);
            });
        }

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

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

        // 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">
                                <div class="flex-1">
                                    <h4 class="text-sm font-medium text-gray-800">${item.title}</h4>
                                    <p class="text-xs text-gray-500">${item.is_free ? 'Free' : formatCurrency(item.price, item.currency)}</p>
                                </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 Amount:</span>
                        <span class="text-2xl font-bold text-primary">${formatCurrency(cart.total, cart.currency)}</span>
                    </div>
                </div>

                <div class="text-center space-y-3">
                    <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>
            `;

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

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

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

        // Cart Modal Functions
        function openCartModal() {
            loadCartModal();
            document.getElementById('cartModal').classList.remove('hidden');
            document.body.style.overflow = 'hidden';
        }

        function closeCartModal() {
            document.getElementById('cartModal').classList.add('hidden');
            document.body.style.overflow = 'auto';
        }

        function loadCartModal() {
            fetch('../api/cart.php')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    renderCartItems(data.cart);
                } else {
                    showToast('Error loading cart', 'error');
                }
            })
            .catch(error => {
                console.error('Error loading cart:', error);
                showToast('Error loading cart', 'error');
            });
        }

        function renderCartItems(cart) {
            const cartContent = document.getElementById('cartContent');
            const cartFooter = document.getElementById('cartFooter');
            const cartTotal = document.getElementById('cartTotal');

            if (!cart.items || cart.items.length === 0) {
                cartContent.innerHTML = `
                    <div class="text-center py-8">
                        <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" class="mx-auto text-gray-300 mb-4"><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>
                        <p class="text-gray-500">Your cart is empty</p>
                    </div>
                `;
                cartFooter.classList.add('hidden');
                return;
            }

            let itemsHtml = '';
            cart.items.forEach(item => {
                const price = item.is_free ? 'Free' : `$${parseFloat(item.price).toFixed(2)}`;
                itemsHtml += `
                    <div class="flex items-center space-x-4 py-4 border-b border-gray-100 last:border-b-0">
                        <img src="${item.thumbnail || 'https://placehold.co/60x40/94a3b8/ffffff?text=Course'}" alt="${item.title}" class="w-16 h-10 object-cover rounded">
                        <div class="flex-1">
                            <h4 class="font-medium text-gray-900 text-sm leading-tight">${item.title}</h4>
                            <p class="text-primary-blue font-semibold text-sm">${price}</p>
                        </div>
                        <button onclick="removeFromCart(${item.item_id})" class="text-red-500 hover:text-red-700 p-1">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
                        </button>
                    </div>
                `;
            });

            cartContent.innerHTML = itemsHtml;
            cartTotal.textContent = `$${parseFloat(cart.total).toFixed(2)}`;
            cartFooter.classList.remove('hidden');
        }

        function removeFromCart(courseId) {
            fetch(`../api/cart.php?course_id=${courseId}`, {
                method: 'DELETE'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast('Course removed from cart', 'success');
                    loadCartModal(); // Reload cart content
                    updateCartCount(); // Update cart badge
                } else {
                    showToast('Error removing course: ' + data.error, 'error');
                }
            })
            .catch(error => {
                console.error('Error removing from cart:', error);
                showToast('Error removing course', 'error');
            });
        }

        function checkoutCart() {
            fetch('../api/cart.php', {
                method: 'PUT'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    if (data.payment_required) {
                        // Check if user is logged in
                        <?php if (!isLoggedIn()): ?>
                        // Redirect to login for non-authenticated users
                        const currentUrl = encodeURIComponent(window.location.href);
                        window.location.href = '../login.php?redirect=' + currentUrl;
                        return;
                        <?php endif; ?>

                        // Redirect to payment page for authenticated users
                        window.location.href = 'checkout.php';
                    } else if (data.enrolled_courses) {
                        showToast(data.message, 'success');
                        closeCartModal();
                        updateCartCount();
                        // Optionally redirect to dashboard
                        setTimeout(() => {
                            window.location.href = 'dashboard.php';
                        }, 2000);
                    }
                } else {
                    if (data.auth_required) {
                        // User needs to login
                        const currentUrl = encodeURIComponent(window.location.href);
                        window.location.href = '../login.php?redirect=' + currentUrl;
                    } else {
                        showToast('Checkout error: ' + data.error, 'error');
                    }
                }
            })
            .catch(error => {
                console.error('Error during checkout:', error);
                showToast('Error during checkout', 'error');
            });
        }

        // Close modal when clicking outside
        document.getElementById('cartModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeCartModal();
            }
        });

        // Mobile Menu Functionality
        const mobileMenuButton = document.getElementById('mobileMenuButton');
        const closeMobileMenu = document.getElementById('closeMobileMenu');
        const mobileMenu = document.getElementById('mobileMenu');

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

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

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

