<?php
require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../config/currency.php';
require_once '../includes/functions.php';

$db = getDB();

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

$page_title = 'Exam Catalog';
$use_tailwind = true;
?>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Exam Catalog - Mutalex Academy</title>
    <!-- Load Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Configure Tailwind to use Inter font and custom colors -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'primary-blue': '#007bff',
                        'nav-text': '#555',
                        'light-border': '#eee',
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style>
        /* Custom styles for mobile menu toggle */
        @media (min-width: 768px) {
            #mobile-menu {
                display: none !important;
            }
        }
        /* Style for the active link border for visual fidelity */
        .nav-link.active {
            font-weight: 600;
            color: theme('colors.primary-blue');
            border-bottom: 2px solid theme('colors.primary-blue');
            padding-bottom: 8px; /* Adjust padding to make space for the border */
        }
        /* Mobile menu button icon transition */
        .menu-icon {
            cursor: pointer;
            display: flex;
            flex-direction: column;
            justify-content: space-around;
            width: 25px;
            height: 25px;
            transition: all 0.3s ease;
        }
        .menu-icon div {
            width: 100%;
            height: 3px;
            background-color: #333;
            border-radius: 2px;
            transition: all 0.3s ease;
        }

        /* Rating Stars */
        .rating .fas.fa-star {
            color: #D1D5DB;
            transition: all 0.3s ease;
        }
        .rating .fas.fa-star.filled {
            color: #F59E0B;
            filter: drop-shadow(0 0 2px rgba(245, 158, 11, 0.3));
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">

    <!-- Header Navigation Bar -->
    <header class="bg-white shadow-md sticky top-0 z-50 border-b border-light-border">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between items-center h-16">
                <!-- Logo -->
                <a href="../home" class="flex-shrink-0 flex items-center gap-3">
                    <?php
                    $siteLogo = getSiteSetting('site_logo') ?: 'fas fa-graduation-cap';
                    $siteName = getSiteSetting('site_name') ?: 'Mutalex Academy';

                    if (strpos($siteLogo, 'assets/images/') === 0) {
                        echo '<img src="../' . htmlspecialchars($siteLogo) . '" alt="' . htmlspecialchars($siteName) . '" class="h-10 w-auto">';
                    } else {
                        echo '<i class="' . htmlspecialchars($siteLogo) . ' text-2xl text-primary-blue"></i>';
                    }
                    ?>
                    <span class="text-2xl font-bold tracking-tight text-purple-700">
                        <?php echo htmlspecialchars($siteName); ?>
                    </span>
                </a>

                <!-- Desktop Navigation Links -->
                <nav class="hidden md:flex space-x-6 lg:space-x-8 items-center">
                    <!-- 'Home' is now the active link for the main blog page -->
                    <a href="../home" class="nav-link text-nav-text hover:text-primary-blue transition duration-150">Home</a>
                    <a href="../courses/catalog.php" class="nav-link text-nav-text hover:text-primary-blue transition duration-150">Courses</a>

                    <!-- Login Button - Distinctive Style -->
                    <a href="../login" class="px-4 py-2 text-white bg-primary-blue rounded-lg shadow-md hover:bg-blue-600 transition duration-150">
                        Login
                    </a>
                </nav>

                <!-- Mobile Menu Button -->
                <div class="md:hidden">
                    <button id="menu-button" type="button" class="text-gray-500 hover:text-gray-900 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-blue p-2 rounded-md">
                        <div class="menu-icon">
                            <div class="bar1"></div>
                            <div class="bar2"></div>
                            <div class="bar3"></div>
                        </div>
                    </button>
                </div>
            </div>
        </div>

        <!-- Mobile Menu (Hidden by default) -->
        <div id="mobile-menu" class="hidden md:hidden bg-white border-t border-light-border">
            <div class="px-2 pt-2 pb-3 space-y-1 sm:px-3">
                <a href="../home" class="block px-3 py-2 rounded-md text-base font-medium text-nav-text hover:bg-gray-100">Home</a>
                <a href="../courses/catalog.php" class="block px-3 py-2 rounded-md text-base font-medium text-nav-text hover:bg-gray-100">Courses</a>
                <a href="../login" class="block w-full text-center mt-2 px-4 py-2 text-white bg-primary-blue rounded-lg font-medium hover:bg-blue-600 transition duration-150">Login</a>
            </div>
        </div>
    </header>
 
        <!-- Exam Catalogue Hero Section -->
        <div style="background: #60B84D; margin-top: 80px;" class="py-16 text-white">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
                <h2 class="text-5xl font-extrabold mb-3">Explore Our Exam Catalogue</h2>
                <p class="text-xl opacity-90">Test your knowledge with our comprehensive exam collection.</p>
                <div class="mt-8 max-w-2xl mx-auto">
                    <!-- Search Input -->
                    <form method="GET" class="flex">
                        <input type="text" name="search" placeholder="Search exams, instructors, or courses..." class="flex-1 p-4 rounded-l-xl text-gray-900 shadow-xl focus:ring-2 focus:ring-white focus:outline-none" value="<?php echo htmlspecialchars($search); ?>">
                        <button type="submit" class="bg-indigo-700 hover:bg-indigo-800 px-6 rounded-r-xl text-white font-semibold transition">
                            <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>
            </div>
        </div>

        <!-- Exam Listings and Filters -->
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
            <div class="lg:grid lg:grid-cols-5 lg:gap-8">

                <!-- Filters Column -->
                <aside class="lg:col-span-1 mb-8 lg:mb-0">
                    <div class="bg-white p-6 rounded-xl shadow-lg sticky top-24 border border-gray-100">
                        <h3 class="text-xl font-bold text-gray-800 mb-6 border-b pb-3">Filter Options</h3>

                        <form method="GET">
                            <!-- Exam Type Filter -->
                            <div class="mb-6">
                                <label for="examTypeFilter" class="block text-sm font-semibold text-gray-700 mb-2">Exam Type</label>
                                <select id="examTypeFilter" name="exam_type" class="w-full p-3 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500">
                                    <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>

                            <!-- Sorting -->
                            <div class="mb-0">
                                <label for="sortOrder" class="block text-sm font-semibold text-gray-700 mb-2">Sort By</label>
                                <select id="sortOrder" name="sort" class="w-full p-3 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500">
                                    <option value="newest" <?php echo $sort === 'newest' ? 'selected' : ''; ?>>Newest 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="w-full mt-6 bg-indigo-600 hover:bg-indigo-700 text-white font-semibold py-3 px-4 rounded-lg transition duration-200">
                                Apply Filters
                            </button>
                        </form>
                    </div>
                </aside>

                <!-- Exam Cards Column -->
                <div class="lg:col-span-4">
                    <!-- Results Header -->
                    <div class="mb-6">
                        <h2 class="text-3xl font-bold text-gray-800 mb-2">Available Exams</h2>
                        <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 id="noResults" class="text-center py-12 bg-white rounded-xl shadow-lg">
                            <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-indigo-600 text-white px-6 py-3 rounded-lg font-semibold hover:bg-indigo-700 transition">
                                Browse All Exams
                            </a>
                        </div>
                    <?php else: ?>
                        <div id="examList" class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-6">
                            <?php foreach ($exams as $index => $exam): ?>
                                <div class="exam-card bg-white rounded-xl shadow-xl overflow-hidden flex flex-col border border-gray-100">
                                    <div class="aspect-video w-full bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center">
                                        <div class="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>
                                    <div class="p-6 flex flex-col flex-grow">
                                        <div class="flex justify-between items-start mb-3">
                                            <span class="text-white text-xs font-semibold px-3 py-1 rounded-full uppercase tracking-wider shadow-md bg-indigo-600">
                                                <?php echo ucfirst($exam['exam_type']); ?>
                                            </span>
                                            <?php if ($exam['course_title']): ?>
                                                <span class="text-xs font-medium text-gray-500 bg-blue-100 px-3 py-1 rounded-full"><?php echo htmlspecialchars(substr($exam['course_title'], 0, 20)); ?>...</span>
                                            <?php endif; ?>
                                        </div>

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

                                        <?php if ($exam['average_rating']): ?>
                                            <div class="flex items-center gap-2 mb-4">
                                                <div class="rating flex gap-1">
                                                    <?php for ($i = 1; $i <= 5; $i++): ?>
                                                        <i class="fas fa-star text-sm <?php echo $i <= round($exam['average_rating']) ? 'filled' : ''; ?>"></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']; ?> reviews)</span>
                                            </div>
                                        <?php endif; ?>

                                        <div class="flex items-center space-x-4 mb-4 text-sm text-gray-600">
                                            <div class="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="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-indigo-600 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-indigo-600 hover:bg-indigo-700 text-white text-sm font-semibold py-2 px-4 rounded-lg shadow-lg shadow-indigo-200 transition duration-200 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-indigo-500 hover:text-indigo-500 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-indigo-600 border-indigo-600 text-white' : 'border-gray-300 bg-white text-gray-600 hover:border-indigo-500 hover:text-indigo-500'; ?>" 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-indigo-500 hover:text-indigo-500 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>
            </div>
        </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-indigo-600">$0.00</span>
                    </div>
                    <button onclick="checkoutCart()" class="w-full bg-indigo-600 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 takeExam(examId) {
            <?php if (!isLoggedIn()): ?>
            const currentUrl = encodeURIComponent(window.location.href);
            window.location.href = '../login.php?redirect=' + currentUrl;
            return;
            <?php endif; ?>
            window.location.href = '../student/exams/take.php?id=' + examId;
        }
        function addToCart(itemId, itemTitle, itemType = 'course') {
            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) {
                    // Show success message
                    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('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);
        }

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

        // 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)}`;
                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-indigo-500 to-purple-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-indigo-600 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;
            cartTotal.textContent = `$${parseFloat(cart.total).toFixed(2)}`;
            cartFooter.classList.remove('hidden');
        }

        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(); // Reload cart content
                    updateCartCount(); // Update cart badge
                } 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) {
                        // 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 = '../student/checkout.php';
                    } else if (data.enrolled_items) {
                        showToast(data.message, 'success');
                        closeCartModal();
                        updateCartCount();
                        // Optionally redirect to dashboard
                        setTimeout(() => {
                            window.location.href = '../student/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();
            }
        });
    </script>

<?php include '../includes/footer.php'; ?>