<?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'] ?? '';
$exam_type = $_GET['exam_type'] ?? '';
$search = $_GET['search'] ?? '';
$sort = $_GET['sort'] ?? 'newest';
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 12;

// Build query
$query = "SELECT DISTINCT e.id, e.title, e.slug, e.description, e.price, e.currency, e.is_free,
             e.exam_type, e.total_points, e.passing_score, e.time_limit, e.max_attempts,
             e.status, e.created_at, e.updated_at,
             e.instructor_id, e.course_id,
             c.title as course_title,
             u.username as instructor_name, up.first_name, up.last_name,
             COALESCE(stats.attempt_count, 0) as attempt_count,
             AVG(er.rating) as average_rating,
             COUNT(DISTINCT er.id) as review_count
      FROM exams e
      LEFT JOIN courses c ON e.course_id = c.id
      LEFT JOIN users u ON e.instructor_id = u.id
      LEFT JOIN user_profiles up ON u.id = up.user_id
      LEFT JOIN (
          SELECT e2.id as exam_id,
                 COUNT(DISTINCT ea.student_id) as attempt_count
          FROM exams e2
          LEFT JOIN exam_attempts ea ON e2.id = ea.exam_id
          GROUP BY e2.id
      ) stats ON e.id = stats.exam_id
      LEFT JOIN exam_reviews er ON e.id = er.exam_id AND er.status = 'approved'
      WHERE e.status = 'published'
      GROUP BY e.id";

$params = [];

// Get total count for pagination
$countQuery = "SELECT COUNT(DISTINCT e.id) as total
                FROM exams e
                LEFT JOIN courses c ON e.course_id = c.id
                WHERE e.status = 'published'";

// Add filters
if (!empty($exam_type)) {
    $query .= " AND e.exam_type = ?";
    $countQuery .= " AND e.exam_type = ?";
    $params[] = $exam_type;
}

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

// Add sorting
switch ($sort) {
    case 'oldest':
        $query .= " ORDER BY e.created_at ASC";
        break;
    case 'popular':
        $query .= " ORDER BY attempt_count DESC";
        break;
    case 'price_low':
        $query .= " ORDER BY e.price ASC";
        break;
    case 'price_high':
        $query .= " ORDER BY e.price DESC";
        break;
    default: // newest
        $query .= " ORDER BY e.created_at DESC";
        break;
}

$query .= " ";

// Add the same filters to count query
$countParams = $params;

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

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

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

// Get exam types for filter
$examTypes = ['quiz', 'midterm', 'final', 'practice', 'certification'];

