<?php
require_once '../includes/middleware.php';
require_once '../config/database.php';
require_once '../config/currency.php';
require_once '../includes/functions.php';
$db = getDB();

// Get filter parameters
$category = $_GET['category'] ?? '';
$level = $_GET['level'] ?? '';
$search = $_GET['search'] ?? '';
$sort = $_GET['sort'] ?? 'newest';
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 12;

// Build query
$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 = [];

// 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
switch ($sort) {
    case 'oldest':
        $query .= " ORDER BY c.created_at ASC";
        break;
    case 'popular':
        $query .= " ORDER BY enrollment_count DESC, average_rating DESC";
        break;
    case 'rating':
        $query .= " ORDER BY average_rating DESC, enrollment_count DESC";
        break;
    case 'price_low':
        $query .= " ORDER BY c.price ASC";
        break;
    case 'price_high':
        $query .= " ORDER BY c.price DESC";
        break;
    default: // newest
        $query .= " ORDER BY c.created_at DESC";
        break;
}

$query .= " ";

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

// Add the same filters to count query
$countParams = [];
if (!empty($category)) {
    $countQuery .= " AND cat.slug = ?";
    $countParams[] = $category;
}

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

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

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

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

$page_title = 'Course Catalog';
?>

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

<script src="https://cdn.tailwindcss.com"></script>

<!-- Catalogue Hero Section -->
        <div class="bg-indigo-600 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 Course Catalogue</h2>
                <p class="text-xl opacity-90">Find the perfect course to advance your career and skills.</p>
                <div class="mt-8 max-w-2xl mx-auto">
                    <!-- Search Input -->
                    <form method="GET" class="flex">
                        <input type="text" name="search" placeholder="Search courses, instructors, or keywords..." 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>

        <!-- Course 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">
                            <!-- Category Filter -->
                            <div class="mb-6">
                                <label for="categoryFilter" class="block text-sm font-semibold text-gray-700 mb-2">Category</label>
                                <select id="categoryFilter" name="category" class="w-full p-3 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500">
                                    <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>

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

                            <!-- 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="rating" <?php echo $sort === 'rating' ? 'selected' : ''; ?>>Highest Rated</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>

                <!-- Course 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 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>

                    <!-- Course Grid -->
                    <?php if (empty($courses)): ?>
                        <div id="noResults" class="text-center py-12 bg-white rounded-xl shadow-lg">
                            <p class="text-xl text-gray-600 font-semibold">No courses 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 Courses
                            </a>
                        </div>
                    <?php else: ?>
                        <div id="courseList" class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-6">
                            <?php foreach ($courses as $index => $course): ?>
                                <div class="course-card bg-white rounded-xl shadow-xl overflow-hidden flex flex-col border border-gray-100">
                                    <div class="aspect-video w-full overflow-hidden">
                                        <img src="<?php echo htmlspecialchars($course['thumbnail'] ?: 'https://placehold.co/600x400/94a3b8/ffffff?text=Course+Image'); ?>" alt="<?php echo htmlspecialchars($course['title']); ?> thumbnail" class="w-full h-full object-cover">
                                    </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" style="background-color: <?php echo htmlspecialchars($course['category_color'] ?? '#10b981'); ?>">
                                                <?php echo htmlspecialchars($course['category_name'] ?? 'General'); ?>
                                            </span>
                                            <span class="text-xs font-medium text-gray-500 bg-gray-100 px-3 py-1 rounded-full"><?php echo ucfirst($course['level']); ?></span>
                                        </div>

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

                                        <div class="flex items-center space-x-1 mb-4">
                                            <?php if ($course['average_rating']): ?>
                                                <?php for ($i = 1; $i <= 5; $i++): ?>
                                                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 <?php echo $i <= round($course['average_rating']) ? 'star-filled' : 'star-empty'; ?> inline-block" viewBox="0 0 20 20" fill="currentColor">
                                                        <path d="M9.049 2.927c.3-.921 1.65-.921 1.95 0l2.121 6.495 6.83.504c.95.07.72 1.34-0.19 1.91l-5.26 3.73 2.01 6.82c.27 1.25-1.07 1.83-1.63 1.15L10 16.14l-5.83 3.65c-.56.35-1.89-0.27-1.62-1.44l2.01-6.82-5.26-3.73c-.92-.57-.92-1.92 0-2.02l6.83-.504L9.049 2.927z"/>
                                                    </svg>
                                                <?php endfor; ?>
                                                <span class="text-sm font-semibold text-gray-800 ml-1"><?php echo number_format($course['average_rating'], 1); ?></span>
                                                <span class="text-xs text-gray-500">(<?php echo $course['review_count']; ?> reviews)</span>
                                            <?php else: ?>
                                                <span class="text-xs text-gray-500 italic">No reviews yet</span>
                                            <?php endif; ?>
                                        </div>

                                        <div class="flex justify-between items-center pt-4 border-t border-gray-100">
                                            <span class="text-lg <?php echo $course['is_free'] ? 'text-green-600 font-extrabold' : 'text-indigo-600 font-extrabold'; ?>">
                                                <?php echo $course['is_free'] ? 'Free' : formatCurrency($course['price'], $course['currency']); ?>
                                            </span>
                                            <button
                                                onclick="addToCart(<?php echo $course['id']; ?>, '<?php echo addslashes($course['title']); ?>')"
                                                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 $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-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 addToCart(courseId, courseTitle) {
            fetch('../api/cart.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ course_id: courseId })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Show success message
                    let message = courseTitle + ' has been added to your cart!';
                    if (data.already_in_cart) {
                        message = courseTitle + ' is already in your cart!';
                    }
                    showToast(message, 'success');
                    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)}`;
                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-indigo-600 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 = '../student/checkout.php';
                    } else if (data.enrolled_courses) {
                        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'; ?>