<?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 student or higher
studentOrHigher();

$user = getUserContext();
$db = getDB();
$userId = $_SESSION['user_id'];

// Get all enrolled courses with detailed information
$stmt = $db->prepare("
    SELECT c.*, ce.enrollment_date, ce.progress_percentage, ce.status as enrollment_status,
           ce.completion_date, cat.name as category_name, cat.color as category_color,
           u.username as instructor_name, up.first_name, up.last_name,
           COUNT(DISTINCT cl.id) as total_lessons,
           COUNT(DISTINCT clp.id) as completed_lessons
    FROM course_enrollments ce
    JOIN courses c ON ce.course_id = c.id
    LEFT JOIN course_categories cat ON c.category_id = cat.id
    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 course_lesson_progress clp ON cl.id = clp.lesson_id AND clp.enrollment_id = ce.id AND clp.status = 'completed'
    WHERE ce.student_id = ?
    GROUP BY ce.id, c.id
    ORDER BY ce.enrollment_date DESC
");
$stmt->execute([$userId]);
$enrolledCourses = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get enrollment statistics
$stmt = $db->prepare("
    SELECT
        COUNT(*) as total_courses,
        COUNT(CASE WHEN status = 'completed' THEN 1 END) as completed_courses,
        COUNT(CASE WHEN status = 'in_progress' THEN 1 END) as in_progress_courses,
        AVG(progress_percentage) as avg_progress
    FROM course_enrollments
    WHERE student_id = ?
");
$stmt->execute([$userId]);
$stats = $stmt->fetch(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Courses | <?php echo htmlspecialchars($user['username'] ?? 'Student'); ?> - Mutalex Academy</title>
    <!-- Load Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Set up Tailwind configuration for Inter font and a professional color palette -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'primary-blue': '#1E3A8A', // Deep Indigo/Navy
                        'background-light': '#F8FAFC', // Slate 50
                        'text-dark': '#1F2937', // Gray 800
                        'accent-subtle': '#E5E7EB', // Gray 200
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style>
        /* Ensuring full page height and scrolling */
        html, body {
            height: 100%;
        }
        /* Custom scrollbar for a cleaner look */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        ::-webkit-scrollbar-thumb {
            background-color: #D1D5DB; /* Gray 300 */
            border-radius: 4px;
        }
        ::-webkit-scrollbar-track {
            background-color: transparent;
        }
    </style>
</head>
<body class="bg-background-light font-sans text-text-dark min-h-screen">

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

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

                <!-- Navigation Links -->
                <nav class="space-y-2 flex-grow">
                    <a href="dashboard.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Home -->
                        <span class="w-5 h-5">🏠</span>
                        <span>Dashboard</span>
                    </a>
                    <a href="available_courses.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Catalog -->
                        <span class="w-5 h-5">📖</span>
                        <span>View All Courses</span>
                    </a>
                    <a href="courses.php" class="flex items-center space-x-3 p-3 rounded-lg bg-primary-blue text-white font-semibold transition duration-150 shadow-md">
                        <!-- 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="#" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Calendar -->
                        <span class="w-5 h-5">📅</span>
                        <span>Calendar</span>
                    </a>
                    <a href="../index.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Globe -->
                        <span class="w-5 h-5">🌐</span>
                        <span>View Site</span>
                    </a>
                    <a href="../logout.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Logout -->
                        <span class="w-5 h-5">🚪</span>
                        <span>Logout</span>
                    </a>
                </nav>

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

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

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

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

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

            <!-- Mobile Navigation Overlay (Hidden by default) -->
            <div id="mobileMenu" class="fixed inset-0 bg-white z-20 p-6 transform -translate-x-full transition-transform duration-300 lg:hidden">
                <div class="flex justify-between items-center mb-10">
                    <div class="text-xl font-extrabold text-primary-blue tracking-wider"></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 bg-primary-blue text-white font-semibold">📚 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="#" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📅 Calendar</a>
                    <a href="../index.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">🌐 View Site</a>
                    <a href="../logout.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">🚪 Logout</a>
                </nav>
            </div>

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

                <!-- Stats -->
                <div class="grid grid-cols-1 sm:grid-cols-4 gap-6 mb-8">

                    <div class="bg-white p-6 rounded-xl shadow-md">
                        <p class="text-sm text-gray-500">Total Courses</p>
                        <p class="text-3xl font-bold text-gray-900"><?php echo $stats['total_courses'] ?? 0; ?></p>
                    </div>
                    <div class="bg-white p-6 rounded-xl shadow-md">
                        <p class="text-sm text-gray-500">Completed</p>
                        <p class="text-3xl font-bold text-green-600"><?php echo $stats['completed_courses'] ?? 0; ?></p>
                    </div>
                    <div class="bg-white p-6 rounded-xl shadow-md">
                        <p class="text-sm text-gray-500">In Progress</p>
                        <p class="text-3xl font-bold text-blue-600"><?php echo $stats['in_progress_courses'] ?? 0; ?></p>
                    </div>
                    <div class="bg-white p-6 rounded-xl shadow-md">
                        <p class="text-sm text-gray-500">Avg Progress</p>
                        <p class="text-3xl font-bold text-amber-600"><?php echo round($stats['avg_progress'] ?? 0); ?>%</p>
                    </div>
                </div>

                <!-- Courses Grid -->
                <?php if (!empty($enrolledCourses)): ?>
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                        <?php foreach ($enrolledCourses as $course): ?>
                            <div class="bg-white rounded-xl shadow-lg overflow-hidden">
                                <div class="relative h-32 bg-gradient-to-br from-primary-blue to-indigo-600 flex items-center justify-center">
                                    <div class="text-white text-center">
                                        <i class="fas fa-graduation-cap w-12 h-12 mx-auto mb-2 opacity-75"></i>
                                        <p class="text-xs opacity-75"><?php echo htmlspecialchars($course['category_name'] ?? 'Course'); ?></p>
                                    </div>
                                    <div class="absolute top-2 right-2">
                                        <span class="px-2 py-1 text-xs font-medium rounded-full <?php
                                            echo $course['enrollment_status'] === 'completed' ? 'bg-green-100 text-green-800' :
                                                 'bg-blue-100 text-blue-800';
                                        ?>">
                                            <?php echo ucfirst(str_replace('_', ' ', $course['enrollment_status'])); ?>
                                        </span>
                                    </div>
                                </div>
                                <div class="p-4">
                                    <h3 class="text-base font-semibold text-gray-800 mb-2">
                                        <?php echo htmlspecialchars($course['title']); ?>
                                    </h3>
                                    <p class="text-sm text-gray-600 mb-3">
                                        by <?php echo htmlspecialchars($course['first_name'] && $course['last_name'] ? $course['first_name'] . ' ' . $course['last_name'] : $course['instructor_name']); ?>
                                    </p>
                                    <div class="mb-4">
                                        <div class="flex justify-between text-sm text-gray-600 mb-1">
                                            <span>Progress</span>
                                            <span><?php echo round($course['progress_percentage']); ?>%</span>
                                        </div>
                                        <div class="w-full bg-gray-200 rounded-full h-2">
                                            <div class="bg-primary-blue h-2 rounded-full" style="width: <?php echo $course['progress_percentage']; ?>%"></div>
                                        </div>
                                    </div>
                                    <div class="flex space-x-2">
                                        <a href="learn.php?id=<?php echo $course['id']; ?>" class="flex-1 bg-primary-blue text-white text-center py-2 px-4 rounded-lg text-sm font-medium hover:bg-indigo-700">
                                            <?php echo $course['enrollment_status'] === 'completed' ? 'Review' : 'Continue'; ?>
                                        </a>
                                        <?php if ($course['enrollment_status'] === 'completed'): ?>
                                            <button onclick="openReviewModal(<?php echo $course['id']; ?>, '<?php echo addslashes($course['title']); ?>')" class="bg-yellow-500 text-white py-2 px-3 rounded-lg text-sm font-medium hover:bg-yellow-600">
                                                <i class="fas fa-star"></i>
                                            </button>
                                        <?php endif; ?>
                                        <a href="../courses/detail.php?id=<?php echo $course['id']; ?>" class="bg-gray-100 text-gray-700 py-2 px-3 rounded-lg text-sm font-medium hover:bg-gray-200">
                                            <i class="fas fa-info-circle"></i>
                                        </a>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <div class="bg-white p-12 rounded-xl shadow-lg text-center">
                        <i class="fas fa-graduation-cap text-gray-400 mx-auto h-16 w-16 mb-4"></i>
                        <h3 class="text-xl font-semibold text-gray-800 mb-2">No courses enrolled</h3>
                        <p class="text-gray-600 mb-6">Start your learning journey by enrolling in courses.</p>
                        <a href="../courses/catalog.php" class="bg-primary-blue text-white px-6 py-3 rounded-lg font-medium hover:bg-indigo-700">
                            Browse Courses
                        </a>
                    </div>
                <?php endif; ?>
            </div>
        </main>
    </div>

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

                <div id="reviewModalContent">
                    <!-- Review form will be loaded here -->
                </div>
            </div>
        </div>
    </div>

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

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

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

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

        // Review Modal Functions
        function openReviewModal(courseId, courseTitle) {
            const modal = document.getElementById('reviewModal');
            const modalContent = document.getElementById('reviewModalContent');

            // Create review form HTML
            const reviewFormHtml = `
                <form id="coursesReviewForm">
                    <input type="hidden" name="type" value="course">
                    <input type="hidden" name="item_id" value="${courseId}">

                    <div class="mb-6">
                        <h3 class="text-lg font-semibold text-gray-900 mb-2">Reviewing: ${courseTitle}</h3>
                        <p class="text-sm text-gray-600">Share your experience with this course</p>
                    </div>

                    <!-- Rating Section -->
                    <div class="mb-6">
                        <label class="block text-gray-700 font-semibold mb-3">Your Rating</label>
                        <div id="coursesRatingContainer" class="flex space-x-1 cursor-pointer text-3xl" onmouseout="resetCoursesVisualRating()">
                            <div data-rating="1" class="courses-rating-star transition-colors duration-150" onmouseover="visualizeCoursesRating(1)" onclick="setCoursesRating(1)">
                                <svg class="w-8 h-8 fill-current text-gray-300" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M12 2l3.09 6.26l6.91 1l-5 4.87l1.18 6.88l-6.18-3.25l-6.18 3.25l1.18-6.88l-5-4.87l6.91-1L12 2z"/>
                                </svg>
                            </div>
                            <div data-rating="2" class="courses-rating-star transition-colors duration-150" onmouseover="visualizeCoursesRating(2)" onclick="setCoursesRating(2)">
                                <svg class="w-8 h-8 fill-current text-gray-300" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M12 2l3.09 6.26l6.91 1l-5 4.87l1.18 6.88l-6.18-3.25l-6.18 3.25l1.18-6.88l-5-4.87l6.91-1L12 2z"/>
                                </svg>
                            </div>
                            <div data-rating="3" class="courses-rating-star transition-colors duration-150" onmouseover="visualizeCoursesRating(3)" onclick="setCoursesRating(3)">
                                <svg class="w-8 h-8 fill-current text-gray-300" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M12 2l3.09 6.26l6.91 1l-5 4.87l1.18 6.88l-6.18-3.25l-6.18 3.25l1.18-6.88l-5-4.87l6.91-1L12 2z"/>
                                </svg>
                            </div>
                            <div data-rating="4" class="courses-rating-star transition-colors duration-150" onmouseover="visualizeCoursesRating(4)" onclick="setCoursesRating(4)">
                                <svg class="w-8 h-8 fill-current text-gray-300" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M12 2l3.09 6.26l6.91 1l-5 4.87l1.18 6.88l-6.18-3.25l-6.18 3.25l1.18-6.88l-5-4.87l6.91-1L12 2z"/>
                                </svg>
                            </div>
                            <div data-rating="5" class="courses-rating-star transition-colors duration-150" onmouseover="visualizeCoursesRating(5)" onclick="setCoursesRating(5)">
                                <svg class="w-8 h-8 fill-current text-gray-300" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M12 2l3.09 6.26l6.91 1l-5 4.87l1.18 6.88l-6.18-3.25l-6.18 3.25l1.18-6.88l-5-4.87l6.91-1L12 2z"/>
                                </svg>
                            </div>
                        </div>
                        <p class="text-sm text-gray-500 mt-2">Click to rate this course</p>
                        <input type="hidden" name="rating" id="coursesRatingValue" value="0" required>
                    </div>

                    <!-- Review Title -->
                    <div class="mb-4">
                        <label for="coursesReviewTitle" class="block text-gray-700 font-semibold mb-2">Review Title (Optional)</label>
                        <input type="text" id="coursesReviewTitle" name="review_title" placeholder="Summarize your experience..." class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-blue focus:border-transparent outline-none transition-shadow" maxlength="100">
                    </div>

                    <!-- Review Text -->
                    <div class="mb-6">
                        <label for="coursesReviewText" class="block text-gray-700 font-semibold mb-2">Your Review</label>
                        <textarea id="coursesReviewText" name="review_text" placeholder="Share your experience with this course..." rows="4" class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-blue focus:border-transparent outline-none resize-none transition-shadow" required></textarea>
                    </div>

                    <!-- Submit Button -->
                    <div class="flex justify-end space-x-3">
                        <button type="button" onclick="closeReviewModal()" class="px-4 py-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">
                            Cancel
                        </button>
                        <button type="submit" class="px-6 py-2 bg-primary-blue text-white rounded-lg hover:bg-blue-700 transition-colors font-semibold">
                            <i class="fas fa-paper-plane mr-2"></i>Submit Review
                        </button>
                    </div>
                </form>
            `;

            modalContent.innerHTML = reviewFormHtml;
            modal.classList.remove('hidden');
            modal.classList.add('flex');

            // Add form submission handler
            const reviewForm = document.getElementById('coursesReviewForm');
            reviewForm.addEventListener('submit', function(e) {
                e.preventDefault();
                submitCoursesReview(new FormData(this));
            });

            // Add escape key handler
            const handleEscapeKey = function(e) {
                if (e.key === 'Escape') {
                    closeReviewModal();
                }
            };
            document.addEventListener('keydown', handleEscapeKey);

            // Add click outside to close
            modal.addEventListener('click', function(e) {
                if (e.target === modal) {
                    closeReviewModal();
                }
            });

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

        function closeReviewModal() {
            const modal = document.getElementById('reviewModal');
            if (modal) {
                modal.classList.add('hidden');
                modal.classList.remove('flex');

                // Remove escape key event listener
                if (modal._escapeHandler) {
                    document.removeEventListener('keydown', modal._escapeHandler);
                }
            }
        }

        // Courses Rating Functions
        function visualizeCoursesRating(rating) {
            const stars = document.querySelectorAll('#coursesRatingContainer .courses-rating-star');
            stars.forEach((star, index) => {
                if (index < rating) {
                    star.classList.remove('text-gray-300');
                    star.classList.add('text-yellow-400');
                } else {
                    star.classList.remove('text-yellow-400');
                    star.classList.add('text-gray-300');
                }
            });
        }

        function setCoursesRating(rating) {
            const ratingValue = document.getElementById('coursesRatingValue');
            ratingValue.value = rating;

            const stars = document.querySelectorAll('#coursesRatingContainer .courses-rating-star');
            stars.forEach((star, index) => {
                if (index < rating) {
                    star.classList.remove('text-gray-300');
                    star.classList.add('text-yellow-400', 'filled');
                } else {
                    star.classList.remove('text-yellow-400', 'filled');
                    star.classList.add('text-gray-300');
                }
            });
        }

        function resetCoursesVisualRating() {
            const ratingValue = document.getElementById('coursesRatingValue');
            const currentRating = parseInt(ratingValue.value) || 0;
            const stars = document.querySelectorAll('#coursesRatingContainer .courses-rating-star');

            stars.forEach((star, index) => {
                if (index < currentRating) {
                    star.classList.remove('text-gray-300');
                    star.classList.add('text-yellow-400');
                } else {
                    star.classList.remove('text-yellow-400');
                    star.classList.add('text-gray-300');
                }
            });
        }

        function submitCoursesReview(formData) {
            const submitBtn = document.querySelector('#coursesReviewForm button[type="submit"]');
            const originalText = submitBtn.innerHTML;

            // Validate rating
            const ratingValue = document.getElementById('coursesRatingValue').value;
            if (!ratingValue || ratingValue === '0') {
                alert('Please select a rating');
                return;
            }

            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Submitting...';

            fetch('../api/reviews.php', {
                method: 'POST',
                body: JSON.stringify({
                    type: formData.get('type'),
                    item_id: formData.get('item_id'),
                    rating: formData.get('rating'),
                    review_title: formData.get('review_title'),
                    review_text: formData.get('review_text')
                }),
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    closeReviewModal();
                    setTimeout(() => {
                        location.reload(); // Reload to show updated course status
                    }, 2000);
                } else {
                    alert(data.error || 'Failed to submit review');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred. Please try again.');
            })
            .finally(() => {
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
            });
        }

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

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