// Get user exam attempts for logged-in users
$userAttempts = [];
if (isLoggedIn()) {
    $stmt = $db->prepare("SELECT exam_id, status FROM exam_attempts WHERE student_id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $userAttempts = $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>Exam Catalog | <?php echo htmlspecialchars($user['username'] ?? 'Student'); ?> - 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;
        }

        /* Home.php Exam Cards - Adapted for Catalog (Emerald Green Theme) */
        .available-exams-section {
            padding: 4rem 0;
            background: #ffffff;
        }
        .exams-header {
            text-align: center;
            margin-bottom: 3rem;
        }
        .exams-title {
            font-size: 2.8rem;
            font-weight: 800;
            color: #1f2937;
            margin-bottom: 1rem;
            letter-spacing: -0.02em;
            line-height: 1.2;
        }
        .exams-subtitle {
            color: #6b7280;
            font-size: 1.1rem;
            margin-bottom: 2rem;
            max-width: 600px;
            margin-left: auto;
            margin-right: auto;
        }
        .exams-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 1.5rem;
            margin-bottom: 3rem;
        }
        .exam-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: examCardFadeIn 0.6s ease-out both;
        }
        .exam-card[style*="--card-index"] {
            animation-delay: calc(var(--card-index, 0) * 0.1s);
        }
        .exam-card:hover {
            transform: translateY(-12px) scale(1.02);
            box-shadow: 0 25px 50px rgba(0, 0, 0, 0.15);
            border-color: #e5e7eb;
        }
        @keyframes examCardFadeIn {
            from { opacity: 0; transform: translateY(30px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .exam-image-container {
            position: relative;
            height: 160px;
            overflow: hidden;
        }
        .exam-image-placeholder {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 3rem;
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        }
        .exam-badges {
            position: absolute;
            top: 12px;
            left: 12px;
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }
        .badge-type {
            background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
            color: white;
            padding: 0.375rem 0.75rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        .badge-free {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
        }
        .exam-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(16, 185, 129, 0.9);
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        .exam-card:hover .exam-overlay { opacity: 1; }
        .exam-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;
        }
        .exam-link:hover { background: rgba(255, 255, 255, 0.3); }
        .exam-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 0.75rem;
        }
        .exam-duration, .exam-passing {
            display: flex;
            align-items: center;
            gap: 0.375rem;
            color: #6b7280;
            font-size: 0.8rem;
            font-weight: 500;
        }
    </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 text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Home -->
                        <span class="w-5 h-5">🏠</span>
                        <span>Dashboard</span>
                    </a>
                    <a href="../available_courses.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Catalog -->
                        <span class="w-5 h-5">📖</span>
                        <span>View All Courses</span>
                    </a>
                    <a href="../courses.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Book -->
                        <span class="w-5 h-5">📚</span>
                        <span>My Courses</span>
                    </a>
                    <a href="../exams.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Exam -->
                        <span class="w-5 h-5">📝</span>
                        <span>My Exam</span>
                    </a>
                    <a href="catalog.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: 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="#" 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">Exam Catalog</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">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 text-text-dark hover:bg-accent-subtle">🏠 Dashboard</a>
                    <a href="../available_courses.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📖 View All Courses</a>
                    <a href="../courses.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📚 My Courses</a>
                    <a href="../exams.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📝 My Exam</a>
                    <a href="catalog.php" class="block p-3 rounded-lg bg-primary-blue text-white font-semibold">📋 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="#" 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 Filter Bar -->
                <div class="bg-white p-6 rounded-xl shadow-md mb-8">
                    <form method="GET" class="flex flex-col md:flex-row gap-4">
                        <!-- Search Input -->
                        <div class="flex-1">
                            <input type="text" name="search" placeholder="Search exams, instructors, or courses..." class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-blue focus:border-transparent outline-none" value="<?php echo htmlspecialchars($search); ?>">
                        </div>
                        
                        <!-- Exam Type Filter -->
                        <div class="w-full md:w-48">
                            <select name="exam_type" class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-blue focus:border-transparent outline-none">
                                <option value="">All Types</option>
                                <option value="quiz" <?php echo $exam_type === 'quiz' ? 'selected' : ''; ?>>Quiz</option>
                                <option value="midterm" <?php echo $exam_type === 'midterm' ? 'selected' : ''; ?>>Midterm</option>
                                <option value="final" <?php echo $exam_type === 'final' ? 'selected' : ''; ?>>Final</option>
                                <option value="practice" <?php echo $exam_type === 'practice' ? 'selected' : ''; ?>>Practice</option>
                                <option value="certification" <?php echo $exam_type === 'certification' ? 'selected' : ''; ?>>Certification</option>
                            </select>
                        </div>

                        <!-- Sort By -->
                        <div class="w-full md:w-48">
                            <select name="sort" class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-blue focus:border-transparent outline-none">
                                <option value="newest" <?php echo $sort === 'newest' ? 'selected' : ''; ?>>Newest First</option>
                                <option value="oldest" <?php echo $sort === 'oldest' ? 'selected' : ''; ?>>Oldest First</option>
                                <option value="popular" <?php echo $sort === 'popular' ? 'selected' : ''; ?>>Most Popular</option>
                                <option value="price_low" <?php echo $sort === 'price_low' ? 'selected' : ''; ?>>Price: Low to High</option>
                                <option value="price_high" <?php echo $sort === 'price_high' ? 'selected' : ''; ?>>Price: High to Low</option>
                            </select>
                        </div>

                        <button type="submit" class="bg-primary-blue text-white px-6 py-3 rounded-lg font-medium hover:bg-indigo-700 transition duration-150">
                            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
                        </button>
                    </form>
                </div>

                <!-- Results Header - Matching home.php -->
                <div class="mb-6 exams-header">
                    <h2 class="exams-title text-3xl font-bold text-gray-800 mb-2"><?php echo htmlspecialchars(getSiteSetting('available_exams_title') ?: 'Available Exams'); ?></h2>
                    <p class="exams-subtitle text-gray-600 mb-4"><?php echo htmlspecialchars(getSiteSetting('available_exams_subtitle') ?: 'Test your knowledge with our comprehensive exam collection'); ?></p>
                    <p class="text-gray-600">
                        Showing <?php echo count($exams); ?> of <?php echo $totalExams; ?> exams
                        <?php if (!empty($search)): ?>
                            for "<strong><?php echo htmlspecialchars($search); ?></strong>"
                        <?php endif; ?>
                    </p>
                </div>

                <!-- Exam Grid -->
                <?php if (empty($exams)): ?>
                    <div class="text-center py-12 bg-white rounded-xl shadow-lg">
                        <i class="fas fa-file-alt text-gray-400 mx-auto h-16 w-16 mb-4"></i>
                        <p class="text-xl text-gray-600 font-semibold">No exams match your current filters.</p>
                        <p class="text-gray-500 mt-2">Try adjusting your search query or filters.</p>
                        <a href="catalog.php" class="inline-block mt-4 bg-primary-blue text-white px-6 py-3 rounded-lg font-semibold hover:bg-indigo-700 transition">
                            Browse All Exams
                        </a>
                    </div>
                <?php else: ?>
                    <div class="exams-grid grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                        <?php foreach ($exams as $index => $exam): ?>
                            <div class="exam-card bg-white rounded-xl shadow-lg overflow-hidden flex flex-col" style="--card-index: <?php echo $index; ?>">
        <div class="exam-image-container relative h-32 bg-gradient-to-br from-green-500 to-green-600 flex items-center justify-center">
                                    <div class="exam-image-placeholder text-white text-center">
                                        <i class="fas fa-file-alt text-4xl mb-2"></i>
                                        <p class="text-sm font-semibold"><?php echo ucfirst($exam['exam_type']); ?></p>
                                    </div>
                                    <div class="exam-badges">
                                        <span class="badge-type px-2 py-1 text-xs font-medium rounded-full">
                                            <?php echo ucfirst($exam['exam_type']); ?>
                                        </span>
                                    </div>
                                    <div class="exam-overlay">
                                        <a href="#" class="exam-link">
                                            <i class="fas fa-eye"></i>
                                            View Exam
                                        </a>
                                    </div>
                                </div>
                                <div class="p-4 flex flex-col flex-grow">
                                    <?php if ($exam['course_title']): ?>
                                        <span class="text-xs font-medium text-gray-500 bg-blue-100 px-3 py-1 rounded-full mb-2 inline-block w-fit"><?php echo htmlspecialchars(substr($exam['course_title'], 0, 30)); ?></span>
                                    <?php endif; ?>

                                    <h3 class="text-base font-semibold text-gray-800 mb-2 leading-snug">
                                        <?php echo htmlspecialchars($exam['title']); ?>
                                    </h3>
                                    <p class="text-sm text-gray-600 flex-grow mb-4">
                                        <?php echo htmlspecialchars(substr($exam['description'] ?? 'No description available', 0, 100)); ?>...
                                    </p>

                                    <?php if ($exam['average_rating']): ?>
                                        <div class="flex items-center gap-2 mb-4">
                                            <div class="flex gap-1">
                                                <?php for ($i = 1; $i <= 5; $i++): ?>
                                                    <i class="fas fa-star text-sm <?php echo $i <= round($exam['average_rating']) ? 'text-yellow-400' : 'text-gray-300'; ?>"></i>
                                                <?php endfor; ?>
                                            </div>
                                            <span class="text-sm font-bold text-gray-700"><?php echo number_format($exam['average_rating'], 1); ?></span>
                                            <span class="text-sm text-gray-600">(<?php echo $exam['review_count']; ?>)</span>
                                        </div>
                                    <?php endif; ?>

                                    <div class="exam-meta flex items-center space-x-4 mb-4 text-sm text-gray-600">
                                        <div class="exam-duration flex items-center">
                                            <i class="fas fa-clock mr-1"></i>
                                            <span><?php echo $exam['time_limit'] ? $exam['time_limit'] . ' min' : 'No limit'; ?></span>
                                        </div>
                                        <div class="exam-passing flex items-center">
                                            <i class="fas fa-trophy mr-1"></i>
                                            <span><?php echo $exam['passing_score']; ?>%</span>
                                        </div>
                                    </div>

                                    <div class="flex justify-between items-center pt-4 border-t border-gray-100">
                                        <span class="text-lg <?php echo $exam['is_free'] ? 'text-green-600 font-extrabold' : 'text-primary-blue font-extrabold'; ?>">
                                            <?php echo $exam['is_free'] ? 'Free' : formatCurrency($exam['price'], $exam['currency']); ?>
                                        </span>
                                        <button
                                            onclick="<?php echo $exam['is_free'] ? 'takeExam(' . $exam['id'] . ')' : 'addToCart(' . $exam['id'] . ', \'' . addslashes($exam['title']) . '\', \'exam\')'; ?>"
                                            class="bg-primary-blue hover:bg-indigo-700 text-white text-sm font-semibold py-2 px-4 rounded-lg shadow-lg transition duration-150 flex items-center"
                                        >
                                            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" viewBox="0 0 20 20" fill="currentColor">
                                                <path fill-rule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clip-rule="evenodd" />
                                            </svg>
                                            <?php echo $exam['is_free'] ? 'Take Exam' : '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="Exam 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 endif; ?>
            </div>
        </main>
    </div>

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

                <div id="cartModalContent">
                    <!-- Cart content will be loaded here -->
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript for Mobile Menu Functionality -->
    <script>
        const mobileMenuButton = document.getElementById('mobileMenuButton');
        const closeMobileMenu = document.getElementById('closeMobileMenu');
        const mobileMenu = document.getElementById('mobileMenu');

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

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

            // Close menu when a link is clicked
            mobileMenu.querySelectorAll('a').forEach(link => {
                link.addEventListener('click', () => {
                    mobileMenu.classList.add('-translate-x-full');
                });
            });
        }

        function takeExam(examId) {
            window.location.href = '../exams/take.php?id=' + examId;
        }

        function addToCart(itemId, itemTitle, itemType = 'exam') {
            fetch('../../api/cart.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ item_id: itemId, item_type: itemType })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    let message = itemTitle + ' has been added to your cart!';
                    if (data.already_in_cart) {
                        message = itemTitle + ' 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('dashboard-cart-count');
                    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);
        }

        // Update cart count on page load
        document.addEventListener('DOMContentLoaded', function() {
            updateCartCount();
        });

        // Cart Modal Functions
        function showDashboardCheckoutModal() {
            loadCartModal();
            const modal = document.getElementById('cartModal');
            modal.classList.remove('hidden');
            modal.classList.add('flex');
            document.body.style.overflow = 'hidden';
        }

        function closeCartModal() {
            const modal = document.getElementById('cartModal');
            modal.classList.add('hidden');
            modal.classList.remove('flex');
            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('cartModalContent');

            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>
                `;
                return;
            }

            let itemsHtml = '';
            cart.items.forEach(item => {
                const price = item.is_free ? 'Free' : `$${parseFloat(item.price).toFixed(2)}`;
                const itemType = item.item_type || 'course';
                itemsHtml += `
                    <div class="flex items-center space-x-4 py-4 border-b border-gray-100 last:border-b-0">
                        <div class="w-16 h-10 bg-gradient-to-br from-primary-blue to-indigo-600 rounded flex items-center justify-center text-white text-xs font-semibold">
                            ${itemType === 'exam' ? 'EXAM' : 'COURSE'}
                        </div>
                        <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}, '${itemType}')" 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}
                <div class="flex justify-between items-center mt-6 pt-4 border-t border-gray-200">
                    <span class="text-lg font-semibold text-gray-900">Total:</span>
                    <span class="text-lg font-bold text-primary-blue">$${parseFloat(cart.total).toFixed(2)}</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 mt-4">
                    Proceed to Checkout
                </button>
            `;
        }

        function removeFromCart(itemId, itemType = 'course') {
            fetch(`../../api/cart.php?item_id=${itemId}&item_type=${itemType}`, {
                method: 'DELETE'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast('Item removed from cart', 'success');
                    loadCartModal();
                    updateCartCount();
                } else {
                    showToast('Error removing item: ' + data.error, 'error');
                }
            })
            .catch(error => {
                console.error('Error removing from cart:', error);
                showToast('Error removing item', 'error');
            });
        }

        function checkoutCart() {
            fetch('../../api/cart.php', {
                method: 'PUT'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    if (data.payment_required) {
                        window.location.href = '../checkout.php';
                    } else if (data.enrolled_items) {
                        showToast(data.message, 'success');
                        closeCartModal();
                        updateCartCount();
                        setTimeout(() => {
                            window.location.href = '../dashboard.php';
                        }, 2000);
                    }
                } else {
                    if (data.auth_required) {
                        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
        const cartModal = document.getElementById('cartModal');
        if (cartModal) {
            cartModal.addEventListener('click', function(e) {
                if (e.target === this) {
                    closeCartModal();
                }
            });
        }

        // Add escape key handler
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                closeCartModal();
            }
        });
    </script>

</body>
</html>
