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

$db = getDB();

// Get user ID if logged in
$userId = $_SESSION['user_id'] ?? null;
$user = getUserContext();

// Get cart contents directly from database
$cartItems = [];
$cartTotal = 0.00;
$cartCurrency = 'USD';
if ($userId) {
    $stmt = $db->prepare("
        SELECT ci.*,
               COALESCE(c.title, e.title) as title,
               COALESCE(c.price, e.price) as price,
               COALESCE(c.currency, e.currency) as currency,
               COALESCE(c.is_free, e.is_free) as is_free,
               COALESCE(c.thumbnail, NULL) as thumbnail,
               COALESCE(c.max_students, NULL) as max_students,
               ci.item_type
        FROM cart_items ci
        LEFT JOIN courses c ON ci.item_id = c.id AND ci.item_type = 'course'
        LEFT JOIN exams e ON ci.item_id = e.id AND ci.item_type = 'exam'
        WHERE ci.user_id = ?
        ORDER BY ci.created_at ASC
    ");
    $stmt->execute([$userId]);
    $cartItems = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($cartItems as $item) {
        if (!$item['is_free']) {
            $cartTotal += floatval($item['price']);
            $cartCurrency = $item['currency'];
        }
    }
}
$cart = ['items' => $cartItems, 'total' => $cartTotal, 'currency' => $cartCurrency, 'item_count' => count($cartItems)];

$page_title = 'Shopping Cart';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($page_title ?? 'Shopping Cart'); ?> | Mutalex Academy</title>
    <!-- Load Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Set up Tailwind configuration -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'primary-blue': '#1E3A8A',
                        'background-light': '#F8FAFC',
                        'text-dark': '#1F2937',
                        'accent-subtle': '#E5E7EB',
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style>
        html, body {
            height: 100%;
        }
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        ::-webkit-scrollbar-thumb {
            background-color: #D1D5DB;
            border-radius: 4px;
        }
        ::-webkit-scrollbar-track {
            background-color: transparent;
        }
        @keyframes fade-in { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
        .animate-fade-in { animation: fade-in 0.4s ease-out forwards; }
    </style>
</head>
<body class="bg-background-light font-sans text-text-dark min-h-screen flex flex-col">

    <!-- Top Bar Header -->
    <header class="bg-white shadow-sm fixed top-0 left-0 right-0 z-50 border-b border-accent-subtle">
        <div class="px-4 sm:px-6 lg:px-8 py-3 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-9 w-9">
                <div>
                    <h1 class="text-lg font-bold text-primary-blue leading-none">Mutalex Academy</h1>
                    <p class="text-[11px] text-gray-500 uppercase tracking-wider font-semibold mt-1">Shopping Cart</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">
                    <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">
                        <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 -->
                    <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>

    <div class="flex flex-1 pt-16">
        <!-- Sidebar Navigation -->
        <aside class="hidden lg:block w-64 bg-white border-r border-accent-subtle p-6 sticky top-16 h-[calc(100vh-64px)] overflow-y-auto">
            <nav class="space-y-1">
                <a href="dashboard.php" class="flex items-center space-x-3 p-3 rounded-xl text-slate-600 hover:bg-indigo-50 hover:text-indigo-600 transition duration-150">
                    <i class="fas fa-home w-5"></i>
                    <span class="font-medium">Dashboard</span>
                </a>
                <a href="available_courses.php" class="flex items-center space-x-3 p-3 rounded-xl text-slate-600 hover:bg-indigo-50 hover:text-indigo-600 transition duration-150">
                    <i class="fas fa-book-open w-5"></i>
                    <span class="font-medium">Catalog</span>
                </a>
                <a href="courses.php" class="flex items-center space-x-3 p-3 rounded-xl text-slate-600 hover:bg-indigo-50 hover:text-indigo-600 transition duration-150">
                    <i class="fas fa-graduation-cap w-5"></i>
                    <span class="font-medium">My Courses</span>
                </a>
                <a href="exams.php" class="flex items-center space-x-3 p-3 rounded-xl text-slate-600 hover:bg-indigo-50 hover:text-indigo-600 transition duration-150">
                    <i class="fas fa-file-alt w-5"></i>
                    <span class="font-medium">My Exams</span>
                </a>
                <a href="../exams/catalog.php" class="flex items-center space-x-3 p-3 rounded-xl text-slate-600 hover:bg-indigo-50 hover:text-indigo-600 transition duration-150">
                    <i class="fas fa-list w-5"></i>
                    <span class="font-medium">All Exams</span>
                </a>
                <a href="reports.php" class="flex items-center space-x-3 p-3 rounded-xl text-slate-600 hover:bg-indigo-50 hover:text-indigo-600 transition duration-150">
                    <i class="fas fa-chart-pie w-5"></i>
                    <span class="font-medium">Grades & Reports</span>
                </a>
                <a href="calendar.php" class="flex items-center space-x-3 p-3 rounded-xl text-slate-600 hover:bg-indigo-50 hover:text-indigo-600 transition duration-150">
                    <i class="fas fa-calendar w-5"></i>
                    <span class="font-medium">Calendar</span>
                </a>
                <div class="pt-4 pb-2">
                    <p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest px-3">Account</p>
                </div>
                <a href="../index.php" class="flex items-center space-x-3 p-3 rounded-xl text-slate-600 hover:bg-indigo-50 hover:text-indigo-600 transition duration-150">
                    <i class="fas fa-globe w-5"></i>
                    <span class="font-medium">View Site</span>
                </a>
                <a href="../logout.php" class="flex items-center space-x-3 p-3 rounded-xl text-red-500 hover:bg-red-50 transition duration-150">
                    <i class="fas fa-sign-out-alt w-5"></i>
                    <span class="font-medium">Logout</span>
                </a>
            </nav>
            <div class="mt-10 p-4 bg-slate-50 rounded-2xl border border-slate-100">
                <p class="text-[10px] text-slate-400 font-bold uppercase">Logged in as</p>
                <p class="text-xs font-mono text-slate-600 mt-1 truncate"><?php echo htmlspecialchars($user['username'] ?? 'User'); ?></p>
            </div>
        </aside>

        <!-- Mobile Menu Overlay -->
        <div id="mobileMenu" class="fixed inset-0 bg-slate-900/50 z-[60] hidden backdrop-blur-sm lg:hidden">
            <div class="w-72 bg-white h-full p-6 shadow-2xl animate-fade-in">
                <div class="flex justify-between items-center mb-8">
                    <h2 class="font-bold text-primary-blue">Menu</h2>
                    <button id="closeMobileMenu" class="text-2xl text-slate-400">&times;</button>
                </div>
                <nav class="space-y-2">
                    <a href="dashboard.php" class="block p-3 rounded-xl bg-slate-50 text-slate-700 font-medium"><i class="fas fa-home w-5 mr-2"></i>Dashboard</a>
                    <a href="available_courses.php" class="block p-3 rounded-xl text-slate-700 font-medium"><i class="fas fa-book-open w-5 mr-2"></i>Catalog</a>
                    <a href="courses.php" class="block p-3 rounded-xl text-slate-700 font-medium"><i class="fas fa-graduation-cap w-5 mr-2"></i>My Courses</a>
                    <a href="exams.php" class="block p-3 rounded-xl text-slate-700 font-medium"><i class="fas fa-file-alt w-5 mr-2"></i>My Exams</a>
                    <a href="../exams/catalog.php" class="block p-3 rounded-xl text-slate-700 font-medium"><i class="fas fa-list w-5 mr-2"></i>All Exams</a>
                    <a href="reports.php" class="block p-3 rounded-xl text-slate-700 font-medium"><i class="fas fa-chart-pie w-5 mr-2"></i>Grades & Reports</a>
                    <a href="calendar.php" class="block p-3 rounded-xl text-slate-700 font-medium"><i class="fas fa-calendar w-5 mr-2"></i>Calendar</a>
                    <div class="border-t border-slate-200 my-4"></div>
                    <a href="../index.php" class="block p-3 rounded-xl text-slate-700 font-medium"><i class="fas fa-globe w-5 mr-2"></i>View Site</a>
                    <a href="../logout.php" class="block p-3 rounded-xl text-red-500 font-medium"><i class="fas fa-sign-out-alt w-5 mr-2"></i>Logout</a>
                </nav>
            </div>
        </div>

        <!-- Main Content -->
        <main class="flex-1 p-4 lg:p-8">
            <div class="max-w-5xl mx-auto">
                <div class="bg-white rounded-3xl shadow-sm border border-slate-200 overflow-hidden animate-fade-in">
                    <div class="p-6 lg:p-10">
                        <?php if (empty($cart['items'])): ?>
                            <!-- Empty Cart -->
                            <div class="text-center py-12">
                                <div class="w-20 h-20 bg-indigo-50 text-indigo-500 rounded-full flex items-center justify-center mx-auto mb-6">
                                    <i class="fas fa-shopping-cart text-3xl"></i>
                                </div>
                                <h2 class="text-2xl font-bold text-slate-900 mb-2">Your cart is empty</h2>
                                <p class="text-slate-500 mb-8">Add some courses to get started with your learning journey!</p>
                                <a href="../courses/catalog.php" class="bg-indigo-600 text-white px-8 py-3 rounded-xl font-bold shadow-lg shadow-indigo-100 hover:bg-indigo-700 transition-all inline-flex items-center gap-2">
                                    <i class="fas fa-arrow-left"></i> Browse Courses
                                </a>
                            </div>
                        <?php else: ?>
                            <!-- Cart Header -->
                            <div class="flex items-center justify-between mb-8">
                                <div>
                                    <h2 class="text-2xl font-bold text-slate-900">Shopping Cart</h2>
                                    <p class="text-slate-500 text-sm mt-1"><?php echo count($cart['items']); ?> item(s) in your cart</p>
                                </div>
                                <button onclick="clearCart()" class="text-sm text-red-500 hover:text-red-700 font-medium flex items-center gap-1 px-3 py-2 border border-red-200 rounded-xl hover:bg-red-50 transition-all">
                                    <i class="fas fa-trash-alt"></i> Clear All
                                </button>
                            </div>

                            <!-- Cart Items -->
                            <div class="space-y-4 mb-8">
                                <?php foreach ($cart['items'] as $item): ?>
                                    <div class="flex items-center justify-between p-4 bg-slate-50 rounded-2xl border border-slate-200 hover:border-indigo-200 transition-all group" id="cart-item-<?php echo $item['item_id']; ?>">
                                        <div class="flex items-center gap-4">
                                            <?php if ($item['thumbnail']): ?>
                                                <img src="<?php echo htmlspecialchars($item['thumbnail']); ?>" alt="" class="w-16 h-12 rounded-xl object-cover border border-slate-200">
                                            <?php else: ?>
                                                <div class="w-16 h-12 rounded-xl bg-indigo-100 flex items-center justify-center text-indigo-400 border border-slate-200">
                                                    <i class="fas <?php echo $item['item_type'] === 'exam' ? 'fa-file-alt' : 'fa-book'; ?>"></i>
                                                </div>
                                            <?php endif; ?>
                                            <div>
                                                <h6 class="font-semibold text-slate-900"><?php echo htmlspecialchars($item['title']); ?></h6>
                                                <div class="flex items-center gap-2 mt-1">
                                                    <span class="text-[10px] uppercase font-bold tracking-wider text-slate-400"><?php echo htmlspecialchars($item['item_type']); ?></span>
                                                    <?php if ($item['is_free']): ?>
                                                        <span class="text-xs font-bold text-green-600 bg-green-50 px-2 py-0.5 rounded-full">Free</span>
                                                    <?php else: ?>
                                                        <span class="text-sm font-bold text-indigo-600"><?php echo formatCurrency($item['price'], $item['currency']); ?></span>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                        <button onclick="removeFromCart(<?php echo $item['item_id']; ?>)" class="text-slate-400 hover:text-red-500 p-2 rounded-lg hover:bg-red-50 transition-all opacity-0 group-hover:opacity-100" title="Remove item">
                                            <i class="fas fa-times"></i>
                                        </button>
                                    </div>
                                <?php endforeach; ?>
                            </div>

                            <!-- Cart Summary -->
                            <div class="bg-indigo-900 text-white rounded-2xl p-6 mb-8">
                                <div class="flex items-center justify-between mb-4">
                                    <span class="text-lg font-semibold text-indigo-200">Order Total</span>
                                    <span class="text-3xl font-bold text-white">
                                        <?php echo formatCurrency($cart['total'], $cart['currency']); ?>
                                    </span>
                                </div>
                                <?php if ($cart['total'] > 0): ?>
                                    <div class="flex items-center gap-2 text-indigo-300 text-sm">
                                        <i class="fas fa-lock"></i>
                                        <span>Secure payment processing powered by Paynow and PayPal</span>
                                    </div>
                                <?php endif; ?>
                            </div>

                            <!-- Action Buttons -->
                            <div class="flex flex-col sm:flex-row gap-4 justify-between items-center">
                                <a href="../courses/catalog.php" class="text-indigo-600 hover:text-indigo-800 font-medium flex items-center gap-2 px-4 py-2 rounded-xl hover:bg-indigo-50 transition-all">
                                    <i class="fas fa-arrow-left"></i> Continue Shopping
                                </a>
                                <?php if (!$userId): ?>
                                    <a href="login.php?redirect=student/dashboard.php" class="bg-indigo-600 text-white px-8 py-3 rounded-xl font-bold shadow-lg shadow-indigo-100 hover:bg-indigo-700 transition-all inline-flex items-center gap-2">
                                        <i class="fas fa-sign-in-alt"></i> Login to Checkout
                                    </a>
                                <?php else: ?>
                                    <a href="checkout.php" class="bg-indigo-600 text-white px-8 py-3 rounded-xl font-bold shadow-lg shadow-indigo-100 hover:bg-indigo-700 transition-all inline-flex items-center gap-2">
                                        <i class="fas fa-credit-card"></i> Proceed to Checkout
                                    </a>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <!-- Checkout Modal -->
    <div id="dashboard-checkout-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl shadow-2xl max-w-md w-full mx-4 max-h-[90vh] overflow-y-auto">
            <div class="p-6">
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-xl font-bold text-gray-900">Complete Checkout</h2>
                    <button onclick="closeDashboardCheckoutModal()" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times text-xl"></i>
                    </button>
                </div>
                <div id="checkout-content">
                    <div class="text-center py-8">
                        <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-blue mx-auto mb-4"></div>
                        <p class="text-gray-600">Loading checkout...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
    // Initialize cart on page load
    document.addEventListener('DOMContentLoaded', function() {
        loadCartContent();
        setupMobileMenu();
    });

    // Mobile Menu Functionality
    function setupMobileMenu() {
        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('hidden');
            });

            closeMobileMenu.addEventListener('click', () => {
                mobileMenu.classList.add('hidden');
            });

            // Close menu when clicking outside the menu panel
            mobileMenu.addEventListener('click', function(e) {
                if (e.target === mobileMenu) {
                    mobileMenu.classList.add('hidden');
                }
            });

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

    // Load cart content
    function loadCartContent() {
        fetch('../api/cart.php')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Update cart count badge
                const cartBadge = document.getElementById('dashboard-cart-count');
                if (cartBadge) {
                    const count = data.cart.item_count || 0;
                    cartBadge.textContent = count;
                    cartBadge.classList.toggle('hidden', count === 0);
                }
            }
        })
        .catch(error => console.error('Error loading cart:', error));
    }

    // Show checkout modal
    function showDashboardCheckoutModal() {
        const modal = document.getElementById('dashboard-checkout-modal');
        if (modal) {
            modal.classList.remove('hidden');
            loadCheckoutContent();
        }
    }

    // Close checkout modal
    function closeDashboardCheckoutModal() {
        const modal = document.getElementById('dashboard-checkout-modal');
        if (modal) {
            modal.classList.add('hidden');
        }
    }

    // Load checkout content
    function loadCheckoutContent() {
        fetch('../api/cart.php')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const cart = data.cart;
                renderCheckoutContent(cart);
            } else {
                document.getElementById('checkout-content').innerHTML = '<div class="text-center py-8"><p class="text-red-600">Error loading cart</p></div>';
            }
        })
        .catch(error => {
            console.error('Error loading checkout:', error);
            document.getElementById('checkout-content').innerHTML = '<div class="text-center py-8"><p class="text-red-600">Error loading checkout</p></div>';
        });
    }

    // Render checkout content
    function renderCheckoutContent(cart) {
        if (!cart.items || cart.items.length === 0) {
            document.getElementById('checkout-content').innerHTML = `
                <div class="text-center py-8">
                    <i class="fas fa-shopping-cart fa-3x text-gray-300 mb-4"></i>
                    <h5 class="text-gray-600 mb-2">Your cart is empty</h5>
                    <p class="text-sm text-gray-500 mb-6">Add some courses to get started with your learning journey</p>
                    <div class="flex flex-col sm:flex-row gap-3 justify-center">
                        <button onclick="closeDashboardCheckoutModal(); window.location.href='../courses/catalog.php';" class="bg-indigo-600 text-white px-6 py-2 rounded-lg hover:bg-indigo-700 font-medium">
                            <i class="fas fa-graduation-cap mr-2"></i>Browse Courses
                        </button>
                        <a href="../courses/catalog.php" class="bg-white text-indigo-600 border border-indigo-300 px-6 py-2 rounded-lg hover:bg-indigo-50 font-medium">
                            <i class="fas fa-external-link-alt mr-2"></i>View Full Catalog
                        </a>
                    </div>
                </div>
            `;
            return;
        }

        let itemsHtml = '';
        cart.items.forEach(item => {
            itemsHtml += `
                <div class="bg-gray-50 rounded-lg p-4 mb-3 border border-gray-200">
                    <div class="flex items-start justify-between">
                        <div class="flex-1">
                            <h4 class="text-sm font-medium text-gray-800">${item.title}</h4>
                            <p class="text-xs text-gray-500">${item.is_free ? 'Free' : formatCurrency(item.price, item.currency)}</p>
                        </div>
                    </div>
                </div>
            `;
        });

        const checkoutHtml = `
            <div class="mb-6">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="font-medium text-gray-800">Cart Items (${cart.items.length})</h3>
                    <div class="flex items-center space-x-3">
                        <button onclick="closeDashboardCheckoutModal(); window.location.href='../courses/catalog.php';" class="text-sm text-blue-600 hover:text-blue-800 font-medium flex items-center">
                            <i class="fas fa-plus mr-1"></i>Add More Courses
                        </button>
                        <button onclick="clearCart()" class="text-xs text-gray-500 hover:text-red-600 font-medium flex items-center ml-4 px-2 py-1 border border-gray-300 rounded">
                            <i class="fas fa-trash mr-1"></i>Clear All
                        </button>
                    </div>
                </div>
                ${itemsHtml}
            </div>

            <div class="bg-gray-50 p-4 rounded-lg mb-6">
                <div class="flex justify-between items-center">
                    <span class="font-medium text-gray-700">Total Amount:</span>
                    <span class="text-2xl font-bold text-indigo-600">${formatCurrency(cart.total, cart.currency)}</span>
                </div>
            </div>

            <div class="text-center space-y-3">
                ${cart.total == 0 ?
                    `<button onclick="processFreeEnrollment()" class="w-full bg-green-600 text-white py-3 px-4 rounded-lg font-semibold hover:bg-green-700 transition duration-200">
                        <i class="fas fa-graduation-cap mr-2"></i>Enroll Now
                    </button>` :
                    `<a href="checkout.php" class="w-full bg-indigo-600 text-white py-3 px-4 rounded-lg font-semibold hover:bg-indigo-700 transition duration-200 inline-flex items-center justify-center">
                        <i class="fas fa-credit-card mr-2"></i>Proceed to Checkout
                    </a>`
                }
            </div>
        `;

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

    // Format currency for JavaScript
    function formatCurrency(amount, currency = 'USD') {
        const formatter = new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: currency,
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        });
        return formatter.format(amount);
    }

    // Clear entire cart
    function clearCart() {
        if (confirm('Are you sure you want to clear your entire cart?')) {
            fetch('../api/cart.php', {
                method: 'DELETE'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast('Cart cleared successfully', 'success');
                    location.reload();
                } else {
                    showToast('Error clearing cart: ' + data.error, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('An error occurred. Please try again.', 'error');
            });
        }
    }

    // Process free enrollment
    function processFreeEnrollment() {
        fetch('../api/cart.php', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                if (data.payment_required) {
                    showToast('Payment required. Redirecting to checkout...', 'success');
                    closeDashboardCheckoutModal();
                    setTimeout(() => {
                        window.location.href = 'checkout.php';
                    }, 1000);
                } else {
                    showToast('Successfully enrolled in courses!', 'success');
                    closeDashboardCheckoutModal();
                    loadCartContent();
                    setTimeout(() => {
                        location.reload();
                    }, 1500);
                }
            } else {
                showToast('Error: ' + (data.error || 'Enrollment failed'), 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('An error occurred. Please try again.', 'error');
        });
    }

    // Remove item from cart
    function removeFromCart(itemId) {
        if (confirm('Remove this item from cart?')) {
            fetch('../api/cart.php?item_id=' + itemId, {
                method: 'DELETE'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    location.reload();
                } else {
                    alert('Error: ' + data.error);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred. Please try again.');
            });
        }
    }

    // Toast notification system
    function showToast(message, type = 'success') {
        const existingToasts = document.querySelectorAll('.toast-notification');
        existingToasts.forEach(toast => toast.remove());

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

        document.body.appendChild(toast);

        setTimeout(() => {
            toast.classList.remove('translate-x-full');
        }, 100);

        setTimeout(() => {
            toast.classList.add('translate-x-full');
            setTimeout(() => {
                toast.remove();
            }, 300);
        }, 4000);
    }
    </script>

</body>
</html>