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

// Check if user is logged in
if (!isLoggedIn()) {
    header('Location: ../login.php');
    exit;
}

$user = getUserContext();
$page_title = 'Student Calendar';
?>
<!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 ?? 'Student Calendar'); ?> | Mutalex Academy</title>
    <!-- Load Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Set up Tailwind configuration for Inter font and a professional color palette -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'primary-blue': '#1E3A8A', // Deep Indigo/Navy
                        'background-light': '#F8FAFC', // Slate 50
                        'text-dark': '#1F2937', // Gray 800
                        'accent-subtle': '#E5E7EB', // Gray 200
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style>
        /* 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;
        }
    </style>
</head>
<body class="bg-background-light font-sans text-text-dark min-h-screen">

    <!-- Main Application Container -->
    <div id="app" class="flex">

        <!-- Top Bar (Mobile/Desktop Header) -->
        <header class="bg-white shadow-sm fixed top-0 left-0 right-0 z-10 border-b border-accent-subtle">
            <div class="px-4 sm:px-6 lg:px-8 py-4 flex justify-between items-center">
                <div class="flex items-center space-x-3">
                    <img src="../assets/images/logo_1757657555.jpg" alt="Mutalex Academy Logo" class="h-10 w-10">
                    <div>
                        <h1 class="text-xl font-bold text-primary-blue">Mutalex Academy</h1>
                        <p class="text-sm text-gray-600">Calendar</p>
                    </div>
                </div>

                <div class="flex items-center space-x-4">
                    <!-- Cart Button -->
                    <button onclick="showDashboardCheckoutModal()" class="text-gray-600 hover:text-primary-blue p-2 rounded-full relative transition duration-150">
                        <!-- Shopping Cart Icon -->
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-shopping-cart">
                            <circle cx="8" cy="21" r="1"/>
                            <circle cx="19" cy="21" r="1"/>
                            <path d="M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.15"/>
                        </svg>
                        <span id="dashboard-cart-count" class="absolute -top-1 -right-1 bg-red-500 text-white text-xs font-bold rounded-full h-5 w-5 flex items-center justify-center hidden">0</span>
                    </button>

                    <!-- User Profile -->
                    <div class="flex items-center space-x-2">
                        <span class="text-sm font-medium hidden sm:inline"><?php echo htmlspecialchars($user['username'] ?? 'Student'); ?></span>
                        <img class="h-10 w-10 rounded-full border-2 border-primary-blue object-cover" src="https://placehold.co/100x100/1E3A8A/ffffff?text=<?php echo substr(htmlspecialchars($user['username'] ?? 'S'), 0, 1); ?>" alt="User Avatar">
                        <!-- Mobile Menu Button (Hamburger) -->
                        <button class="lg:hidden p-2 rounded-lg text-text-dark hover:bg-accent-subtle ml-4" id="mobileMenuButton">
                            <span class="text-xl">☰</span>
                        </button>
                    </div>
                </div>
            </div>
        </header>

        <!-- Sidebar Navigation (Desktop View) -->
        <aside class="hidden lg:block w-64 bg-white border-r border-accent-subtle p-6 shadow-sm sticky top-16 h-screen">
            <div class="flex flex-col h-full">
                <!-- Logo/Title -->
                <div class="text-xl font-extrabold text-primary-blue mb-10 tracking-wider">
                </div>

                <!-- Navigation Links -->
                <nav class="space-y-2 flex-grow">
                    <a href="dashboard.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Home -->
                        <span class="w-5 h-5">🏠</span>
                        <span>Dashboard</span>
                    </a>
                    <a href="available_courses.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Catalog -->
                        <span class="w-5 h-5">📖</span>
                        <span>View All Courses</span>
                    </a>
                    <a href="courses.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Book -->
                        <span class="w-5 h-5">📚</span>
                        <span>My Courses</span>
                    </a>
                    <a href="exams.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Exam -->
                        <span class="w-5 h-5">📝</span>
                        <span>My Exam</span>
                    </a>
                    <a href="../exams/catalog.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: All Exams -->
                        <span class="w-5 h-5">📋</span>
                        <span>All Exam</span>
                    </a>
                    <a href="reports.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Checkmark -->
                        <span class="w-5 h-5">✅</span>
                        <span>Grades & Reports</span>
                    </a>
                    <a href="calendar.php" class="flex items-center space-x-3 p-3 rounded-lg bg-primary-blue text-white font-semibold transition duration-150 shadow-md">
                        <!-- Icon Placeholder: Calendar -->
                        <span class="w-5 h-5">📅</span>
                        <span>Calendar</span>
                    </a>
                    <a href="../index.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Globe -->
                        <span class="w-5 h-5">🌐</span>
                        <span>View Site</span>
                    </a>
                    <a href="../logout.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Logout -->
                        <span class="w-5 h-5">🚪</span>
                        <span>Logout</span>
                    </a>
                </nav>

                <!-- Footer/User Info (Bottom of Sidebar) -->
                <div class="mt-8 pt-4 border-t border-accent-subtle">
                    <p class="text-xs text-gray-500 mb-2">Authenticated User:</p>
                    <p class="text-xs text-gray-700 truncate font-mono bg-accent-subtle p-1 rounded"><?php echo htmlspecialchars($user['username'] ?? 'User'); ?></p>
                </div>
            </div>
        </aside>

        <!-- Main Content Area -->
        <main class="flex-1 overflow-y-auto pt-16">

            <!-- Mobile Navigation Overlay (Hidden by default) -->
            <div id="mobileMenu" class="fixed inset-0 bg-white z-20 p-6 transform -translate-x-full transition-transform duration-300 lg:hidden">
                <div class="flex justify-between items-center mb-10">
                    <div class="text-xl font-extrabold text-primary-blue tracking-wider"></div>
                    <button id="closeMobileMenu" class="text-3xl text-text-dark">&times;</button>
                </div>
                <nav class="space-y-4">
                    <!-- Links repeated from sidebar -->
                    <a href="dashboard.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">🏠 Dashboard</a>
                    <a href="available_courses.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📖 View All Courses</a>
                    <a href="courses.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📚 My Courses</a>
                    <a href="exams.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📝 My Exam</a>
                    <a href="../exams/catalog.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📋 All Exam</a>
                    <a href="reports.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">✅ Grades & Reports</a>
                    <a href="calendar.php" class="block p-3 rounded-lg bg-primary-blue text-white font-semibold">📅 Calendar</a>
                    <a href="../index.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">🌐 View Site</a>
                    <a href="../logout.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">🚪 Logout</a>
                </nav>
            </div>
?>

<!-- Student Calendar JavaScript -->
<script>
    // --- Types/State ---
    let currentDate = new Date();
    let events = [];
    let selectedDate = null;

    // Constants
    const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    const daysOfWeek = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

    // Helpers
    const getDaysInMonth = (year, month) => new Date(year, month + 1, 0).getDate();
    const getFirstDayOfMonth = (year, month) => new Date(year, month, 1).getDay();

    const formatDateKey = (year, month, day) => {
        return `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
    };

    // Initialize calendar
    async function initCalendar() {
        try {
            await loadEvents();
            renderCalendar();
            renderEventsList();
            console.log("Student calendar initialized successfully");
        } catch (error) {
            console.error("Student calendar initialization failed:", error);
        }
    }

    // Load events from server
    async function loadEvents() {
        const response = await fetch('../api/calendar.php');
        const data = await response.json();

        if (data.success) {
            events = data.events.map(event => ({
                id: event.id,
                title: event.title,
                description: event.description,
                date: event.event_date,
                creator: event.creator_name || 'Admin',
                time: event.event_time || '09:00'
            }));
        } else {
            console.error("Failed to load events:", data.error);
        }
    }

    // Event Handlers
    const handlePrevMonth = () => {
        currentDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, 1);
        renderCalendar();
    };

    const handleNextMonth = () => {
        currentDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 1);
        renderCalendar();
    };

    const handleDayClick = (day) => {
        const dateKey = formatDateKey(currentDate.getFullYear(), currentDate.getMonth(), day);
        selectedDate = dateKey;
        renderEventsList();
    };

    // Render Functions
    function renderCalendar() {
        const calendarContainer = document.getElementById('calendar-container');
        const year = currentDate.getFullYear();
        const month = currentDate.getMonth();
        const daysInMonth = getDaysInMonth(year, month);
        const firstDay = getFirstDayOfMonth(year, month);

        // Create blank cells for days before the 1st of the month
        const blanks = Array(firstDay).fill(null);

        // Create array of days
        const days = Array.from({ length: daysInMonth }, (_, i) => i + 1);

        let html = `
            <div class="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden">
                <!-- Calendar Controls -->
                <div class="flex items-center justify-between p-6 border-b border-slate-100">
                    <h2 class="text-xl font-bold text-slate-800">
                        ${months[month]} <span class="text-indigo-600">${year}</span>
                    </h2>
                    <div class="flex items-center gap-2">
                        <button onclick="handlePrevMonth()" class="p-2 hover:bg-slate-100 rounded-full transition-colors">
                            <svg class="w-5 h-5 text-slate-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path></svg>
                        </button>
                        <button onclick="currentDate = new Date(); renderCalendar();" class="text-sm font-medium text-indigo-600 hover:underline px-2">
                            Today
                        </button>
                        <button onclick="handleNextMonth()" class="p-2 hover:bg-slate-100 rounded-full transition-colors">
                            <svg class="w-5 h-5 text-slate-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path></svg>
                        </button>
                    </div>
                </div>

                <!-- Days Header -->
                <div class="grid grid-cols-7 border-b border-slate-100 bg-slate-50/50">
                    ${daysOfWeek.map(day => `
                        <div class="py-3 text-center text-xs font-semibold text-slate-500 uppercase tracking-wider">
                            ${day}
                        </div>
                    `).join('')}
                </div>

                <!-- Calendar Cells -->
                <div class="grid grid-cols-7 auto-rows-fr">
                    <!-- Blank spots for previous month -->
                    ${blanks.map((_, i) => `
                        <div class="min-h-[100px] border-b border-r border-slate-50 bg-slate-50/30"></div>
                    `).join('')}

                    <!-- Actual Days -->
                    ${days.map(day => {
                        const dateKey = formatDateKey(year, month, day);
                        const isToday = dateKey === new Date().toISOString().split('T')[0];
                        const isSelected = selectedDate === dateKey;
                        const dayEvents = events.filter(e => e.date === dateKey);

                        return `
                            <div
                                onclick="handleDayClick(${day})"
                                class="min-h-[120px] p-2 border-b border-r border-slate-100 cursor-pointer transition-colors relative group ${isToday ? 'bg-indigo-50/30' : isSelected ? 'bg-blue-50/50' : 'hover:bg-slate-50'}"
                            >
                                <div class="flex justify-between items-start mb-1">
                                    <span class="text-sm font-medium w-7 h-7 flex items-center justify-center rounded-full ${isToday ? 'bg-indigo-600 text-white shadow-md' : isSelected ? 'bg-blue-600 text-white shadow-md' : 'text-slate-700'}">
                                        ${day}
                                    </span>
                                </div>

                                <!-- Event Dots/Preview -->
                                <div class="flex flex-col gap-1 mt-1">
                                    ${dayEvents.slice(0, 3).map((ev, idx) => `
                                        <div class="text-xs truncate bg-indigo-100 text-indigo-800 px-1.5 py-0.5 rounded border border-indigo-200/50 font-medium" title="${ev.title} at ${ev.time}">
                                            ${ev.time} ${ev.title}
                                        </div>
                                    `).join('')}
                                    ${dayEvents.length > 3 ? `<div class="text-xs text-slate-500 mt-1">+${dayEvents.length - 3} more</div>` : ''}
                                </div>
                            </div>
                        `;
                    }).join('')}
                </div>
            </div>
        `;

        calendarContainer.innerHTML = html;
    }

    function renderEventsList() {
        const eventsListEl = document.getElementById('events-list');
        const eventsCountEl = document.getElementById('events-count');

        // Filter events for the selected date or show upcoming events
        let displayEvents = [];
        if (selectedDate) {
            displayEvents = events.filter(e => e.date === selectedDate);
        } else {
            // Show upcoming events (next 7 days)
            const today = new Date();
            const nextWeek = new Date(today);
            nextWeek.setDate(today.getDate() + 7);

            displayEvents = events.filter(e => {
                const eventDate = new Date(e.date);
                return eventDate >= today && eventDate <= nextWeek;
            }).sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());
        }

        eventsCountEl.textContent = displayEvents.length;

        let html = '';

        if (displayEvents.length === 0) {
            const message = selectedDate
                ? `No events scheduled for ${new Date(selectedDate).toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })}.`
                : 'No upcoming events in the next 7 days.';
            html = `
                <div class="text-center py-8 text-slate-400">
                    <svg class="w-10 h-10 mx-auto mb-2 opacity-20" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg>
                    <p>${message}</p>
                </div>
            `;
        } else {
            html = displayEvents.map(event => `
                <div class="group flex gap-4 p-3 rounded-xl hover:bg-slate-50 border border-transparent hover:border-slate-100 transition-all">
                    <!-- Date Box -->
                    <div class="flex-shrink-0 w-14 h-14 bg-indigo-50 rounded-lg flex flex-col items-center justify-center border border-indigo-100">
                        <span class="text-xs text-indigo-600 font-bold uppercase">
                            ${new Date(event.date).toLocaleString('default', { month: 'short' })}
                        </span>
                        <span class="text-xl font-bold text-slate-800">
                            ${new Date(event.date).getDate()}
                        </span>
                    </div>

                    <!-- Content -->
                    <div class="flex-grow min-w-0">
                        <h4 class="font-semibold text-slate-800 truncate">${event.title}</h4>
                        <p class="text-xs text-slate-500 mb-2 truncate">${event.description}</p>
                        <div class="flex items-center gap-3 text-xs text-slate-400">
                            <span class="flex items-center gap-1">
                                <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                                ${event.time}
                            </span>
                            <span class="flex items-center gap-1">
                                <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path></svg>
                                ${event.creator}
                            </span>
                            </div>
                        </main>
                    </div>
            `).join('');
        }

        eventsListEl.innerHTML = html;
    }

    // Expose functions globally
    window.initCalendar = initCalendar;
    window.handlePrevMonth = handlePrevMonth;
    window.handleNextMonth = handleNextMonth;
    window.handleDayClick = handleDayClick;
</script>

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

                <!-- Header -->
                <header class="mb-8 flex flex-col md:flex-row md:items-center justify-between gap-4">
                    <div>
                        <h1 class="text-3xl font-bold text-slate-900 flex items-center gap-2">
                            <svg class="w-8 h-8 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg>
                            Student Calendar
                        </h1>
                        <p class="text-slate-500 mt-1">View your academic schedule and important events</p>
                    </div>
                </header>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">

        <!-- Left Column: Calendar Grid -->
        <div class="lg:col-span-2 space-y-6">
            <div id="calendar-container">
                <!-- Calendar will be rendered here -->
            </div>
        </div>

        <!-- Right Column: Events List -->
        <div class="lg:col-span-1 space-y-6">
            <div class="bg-white rounded-2xl shadow-sm border border-slate-200 p-6">
                <h3 class="text-lg font-bold text-slate-800 mb-4 flex items-center justify-between">
                    <span id="events-title">Upcoming Events</span>
                    <span id="events-count" class="bg-slate-100 text-slate-600 text-xs px-2 py-1 rounded-full">0</span>
                </h3>

                <div class="space-y-4 max-h-[600px] overflow-y-auto pr-2" id="events-list">
                    <!-- Events will be rendered here -->
                </div>
            </div>
        </div>
    </div>
</div>

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

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

                if (data.cart.items.length > 0) {
                    // Cart has items, checkout modal can be shown when needed
                    console.log('Cart loaded:', data.cart);
                }
            }
        })
        .catch(error => console.error('Error loading cart:', error));
    }

    // Show checkout modal from dashboard
    function showDashboardCheckoutModal() {
        // Create modal HTML
        const modalHtml = `
            <div id="dashboard-checkout-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
                <div class="bg-white rounded-xl shadow-2xl max-w-md w-full mx-4 max-h-[90vh] overflow-y-auto">
                    <div class="p-6">
                        <div class="flex justify-between items-center mb-6">
                            <h2 class="text-xl font-bold text-gray-900">Complete Checkout</h2>
                            <button onclick="closeDashboardCheckoutModal()" class="text-gray-400 hover:text-gray-600">
                                <i class="fas fa-times text-xl"></i>
                            </button>
                        </div>

                        <div id="checkout-content">
                            <!-- Content will be loaded here -->
                            <div class="text-center py-8">
                                <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-blue mx-auto mb-4"></div>
                                <p class="text-gray-600">Loading checkout...</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;

        document.body.insertAdjacentHTML('beforeend', modalHtml);

        // Add event listeners for closing modal
        const modal = document.getElementById('dashboard-checkout-modal');

        // Close modal when clicking outside
        modal.addEventListener('click', function(e) {
            if (e.target === modal) {
                closeDashboardCheckoutModal();
            }
        });

        // Close modal when pressing ESC key
        const handleEscapeKey = function(e) {
            if (e.key === 'Escape') {
                closeDashboardCheckoutModal();
            }
        };
        document.addEventListener('keydown', handleEscapeKey);

        // Store the escape handler to remove it later
        modal._escapeHandler = handleEscapeKey;

        loadCheckoutContent();
    }

    // Close checkout modal
    function closeDashboardCheckoutModal() {
        const modal = document.getElementById('dashboard-checkout-modal');
        if (modal) {
            // Remove escape key event listener
            if (modal._escapeHandler) {
                document.removeEventListener('keydown', modal._escapeHandler);
            }
            modal.remove();
        }
    }

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

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

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

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

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

            <div class="text-center space-y-3">
                <button onclick="processFreeEnrollment()" class="w-full bg-green-600 text-white py-3 px-4 rounded-lg font-semibold hover:bg-green-700 transition duration-200">
                    <i class="fas fa-graduation-cap mr-2"></i>Enroll Now
                </button>
            </div>
        `;

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

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

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

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

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

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

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

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

    // Toast notification system
    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);
    }
</script>

</body>
</html>