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

$db = getDB();
$courseId = $_GET['id'] ?? 0;

if (!$courseId) {
    header('Location: index.php');
    exit;
}

// Get course details
$stmt = $db->prepare("
    SELECT c.*, cat.name as category_name, cat.icon as category_icon, cat.color as category_color,
           u.username as instructor_name, up.first_name, up.last_name, up.bio as instructor_bio,
           COUNT(DISTINCT ce.id) as enrollment_count,
           AVG(cr.rating) as average_rating,
           COUNT(DISTINCT cr.id) as review_count
    FROM courses c
    LEFT JOIN course_categories cat ON c.category_id = cat.id
    LEFT JOIN users u ON c.instructor_id = u.id
    LEFT JOIN user_profiles up ON u.id = up.user_id
    LEFT JOIN course_enrollments ce ON c.id = ce.course_id AND ce.status IN ('enrolled', 'in_progress', 'completed')
    LEFT JOIN course_reviews cr ON c.id = cr.course_id AND cr.status = 'approved'
    WHERE c.id = ? AND c.status = 'published'
    GROUP BY c.id
");
$stmt->execute([$courseId]);
$course = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$course) {
    $_SESSION['error_message'] = 'Course not found.';
    header('Location: index.php');
    exit;
}

// Get course modules with topics and lessons - hierarchical query
$stmt = $db->prepare("
    SELECT 
        cm.id as module_id, cm.title as module_title, cm.description as module_description, cm.sort_order as module_sort,
        ct.id as topic_id, ct.title as topic_title, ct.sort_order as topic_sort,
        cl.id as lesson_id, cl.title as lesson_title, cl.description as lesson_description, 
        cl.lesson_type, cl.estimated_time, cl.sort_order as lesson_sort
    FROM course_modules cm 
    LEFT JOIN course_topics ct ON cm.id = ct.module_id 
    LEFT JOIN course_lessons cl ON ct.id = cl.topic_id OR (cl.module_id = cm.id AND cl.topic_id IS NULL)
    WHERE cm.course_id = ?
    ORDER BY cm.sort_order, ct.sort_order, cl.sort_order
");
$stmt->execute([$courseId]);
$curriculumData = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Build hierarchical curriculum structure
$curriculum = [];
$currentModule = null;
$currentTopic = null;

foreach ($curriculumData as $row) {
    $modId = $row['module_id'];
    $topicId = $row['topic_id'];
    
    // New module
    if (!isset($curriculum[$modId])) {
        $curriculum[$modId] = [
            'id' => $modId,
            'title' => $row['module_title'],
            'description' => $row['module_description'],
            'sort_order' => $row['module_sort'],
            'topics' => []
        ];
    }
    
    // New topic (if exists)
    if ($topicId && !isset($curriculum[$modId]['topics'][$topicId])) {
        $curriculum[$modId]['topics'][$topicId] = [
            'id' => $topicId,
            'title' => $row['topic_title'],
            'sort_order' => $row['topic_sort'],
            'lessons' => []
        ];
    }
    
    // Add lesson (if exists)
    if (!empty($row['lesson_id'])) {
        $lessonData = [
            'id' => $row['lesson_id'],
            'title' => $row['lesson_title'],
            'description' => $row['lesson_description'],
            'lesson_type' => $row['lesson_type'],
            'estimated_time' => $row['estimated_time'],
            'sort_order' => $row['lesson_sort']
        ];
        
        if ($topicId) {
            $curriculum[$modId]['topics'][$topicId]['lessons'][] = $lessonData;
        } else {
            // Lessons without topic go directly under module
            $curriculum[$modId]['lessons'][] = $lessonData;
        }
    }
}

// Get course reviews
$stmt = $db->prepare("
    SELECT cr.*, u.username, up.first_name, up.last_name
    FROM course_reviews cr
    JOIN users u ON cr.student_id = u.id
    LEFT JOIN user_profiles up ON u.id = up.user_id
    WHERE cr.course_id = ? AND cr.status = 'approved'
    ORDER BY cr.created_at DESC
    LIMIT 10
");
$stmt->execute([$courseId]);
$reviews = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Check if user is enrolled
$userEnrolled = false;
$userProgress = 0;
if (isLoggedIn()) {
    $userId = $_SESSION['user_id'];
    $stmt = $db->prepare("
        SELECT status, progress_percentage
        FROM course_enrollments
        WHERE course_id = ? AND student_id = ?
    ");
    $stmt->execute([$courseId, $userId]);
    $enrollment = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($enrollment) {
        $userEnrolled = true;
        $userProgress = $enrollment['progress_percentage'];
    }
}

// Get related courses
$stmt = $db->prepare("
    SELECT c.*, AVG(cr.rating) as avg_rating, COUNT(cr.id) as review_count
    FROM courses c
    LEFT JOIN course_reviews cr ON c.id = cr.course_id AND cr.status = 'approved'
    WHERE c.category_id = ? AND c.id != ? AND c.status = 'published'
    GROUP BY c.id
    ORDER BY c.created_at DESC
    LIMIT 3
");
$stmt->execute([$course['category_id'], $courseId]);
$relatedCourses = $stmt->fetchAll(PDO::FETCH_ASSOC);

$pageTitle = htmlspecialchars($course['title']) . ' - Mutalex Academy';
?>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($course['title']); ?> - Course Details</title>
    <!-- Load Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Configure Tailwind to use Inter font and custom colors -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'primary-blue': '#007bff',
                        'nav-text': '#555',
                        'light-border': '#eee',
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style>
        /* Load Tailwind CSS */
        @import url('https://cdn.tailwindcss.com');
        /* Use Inter font family */
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=swap');

        body {
            font-family: 'Inter', sans-serif;
            background-color: #f8fafc; /* Slate 50 background */
        }

        /* Custom styles for the shimmer effect (for lazy loading demonstration) */
        .loading-shimmer {
            background: linear-gradient(to right, #f6f7f8 0%, #e8e8e8 20%, #f6f7f8 40%);
            background-size: 800px 104px;
            animation: shimmer 1.5s infinite linear;
        }

        @keyframes shimmer {
            0% {
                background-position: -468px 0;
            }
            100% {
                background-position: 468px 0;
            }
        }

        /* Curriculum toggle styles */
        .curriculum-toggle {
            cursor: pointer;
            position: relative;
        }

        .curriculum-toggle i {
            transition: transform 0.3s ease;
        }

        .curriculum-toggle[aria-expanded="true"] i {
            transform: rotate(180deg);
        }

        .curriculum-content {
            max-height: 0;
            overflow: hidden;
            transition: all 0.3s ease-out;
        }

        .curriculum-content:not(.hidden) {
            max-height: 2000px; /* Adjust based on content */
            opacity: 1;
        }

        /* Counter animation */
        @keyframes countUp {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        [data-target] {
            animation: countUp 0.6s ease-out forwards;
        }

        /* Enhanced hover effects */
        .interactive-card {
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        .interactive-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
        }

        /* Modern card hover effects */
        .modern-card {
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            transform: translateZ(0);
        }

        .modern-card:hover {
            transform: translateY(-8px) scale(1.02);
            box-shadow: 0 25px 50px rgba(0, 0, 0, 0.15);
        }

        /* Gradient text effects */
        .gradient-text {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        /* Smooth scroll behavior */
        html {
            scroll-behavior: smooth;
        }

        /* Custom scrollbar */
        ::-webkit-scrollbar {
            width: 8px;
        }

        ::-webkit-scrollbar-track {
            background: #f1f5f9;
            border-radius: 10px;
        }

        ::-webkit-scrollbar-thumb {
            background: linear-gradient(135deg, #667eea, #764ba2);
            border-radius: 10px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: linear-gradient(135deg, #5a67d8, #6b46c1);
        }

        /* Loading states */
        .loading-skeleton {
            background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
            background-size: 200% 100%;
            animation: loading 1.5s infinite;
        }

        @keyframes loading {
            0% { background-position: -200% 0; }
            100% { background-position: 200% 0; }
        }

        /* Mobile responsiveness */
        @media (max-width: 768px) {
            .hero-section {
                padding: 80px 0;
            }

            .hero-title {
                font-size: 2.5rem;
                line-height: 1.2;
            }

            .modern-card:hover {
                transform: none;
            }
        }

        /* Focus states for accessibility */
        .focus-ring:focus {
            outline: none;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.3);
            border-color: #667eea;
        }

        /* Animation delays for staggered effects */
        .stagger-1 { animation-delay: 0.1s; }
        .stagger-2 { animation-delay: 0.2s; }
        .stagger-3 { animation-delay: 0.3s; }
        .stagger-4 { animation-delay: 0.4s; }

        /* Subtle parallax effect */
        .parallax-element {
            transform: translateZ(0);
            will-change: transform;
        }

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

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

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

                <!-- Desktop Navigation Links -->
                <nav class="hidden md:flex space-x-6 lg:space-x-8 items-center">
                    <!-- 'Home' is now the active link for the main blog page -->
                    <a href="../home" class="nav-link active hover:text-primary-blue transition duration-150">Home</a>
                    <a href="../category?cat=news" class="nav-link text-nav-text hover:text-primary-blue transition duration-150">News</a>
                    <a href="../category?cat=articles" class="nav-link text-nav-text hover:text-primary-blue transition duration-150">Articles</a>
                    <a href="../category?cat=journals" class="nav-link text-nav-text hover:text-primary-blue transition duration-150">Journals</a>
                    <a href="../surveys.php" class="nav-link text-nav-text hover:text-primary-blue transition duration-150">Surveys</a>

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

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

        <!-- Mobile Menu (Hidden by default) -->
        <div id="mobile-menu" class="hidden md:hidden bg-white border-t border-light-border">
            <div class="px-2 pt-2 pb-3 space-y-1 sm:px-3">
                <a href="../home" class="block px-3 py-2 rounded-md text-base font-medium active">Home</a>
                <a href="../category?cat=news" class="block px-3 py-2 rounded-md text-base font-medium text-nav-text hover:bg-gray-100">News</a>
                <a href="../category?cat=articles" class="block px-3 py-2 rounded-md text-base font-medium text-nav-text hover:bg-gray-100">Articles</a>
                <a href="../category?cat=journals" class="block px-3 py-2 rounded-md text-base font-medium text-nav-text hover:bg-gray-100">Journals</a>
                <a href="../surveys.php" class="block px-3 py-2 rounded-md text-base font-medium text-nav-text hover:bg-gray-100">Surveys</a>
                <a href="../login" class="block w-full text-center mt-2 px-4 py-2 text-white bg-primary-blue rounded-lg font-medium hover:bg-blue-600 transition duration-150">Login</a>
            </div>
        </div>
    </header>

<!-- Header & Hero Section -->
<header class="bg-indigo-700 py-16 text-white shadow-lg" style="margin-top: 80px;">
    <div class="container mx-auto px-4 md:px-8">
        <span class="inline-flex items-center rounded-full bg-indigo-500 px-3 py-1 text-sm font-medium text-white mb-4">
            <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19V6l12-3v14L9 19zm0 0l-4 2v-12l4-2m0 0v12m8-14h-4m4 0h-4m4 0l-4 2"></path></svg>
            <?php echo htmlspecialchars($course['category_name'] ?? 'Software Development'); ?>
        </span>
        <h1 class="text-4xl sm:text-5xl font-extrabold mb-4 leading-tight"><?php echo htmlspecialchars($course['title']); ?></h1>
        <p class="text-indigo-200 text-lg mb-6 max-w-3xl"><?php echo htmlspecialchars($course['short_description'] ?? substr($course['description'], 0, 150) . '...'); ?></p>

        <div class="flex flex-col sm:flex-row items-start sm:items-center space-y-4 sm:space-y-0 sm:space-x-8">
            <div class="flex items-center space-x-2">
                <img src="https://placehold.co/40x40/fca5a5/1f2937?text=<?php echo strtoupper(substr($course['first_name'] ?? $course['instructor_name'], 0, 1)); ?>" alt="Instructor Profile" class="w-10 h-10 rounded-full border-2 border-white">
                <span class="text-sm font-semibold text-indigo-100">By <?php echo htmlspecialchars($course['first_name'] && $course['last_name'] ? $course['first_name'] . ' ' . $course['last_name'] : $course['instructor_name']); ?></span>
            </div>
            <div class="flex items-center space-x-1">
                <div class="rating flex gap-1">
                    <?php
                    $rating = $course['average_rating'] ?: 4.7;
                    for ($i = 1; $i <= 5; $i++):
                    ?>
                        <i class="fas fa-star text-lg <?php echo $i <= round($rating) ? 'filled' : ''; ?>"></i>
                    <?php endfor; ?>
                </div>
                <span class="text-lg font-semibold text-white"><?php echo number_format($rating, 1); ?></span>
                <span class="text-indigo-200 text-sm">(<?php echo $course['review_count'] ?: '1,250'; ?> ratings)</span>
            </div>
        </div>

        <!-- Edit Course Button for Instructors -->
        <?php if (canEditCourse($course['instructor_id'])): ?>
            <div class="mt-6">
                <a href="<?php echo BASE_URL; ?>instructor/courses/course_builder.php?id=<?php echo $course['id']; ?>" class="inline-flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg shadow hover:bg-blue-700 transition duration-150">
                    <i class="fas fa-edit mr-2"></i>Edit Course
                </a>
            </div>
        <?php endif; ?>

        <!-- CTA/Pricing Section -->
        <div class="mt-8 p-6 bg-white bg-opacity-10 backdrop-blur-sm rounded-xl max-w-sm">
            <p class="text-3xl font-bold text-white mb-2"><?php echo $course['is_free'] ? 'Free' : formatCurrency($course['price'], $course['currency']); ?></p>
            <button id="enrollButton" class="w-full bg-yellow-400 hover:bg-yellow-500 text-indigo-900 font-bold py-3 rounded-xl transition duration-200 shadow-md hover:shadow-lg">
                <?php if (isLoggedIn()): ?>
                    <?php if ($userEnrolled): ?>
                        <a href="<?php echo BASE_URL; ?>courses/course.php?id=<?php echo $course['id']; ?>" class="inline-flex items-center justify-center gap-2">
                            <i class="fas fa-play"></i>
                            Continue Learning
                        </a>
                    <?php else: ?>
                        <?php if ($course['is_free']): ?>
                            <span onclick="enrollCourse(<?php echo $course['id']; ?>)">Enroll Now</span>
                        <?php else: ?>
                            <span onclick="showPaymentModal(<?php echo $course['id']; ?>, '<?php echo addslashes($course['title']); ?>', <?php echo $course['price']; ?>, '<?php echo $course['currency'] ?: 'USD'; ?>')">Purchase Course</span>
                        <?php endif; ?>
                    <?php endif; ?>
                <?php else: ?>
                    <a href="<?php echo BASE_URL; ?>login.php?redirect=courses/index.php?id=<?php echo $course['id']; ?>">Login to Enroll</a>
                <?php endif; ?>
            </button>
            <p class="text-xs text-indigo-200 mt-2 text-center">30-Day Money-Back Guarantee.</p>
        </div>
    </div>
</header>

<!-- Main Content Grid -->
<main class="container mx-auto px-4 md:px-8 py-12 grid grid-cols-1 lg:grid-cols-3 gap-10">

    <!-- Left Column: Description & Curriculum -->
    <div class="lg:col-span-2 space-y-10">


        <!-- Course Description -->
        <div class="bg-white p-8 rounded-xl shadow-md border border-gray-100">
            <h2 class="text-2xl font-bold text-gray-800 mb-4">What You'll Learn</h2>
            <?php if ($course['learning_objectives']): ?>
                <?php $objectives = json_decode($course['learning_objectives'], true); ?>
                <?php if (is_array($objectives) && !empty($objectives)): ?>
                    <ul class="list-disc list-inside space-y-2 text-gray-600 ml-4">
                        <?php foreach ($objectives as $objective): ?>
                            <li><?php echo htmlspecialchars($objective); ?></li>
                        <?php endforeach; ?>
                    </ul>
                <?php else: ?>
                    <p class="text-gray-600">No learning objectives specified.</p>
                <?php endif; ?>
            <?php else: ?>
                <p class="text-gray-600">No learning objectives specified.</p>
            <?php endif; ?>

            <h2 class="text-2xl font-bold text-gray-800 mt-8 mb-4">Course Details</h2>
            <?php if ($course['description']): ?>
                <p class="text-gray-700 leading-relaxed"><?php echo nl2br(htmlspecialchars($course['description'])); ?></p>
            <?php else: ?>
                <p class="text-gray-600">No course description available.</p>
            <?php endif; ?>
        </div>

        <!-- Curriculum Section -->
        <div class="bg-white p-8 rounded-xl shadow-md border border-gray-100">
            <h2 class="text-2xl font-bold text-gray-800 mb-6">Curriculum</h2>
            <div class="space-y-4">
<?php if (empty($curriculum)): ?>
                    <div class="text-center py-12 px-6">
                        <div class="w-24 h-24 bg-gradient-to-br from-orange-100 to-yellow-100 rounded-2xl flex items-center justify-center mx-auto mb-6">
                            <i class="fas fa-exclamation-triangle text-3xl text-orange-500"></i>
                        </div>
                        <h4 class="text-xl font-semibold text-gray-900 mb-3">Curriculum Coming Soon</h4>
                        <p class="text-gray-600 max-w-md mx-auto mb-6">This course is in development. Lessons will be available once the instructor completes the curriculum.</p>
                        <?php if (hasRole('instructor') && isset($course['instructor_id']) && canEditCourse($course['instructor_id'])): ?>
                            <a href="instructor/courses/course_builder.php?id=<?php echo $course['id']; ?>" 
                               class="inline-flex items-center gap-2 bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-xl font-semibold transition-all shadow-lg">
                                <i class="fas fa-plus"></i>
                                Add Curriculum
                            </a>
                        <?php endif; ?>
                    </div>
                <?php else: ?>
                    <?php foreach ($curriculum as $module): ?>
                        <div class="border border-gray-200 rounded-lg overflow-hidden">
                            <div class="p-4 bg-gray-50">
                                <h3 class="font-semibold text-gray-800 text-lg"><?php echo htmlspecialchars($module['title']); ?></h3>
                                <?php if ($module['description']): ?>
                                    <p class="text-sm text-gray-600 mt-1"><?php echo htmlspecialchars($module['description']); ?></p>
                                <?php endif; ?>
                            </div>
                            
                            <?php if (!empty($module['topics'])): ?>
                                <?php foreach ($module['topics'] as $topic): ?>
                                    <div class="p-4 border-t border-gray-100">
                                        <h4 class="font-medium text-green-600 mb-3"><?php echo htmlspecialchars($topic['title']); ?></h4>
                                        <div class="space-y-3">
                                            <?php foreach ($topic['lessons'] as $lesson): ?>
                                                <div class="flex justify-between items-start ml-2">
                                                    <div class="flex-1">
                                                        <div class="flex items-center gap-2">
                                                            <?php $typeIcons = ['video' => 'fa-play-circle', 'text' => 'fa-file-alt', 'assignment' => 'fa-tasks', 'quiz' => 'fa-question-circle']; ?>
                                                            <i class="fas <?php echo $typeIcons[$lesson['lesson_type']] ?? 'fa-play-circle'; ?> text-gray-400"></i>
                                                            <span class="text-gray-800"><?php echo htmlspecialchars($lesson['title']); ?></span>
                                                        </div>
                                                        <?php if ($lesson['description']): ?>
                                                            <p class="text-sm text-gray-500 ml-6"><?php echo htmlspecialchars($lesson['description']); ?></p>
                                                        <?php endif; ?>
                                                    </div>
                                                    <span class="text-xs text-gray-400"><?php echo isset($lesson['estimated_time']) && $lesson['estimated_time'] ? $lesson['estimated_time'] . ' min' : ''; ?></span>
                                                </div>
                                            <?php endforeach; ?>
                                            
                                            <?php if (empty($topic['lessons'])): ?>
                                                <p class="text-sm text-gray-400 ml-2">No lessons in this topic.</p>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                            
                            <?php if (!empty($module['lessons'])): ?>
                                <div class="p-4 border-t border-gray-100 space-y-3">
                                    <?php foreach ($module['lessons'] as $lesson): ?>
                                        <div class="flex justify-between items-start">
                                            <div class="flex-1">
                                                <div class="flex items-center gap-2">
                                                    <i class="fas fa-play-circle text-gray-400"></i>
                                                    <span class="text-gray-800"><?php echo htmlspecialchars($lesson['title']); ?></span>
                                                </div>
                                            </div>
                                            <span class="text-xs text-gray-400"><?php echo isset($lesson['estimated_time']) && $lesson['estimated_time'] ? $lesson['estimated_time'] . ' min' : ''; ?></span>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</main>

<!-- Student Reviews Section -->
<section class="py-20 bg-gray-50">
    <div class="max-w-7xl mx-auto px-4 md:px-8">
        <div class="text-center mb-16">
            <div class="inline-flex items-center gap-4 glass px-6 py-3 rounded-full mb-6">
                <div class="w-8 h-8 bg-gradient-to-br from-yellow-400 to-orange-500 rounded-lg flex items-center justify-center">
                    <i class="fas fa-star text-white text-sm"></i>
                </div>
                <span class="text-sm font-bold text-gray-700 uppercase tracking-wider">Student Feedback</span>
            </div>
            <h3 class="text-4xl font-black text-gray-900 mb-4">Student Reviews</h3>
            <p class="text-xl text-gray-600 max-w-2xl mx-auto">See what our students say about this course</p>
        </div>

        <!-- Review Submission Form -->
        <?php if (isLoggedIn() && $userEnrolled && $userProgress >= 100): ?>
            <div class="bg-white p-6 sm:p-10 rounded-2xl shadow-xl border border-gray-100">
                <form id="reviewForm">
                    <!-- Hidden inputs for API -->
                    <input type="hidden" name="type" value="course">
                    <input type="hidden" name="item_id" value="<?php echo $courseId; ?>">

                    <!-- Review Title Block -->
                    <div class="flex items-center space-x-3 mb-8">
                        <!-- Icon placeholder -->
                        <div class="p-2 bg-primary-green rounded-xl shadow-md">
                            <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path></svg>
                        </div>
                        <h2 class="text-2xl font-bold text-gray-800">Write a Review</h2>
                    </div>

                    <!-- Rating Section - Now uses Stars -->
                    <div class="mb-8">
                        <label class="block text-gray-700 font-semibold mb-2">Your Rating</label>

                        <div id="rating-container" class="flex space-x-1 cursor-pointer text-4xl" onmouseout="resetVisualRating()">
                            <!-- Star Icons (5 total) -->
                            <div data-rating="1" class="rating-star transition-colors duration-150" onmouseover="visualizeRating(1)" onclick="setRating(1)">
                                <svg class="w-10 h-10 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="rating-star transition-colors duration-150" onmouseover="visualizeRating(2)" onclick="setRating(2)">
                                  <svg class="w-10 h-10 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="rating-star transition-colors duration-150" onmouseover="visualizeRating(3)" onclick="setRating(3)">
                                  <svg class="w-10 h-10 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="rating-star transition-colors duration-150" onmouseover="visualizeRating(4)" onclick="setRating(4)">
                                  <svg class="w-10 h-10 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="rating-star transition-colors duration-150" onmouseover="visualizeRating(5)" onclick="setRating(5)">
                                  <svg class="w-10 h-10 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="rating-value" value="0" required>
                    </div>

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

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

                    <!-- Submit Button -->
                    <div class="flex justify-end">
                        <button type="submit" class="px-6 py-3 bg-gradient-to-r from-primary-violet to-purple-600 text-white font-bold rounded-lg shadow-lg hover:shadow-xl transition-all duration-300 transform hover:scale-[1.01] focus:outline-none focus:ring-4 focus:ring-primary-violet focus:ring-opacity-50">
                            Submit Review
                        </button>
                    </div>
                </form>
            </div>
        <?php elseif (isLoggedIn() && $userEnrolled): ?>
            <div class="bg-blue-50 border border-blue-200 rounded-2xl p-6 mb-12">
                <div class="flex items-center gap-4">
                    <div class="w-12 h-12 bg-blue-100 rounded-xl flex items-center justify-center">
                        <i class="fas fa-info-circle text-blue-600 text-xl"></i>
                    </div>
                    <div>
                        <h4 class="text-lg font-bold text-blue-900">Complete the course to leave a review</h4>
                        <p class="text-blue-700 mt-1">You need to finish all lessons to share your feedback.</p>
                    </div>
                </div>
            </div>
        <?php elseif (!isLoggedIn()): ?>
            <div class="bg-yellow-50 border border-yellow-200 rounded-2xl p-6 mb-12">
                <div class="flex items-center gap-4">
                    <div class="w-12 h-12 bg-yellow-100 rounded-xl flex items-center justify-center">
                        <i class="fas fa-sign-in-alt text-yellow-600 text-xl"></i>
                    </div>
                    <div>
                        <h4 class="text-lg font-bold text-yellow-900">Login to leave a review</h4>
                        <p class="text-yellow-700 mt-1">You must be logged in and have completed the course to share your feedback.</p>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <?php if (!empty($reviews)): ?>
            <!-- Overall Rating Card -->
            <div class="bg-white rounded-2xl p-8 mb-12 shadow-lg border border-gray-100">
                <div class="flex flex-col md:flex-row items-center gap-8">
                    <div class="text-center">
                        <div class="rating flex justify-center gap-2 mb-4">
                            <?php
                            $rating = $course['average_rating'] ?: 4.7;
                            for ($i = 1; $i <= 5; $i++):
                            ?>
                                <i class="fas fa-star text-4xl <?php echo $i <= round($rating) ? 'filled' : ''; ?>"></i>
                            <?php endfor; ?>
                        </div>
                        <div class="text-4xl font-black text-gray-900 mb-2"><?php echo number_format($rating, 1); ?></div>
                        <div class="text-lg font-bold text-gray-700 mb-2"><?php echo $course['review_count']; ?> Reviews</div>
                        <div class="text-sm text-gray-600">Based on verified student feedback</div>
                    </div>

                    <div class="flex-1 w-full md:w-auto">
                        <div class="space-y-3">
                            <?php for ($i = 5; $i >= 1; $i--): ?>
                                <div class="flex items-center gap-4">
                                    <div class="flex items-center gap-2 min-w-0">
                                        <span class="text-sm font-medium text-gray-700"><?php echo $i; ?></span>
                                        <i class="fas fa-star text-yellow-400 text-sm"></i>
                                    </div>
                                    <div class="flex-1 bg-gray-200 rounded-full h-2">
                                        <div class="bg-yellow-400 h-2 rounded-full" style="width: <?php echo ($i <= round($course['average_rating'])) ? '80%' : '20%'; ?>"></div>
                                    </div>
                                    <span class="text-sm text-gray-600 min-w-0"><?php echo rand(5, 25); ?>%</span>
                                </div>
                            <?php endfor; ?>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Individual Reviews -->
            <div class="space-y-8">
                <?php foreach ($reviews as $index => $review): ?>
                    <div class="bg-white rounded-2xl p-8 shadow-lg hover:shadow-xl transition-shadow duration-300 border border-gray-100" style="animation-delay: <?php echo $index * 0.1; ?>s;">
                        <div class="flex items-start justify-between mb-6">
                            <div class="flex items-center gap-4">
                                <div class="w-16 h-16 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-2xl flex items-center justify-center shadow-lg">
                                    <i class="fas fa-user text-white text-xl"></i>
                                </div>
                                <div>
                                    <h5 class="text-lg font-bold text-gray-900"><?php echo htmlspecialchars($review['first_name'] && $review['last_name'] ? $review['first_name'] . ' ' . $review['last_name'] : $review['username']); ?></h5>
                                    <div class="rating flex gap-1 mt-2">
                                        <?php for ($i = 1; $i <= 5; $i++): ?>
                                            <i class="fas fa-star text-lg <?php echo $i <= $review['rating'] ? 'filled' : ''; ?>"></i>
                                        <?php endfor; ?>
                                    </div>
                                </div>
                            </div>
                            <div class="text-right">
                                <div class="bg-gray-100 px-4 py-2 rounded-full text-sm font-bold text-gray-700">
                                    <i class="fas fa-calendar-alt mr-2"></i><?php echo date('M j, Y', strtotime($review['created_at'])); ?>
                                </div>
                            </div>
                        </div>

                        <?php if ($review['review_title']): ?>
                            <h4 class="text-xl font-bold text-gray-900 mb-4 italic">"<?php echo htmlspecialchars($review['review_title']); ?>"</h4>
                        <?php endif; ?>

                        <?php if ($review['review_text']): ?>
                            <div class="bg-gray-50 rounded-xl p-6 border border-gray-100">
                                <p class="text-gray-700 leading-relaxed text-lg"><?php echo htmlspecialchars($review['review_text']); ?></p>
                            </div>
                        <?php endif; ?>

                        <!-- Review Actions -->
                        <div class="flex items-center gap-4 mt-6 pt-6 border-t border-gray-100">
                            <button class="bg-gray-100 px-4 py-2 rounded-full text-sm font-medium text-gray-700 hover:bg-gray-200 transition-colors">
                                <i class="fas fa-thumbs-up mr-2"></i>Helpful
                            </button>
                            <button class="bg-gray-100 px-4 py-2 rounded-full text-sm font-medium text-gray-700 hover:bg-gray-200 transition-colors">
                                <i class="fas fa-reply mr-2"></i>Reply
                            </button>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>

            <!-- Load More Reviews -->
            <?php if (count($reviews) >= 10): ?>
                <div class="text-center mt-12">
                    <button class="bg-gradient-to-r from-indigo-600 to-purple-600 text-white px-8 py-4 rounded-xl font-bold hover:from-indigo-700 hover:to-purple-700 transition-all duration-300 shadow-lg hover:shadow-xl transform hover:-translate-y-1">
                        <i class="fas fa-plus mr-3"></i>Load More Reviews
                    </button>
                </div>
            <?php endif; ?>
        <?php else: ?>
            <div class="text-center py-20">
                <div class="w-24 h-24 bg-gradient-to-br from-gray-200 to-gray-300 rounded-2xl flex items-center justify-center mx-auto mb-8 shadow-lg">
                    <i class="fas fa-comments text-4xl text-gray-400"></i>
                </div>
                <h4 class="text-2xl font-bold text-gray-900 mb-4">No Reviews Yet</h4>
                <p class="text-gray-600 text-lg max-w-md mx-auto mb-8">Be the first to share your experience after completing this course!</p>
                <div class="inline-flex items-center gap-2 bg-gray-100 px-6 py-3 rounded-full">
                    <i class="fas fa-star text-yellow-500"></i>
                    <span class="text-sm font-medium text-gray-700">Reviews will appear here</span>
                </div>
            </div>
        <?php endif; ?>
    </div>
</section>

<style>
<div id="paymentModal" 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">Purchase Course</h2>
                <button onclick="closePaymentModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            <div id="paymentContent">
                <!-- Payment form will be loaded here -->
            </div>
        </div>
    </div>
</div>


<script>
// Wait for the DOM content to be fully loaded
document.addEventListener('DOMContentLoaded', function() {
    // Initialize Lucide icons
    lucide.createIcons();

    // 1. Counter Animation Logic
    const stats = document.querySelectorAll('[data-target]');

    // Intersection Observer for performance: only start animation when visible
    const counterObserver = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const stat = entry.target;
                const target = parseInt(stat.getAttribute('data-target'));
                // Only animate if the target is a valid positive number
                if (!isNaN(target) && target > 0) {
                    animateCounter(stat, 0, target, 2000); // 2000ms duration
                }
                // Stop observing once the animation has started
                counterObserver.unobserve(stat);
            }
        });
    }, {
        threshold: 0.5 // Trigger when 50% of the element is visible
    });

    // Start observing all stat elements
    stats.forEach(stat => {
        counterObserver.observe(stat);
    });

    // Counter animation function
    function animateCounter(element, start, end, duration) {
        const startTime = performance.now();
        const endTime = startTime + duration;

        function updateCounter(currentTime) {
            if (currentTime < endTime) {
                const progress = (currentTime - startTime) / duration;
                // Ease out cubic function for a smooth finish
                const easeOutProgress = 1 - Math.pow(1 - progress, 3);
                const currentValue = Math.floor(start + (end - start) * easeOutProgress);

                // Use Intl.NumberFormat for better number formatting (e.g., 18,500)
                element.textContent = new Intl.NumberFormat().format(currentValue);
                requestAnimationFrame(updateCounter);
            } else {
                element.textContent = new Intl.NumberFormat().format(end);
            }
        }
        requestAnimationFrame(updateCounter);
    }

    // 2. Curriculum toggle functionality
    const curriculumToggles = document.querySelectorAll('.curriculum-toggle');
    curriculumToggles.forEach(toggle => {
        toggle.addEventListener('click', function() {
            const content = this.nextElementSibling;
            const isExpanded = !content.classList.contains('hidden');

            // Toggle content visibility
            content.classList.toggle('hidden');

            // Update aria-expanded for accessibility
            this.setAttribute('aria-expanded', !isExpanded);

            // Rotate chevron icon
            const chevron = this.querySelector('i');
            if (chevron) {
                chevron.style.transform = isExpanded ? 'rotate(0deg)' : 'rotate(180deg)';
            }
        });
    });

    // 3. Performance optimization - lazy load images (mocked for the instructor image)
    const images = document.querySelectorAll('img[data-src]');
    const imageObserver = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const img = entry.target;
                // Load the image source
                img.src = img.dataset.src;
                // Remove the loading shimmer effect
                img.classList.remove('loading-shimmer');
                // Stop observing once loaded
                imageObserver.unobserve(img);
            }
        });
    }, {
        rootMargin: '0px 0px 50px 0px', // Load images slightly before they enter the viewport
        threshold: 0
    });

    images.forEach(img => {
        imageObserver.observe(img);
    });

    // 4. Simple Mock Enrollment Button Handler
    const enrollButtons = document.querySelectorAll('button[onclick*="enrollCourse"]');
    enrollButtons.forEach(button => {
        button.addEventListener('click', function() {
            // In a real application, this would redirect or open a checkout modal
            showNotification('Course added to cart! Proceed to checkout.');
        });
    });

    // Custom Notification Box (replacing forbidden alert())
    function showNotification(message) {
        let notification = document.getElementById('customNotification');
        if (!notification) {
            notification = document.createElement('div');
            notification.id = 'customNotification';
            notification.className = 'fixed bottom-5 right-5 bg-green-600 text-white p-4 rounded-lg shadow-xl transition-opacity duration-300 opacity-0';
            document.body.appendChild(notification);
        }

        notification.textContent = message;
        notification.classList.remove('opacity-0');
        notification.classList.add('opacity-100');

        // Hide after 3 seconds
        setTimeout(() => {
            notification.classList.remove('opacity-100');
            notification.classList.add('opacity-0');
        }, 3000);
    }
});

// Modern enrollment function with loading states
function enrollCourse(courseId) {
// Show modern confirmation dialog
if (!confirm('Are you sure you want to enroll in this course?')) return;

// Show loading state
const enrollBtn = event.target.closest('button');
if (enrollBtn) {
    const originalText = enrollBtn.innerHTML;
    enrollBtn.disabled = true;
    enrollBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Enrolling...';
}

// Make API call
fetch('../api/enrollments.php', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({ course_id: courseId })
})
.then(response => {
    if (!response.ok) {
        return response.text().then(text => {
            console.error('API enrollment returned non-OK response:', text);
            // Try to extract error message from JSON response
            try {
                const json = JSON.parse(text);
                throw new Error(json.message || json.error || 'Server error: ' + response.status);
            } catch (e) {
                if (e instanceof SyntaxError) {
                    throw new Error('Network response was not ok (HTTP ' + response.status + ')');
                }
                throw e;
            }
        });
    }
    return response.json();
})
.then(data => {
    if (data.success) {
        // Show success message
        showToast('Successfully enrolled in the course!', 'success');

        // Reload page after delay
        setTimeout(() => {
            location.reload();
        }, 1500);
    } else {
        // Show error message
        showToast('Enrollment failed: ' + (data.error || 'Unknown error'), 'error');

        // Reset button
        if (enrollBtn) {
            enrollBtn.disabled = false;
            enrollBtn.innerHTML = originalText;
        }
    }
})
.catch(error => {
    console.error('Error:', error);
    showToast('An error occurred. Please try again.', 'error');

    // Reset button
    if (enrollBtn) {
        enrollBtn.disabled = false;
        enrollBtn.innerHTML = originalText;
    }
});
}

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

// Create toast element
const toast = document.createElement('div');
toast.className = `modern-toast fixed top-6 right-6 z-50 p-4 rounded-xl shadow-2xl transform translate-x-full transition-all duration-300 max-w-sm ${
    type === 'success'
        ? 'bg-gradient-to-r from-green-500 to-emerald-500 text-white'
        : 'bg-gradient-to-r from-red-500 to-pink-500 text-white'
}`;

// Add to page
document.body.appendChild(toast);

// Re-initialize icons
lucide.createIcons();

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

// Auto remove after 5 seconds
setTimeout(() => {
    toast.classList.add('translate-x-full');
    setTimeout(() => {
        toast.remove();
    }, 300);
}, 5000);
}

function showPaymentModal(courseId, courseTitle, price, currency) {
// Create modern modal
const modal = document.createElement('div');
modal.className = 'fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm';
modal.innerHTML = `
    <div class="bg-white rounded-2xl shadow-2xl max-w-md w-full max-h-[90vh] overflow-y-auto">
        <div class="p-6 border-b border-gray-100">
            <div class="flex items-center justify-between">
                <h3 class="text-xl font-bold text-gray-900">Purchase Course</h3>
                <button onclick="this.closest('.fixed').remove()" class="text-gray-400 hover:text-gray-600 transition-colors">
                    <i data-lucide="x" class="w-6 h-6"></i>
                </button>
            </div>
        </div>

        <div class="p-6">
            <div class="text-center mb-6">
                <div class="w-16 h-16 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-2xl flex items-center justify-center mx-auto mb-4">
                    <i data-lucide="credit-card" class="w-8 h-8 text-white"></i>
                </div>
                <h4 class="text-lg font-bold text-gray-900 mb-2">${courseTitle}</h4>
                <p class="text-gray-600 mb-4">Complete your purchase to access this course</p>
                <div class="text-3xl font-bold text-indigo-600">${currency} ${price.toFixed(2)}</div>
            </div>

            <form id="paymentForm">
                <input type="hidden" name="item_type" value="course">
                <input type="hidden" name="item_id" value="${courseId}">

                <div class="mb-6">
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Discount Code (Optional)</label>
                    <input type="text" class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all" name="discount_code" placeholder="Enter discount code">
                    <div id="discountMessage" class="mt-2 text-sm"></div>
                </div>

                <div class="mb-6">
                    <label class="block text-sm font-semibold text-gray-700 mb-3">Payment Method</label>
                    <div class="space-y-3">
                        <label class="flex items-center p-4 border border-gray-200 rounded-xl cursor-pointer hover:border-indigo-300 hover:bg-indigo-50 transition-all">
                            <input type="radio" name="gateway" value="paynow" class="text-indigo-600 focus:ring-indigo-500" checked>
                            <div class="ml-3 flex items-center">
                                <i class="fas fa-mobile-alt text-green-600 mr-3 text-lg"></i>
                                <div>
                                    <div class="font-semibold text-gray-900">Paynow</div>
                                    <div class="text-sm text-gray-600">Mobile Money</div>
                                </div>
                            </div>
                        </label>
                        <label class="flex items-center p-4 border border-gray-200 rounded-xl cursor-pointer hover:border-indigo-300 hover:bg-indigo-50 transition-all">
                            <input type="radio" name="gateway" value="paypal" class="text-indigo-600 focus:ring-indigo-500">
                            <div class="ml-3 flex items-center">
                                <i class="fab fa-paypal text-blue-600 mr-3 text-lg"></i>
                                <div>
                                    <div class="font-semibold text-gray-900">PayPal</div>
                                    <div class="text-sm text-gray-600">Credit/Debit Cards</div>
                                </div>
                            </div>
                        </label>
                    </div>
                </div>

                <div id="finalAmount" class="bg-indigo-50 border border-indigo-200 rounded-xl p-4 mb-6">
                    <div class="flex items-center justify-between">
                        <span class="font-semibold text-gray-900">Final Amount:</span>
                        <span class="text-xl font-bold text-indigo-600">${currency} ${price.toFixed(2)}</span>
                    </div>
                </div>

                <button type="submit" class="w-full bg-gradient-to-r from-indigo-600 to-purple-600 text-white py-4 px-6 rounded-xl font-bold hover:from-indigo-700 hover:to-purple-700 transition-all duration-300 shadow-lg hover:shadow-xl transform hover:-translate-y-1" id="payButton">
                    <i data-lucide="credit-card" class="w-5 h-5 mr-2"></i>
                    Proceed to Payment
                </button>
            </form>
        </div>
    </div>
`;

// Add to page
document.body.appendChild(modal);
lucide.createIcons();

// Handle discount code validation
const discountInput = modal.querySelector('input[name="discount_code"]');
discountInput.addEventListener('blur', function() {
    validateDiscountCode(this.value, price, currency);
});

// Handle form submission
const form = modal.querySelector('#paymentForm');
form.addEventListener('submit', function(e) {
    e.preventDefault();
    processPayment(new FormData(this), modal);
});
}

function validateDiscountCode(code, originalPrice, currency) {
const messageElement = document.getElementById('discountMessage');

if (!code.trim()) {
    messageElement.innerHTML = '';
    updateFinalAmount(originalPrice, 0, currency);
    return;
}

messageElement.innerHTML = '<span class="text-blue-600"><i data-lucide="loader" class="w-4 h-4 animate-spin mr-1"></i>Validating...</span>';
lucide.createIcons();

setTimeout(() => {
    if (code.toUpperCase().startsWith('TEST')) {
        const discountAmount = originalPrice * 0.1;
        messageElement.innerHTML = '<span class="text-green-600"><i data-lucide="check" class="w-4 h-4 mr-1"></i>10% discount applied!</span>';
        updateFinalAmount(originalPrice, discountAmount, currency);
    } else {
        messageElement.innerHTML = '<span class="text-red-600"><i data-lucide="x" class="w-4 h-4 mr-1"></i>Invalid discount code</span>';
        updateFinalAmount(originalPrice, 0, currency);
    }
    lucide.createIcons();
}, 1000);
}

function updateFinalAmount(originalPrice, discountAmount, currency) {
const finalAmount = originalPrice - discountAmount;
const finalAmountElement = document.getElementById('finalAmount');

if (discountAmount > 0) {
    finalAmountElement.innerHTML = `
        <div class="flex items-center justify-between">
            <div>
                <span class="font-semibold text-gray-900">Final Amount:</span>
                <div class="text-sm text-green-600">You saved ${currency} ${discountAmount.toFixed(2)}</div>
            </div>
            <span class="text-2xl font-bold text-indigo-600">${currency} ${finalAmount.toFixed(2)}</span>
        </div>
    `;
} else {
    finalAmountElement.innerHTML = `
        <div class="flex items-center justify-between">
            <span class="font-semibold text-gray-900">Final Amount:</span>
            <span class="text-2xl font-bold text-indigo-600">${currency} ${finalAmount.toFixed(2)}</span>
        </div>
    `;
}
}

function processPayment(formData, modalElement = null) {
const payButton = document.getElementById('payButton');
const originalText = payButton.innerHTML;

payButton.disabled = true;
payButton.innerHTML = '<i data-lucide="loader" class="w-5 h-5 animate-spin mr-2"></i>Processing...';
lucide.createIcons();

fetch('../api/payments.php', {
    method: 'POST',
    body: formData
})
.then(response => {
    if (!response.ok) {
        return response.text().then(text => {
            console.error('API payments returned non-OK response:', text);
            // Try to extract error message from JSON response
            try {
                const json = JSON.parse(text);
                throw new Error(json.message || json.error || 'Server error: ' + response.status);
            } catch (e) {
                if (e instanceof SyntaxError) {
                    throw new Error('Network response was not ok (HTTP ' + response.status + ')');
                }
                throw e;
            }
        });
    }
    return response.json();
})
.then(data => {
    if (data.success) {
        if (data.redirect_url) {
            showToast('Redirecting to payment gateway...', 'success');
            setTimeout(() => {
                window.location.href = data.redirect_url;
            }, 1000);
        } else {
            showToast('Payment initiated successfully!', 'success');
            if (modalElement) modalElement.remove();
            setTimeout(() => {
                location.reload();
            }, 1500);
        }
    } else {
        showToast('Payment failed: ' + (data.error || 'Unknown error'), 'error');
    }
})
.catch(error => {
    console.error('Error:', error);
    showToast('An error occurred. Please try again.', 'error');
})
.finally(() => {
    payButton.disabled = false;
    payButton.innerHTML = originalText;
    lucide.createIcons();
});
}

// Initialize page on load
document.addEventListener('DOMContentLoaded', function() {
// Initialize Lucide icons
lucide.createIcons();

// Add fade-in animation to content
const contentElements = document.querySelectorAll('.fade-in');
contentElements.forEach((element, index) => {
    element.style.animationDelay = `${index * 0.1}s`;
});

// Smooth scroll-triggered animations
const observerOptions = {
    threshold: 0.1,
    rootMargin: '0px 0px -50px 0px'
};

const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            entry.target.classList.add('revealed');
        }
    });
}, observerOptions);

// Observe elements for scroll animations
const revealElements = document.querySelectorAll('.reveal-on-scroll');
revealElements.forEach(el => observer.observe(el));

// Add smooth scrolling to lesson links
const lessonLinks = document.querySelectorAll('a[href*="lesson_preview"]');
lessonLinks.forEach(link => {
    link.addEventListener('click', function(e) {
        // Add loading state
        const originalHTML = this.innerHTML;
        this.innerHTML = originalHTML + ' <i data-lucide="loader" class="w-4 h-4 animate-spin ml-2"></i>';
        lucide.createIcons();

        // Reset after a short delay (in case navigation fails)
        setTimeout(() => {
            this.innerHTML = originalHTML;
            lucide.createIcons();
        }, 2000);
    });
});

// Enhanced hover effects for cards
const cards = document.querySelectorAll('.interactive-card');
cards.forEach(card => {
    card.addEventListener('mouseenter', function() {
        this.style.transform = 'translateY(-8px) scale(1.02)';
        this.style.boxShadow = '0 25px 50px rgba(0, 0, 0, 0.15)';
    });
    card.addEventListener('mouseleave', function() {
        this.style.transform = 'translateY(0) scale(1)';
        this.style.boxShadow = '';
    });
});

// Progress bar animation
const progressBars = document.querySelectorAll('.progress-bar');
progressBars.forEach(bar => {
    const width = bar.style.width;
    bar.style.width = '0%';
    setTimeout(() => {
        bar.style.width = width;
    }, 500);
});

// Add click tracking for analytics
const actionButtons = document.querySelectorAll('button[onclick*="enrollCourse"], button[onclick*="showPaymentModal"]');
actionButtons.forEach(button => {
    button.addEventListener('click', function() {
        // Could send analytics event here
        console.log('Action button clicked:', this.textContent.trim());
    });
});

// Keyboard navigation enhancements
document.addEventListener('keydown', function(e) {
    // ESC key to close modals
    if (e.key === 'Escape') {
        const modals = document.querySelectorAll('.fixed');
        modals.forEach(modal => modal.remove());
    }
});

// Add loading states to forms
const forms = document.querySelectorAll('form');
forms.forEach(form => {
    form.addEventListener('submit', function() {
        const submitBtn = form.querySelector('button[type="submit"]');
        if (submitBtn) {
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i data-lucide="loader" class="w-5 h-5 animate-spin mr-2"></i>Processing...';
            lucide.createIcons();
        }
    });
});

// Parallax effect for hero section (subtle)
let lastScrollY = window.scrollY;
const heroSection = document.querySelector('.hero-section');

if (heroSection) {
    window.addEventListener('scroll', () => {
        const currentScrollY = window.scrollY;
        const deltaY = currentScrollY - lastScrollY;

        // Subtle parallax effect
        const translateY = Math.min(currentScrollY * 0.5, 100);
        heroSection.style.transform = `translateY(${translateY}px)`;

        lastScrollY = currentScrollY;
    });
}

// Add dynamic stats counter animation
const statNumbers = document.querySelectorAll('.stat-number');
statNumbers.forEach(stat => {
    const target = parseInt(stat.textContent.replace(/[^\d]/g, ''));
    if (target && target > 0) {
        animateCounter(stat, 0, target, 2000);
    }
});
});

// Counter animation function
function animateCounter(element, start, end, duration) {
const startTime = performance.now();
const endTime = startTime + duration;

function updateCounter(currentTime) {
    if (currentTime < endTime) {
        const progress = (currentTime - startTime) / duration;
        const easeOutProgress = 1 - Math.pow(1 - progress, 3); // Ease out cubic
        const currentValue = Math.floor(start + (end - start) * easeOutProgress);

        element.textContent = currentValue.toLocaleString() + (element.textContent.includes('+') ? '+' : '');
        requestAnimationFrame(updateCounter);
    } else {
        element.textContent = end.toLocaleString() + (element.textContent.includes('+') ? '+' : '');
    }
}

requestAnimationFrame(updateCounter);
}

// Performance optimization - lazy load images
document.addEventListener('DOMContentLoaded', function() {
const images = document.querySelectorAll('img[data-src]');
const imageObserver = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            const img = entry.target;
            img.src = img.dataset.src;
            img.classList.remove('loading-shimmer');
            imageObserver.unobserve(img);
        }
    });
});

images.forEach(img => imageObserver.observe(img));
});

// Rating Stars Functions
function visualizeRating(rating) {
    const stars = document.querySelectorAll('#rating-container .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 setRating(rating) {
    const ratingValue = document.getElementById('rating-value');
    ratingValue.value = rating;

    const stars = document.querySelectorAll('#rating-container .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 resetVisualRating() {
    const ratingValue = document.getElementById('rating-value');
    const currentRating = parseInt(ratingValue.value) || 0;
    const stars = document.querySelectorAll('#rating-container .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');
        }
    });
}

// Review Form Functionality
document.addEventListener('DOMContentLoaded', function() {
    const reviewForm = document.getElementById('reviewForm');
    if (!reviewForm) return;

    const submitBtn = reviewForm.querySelector('button[type="submit"]');

    // Form submission
    reviewForm.addEventListener('submit', function(e) {
        e.preventDefault();

        const ratingValue = document.getElementById('rating-value').value;
        if (!ratingValue || ratingValue === '0') {
            showToast('Please select a rating', 'error');
            return;
        }

        const formData = new FormData(this);
        const originalText = submitBtn.innerHTML;

        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) {
                showToast(data.message, 'success');
                // Reload page to show the new review
                setTimeout(() => {
                    location.reload();
                }, 2000);
            } else {
                showToast(data.error || 'Failed to submit review', 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('An error occurred. Please try again.', 'error');
        })
        .finally(() => {
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalText;
        });
    });
});
</script>

<!-- START OF FOOTER -->
    <footer style="background-color: #73D216;" class="text-white mt-auto">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10">

            <div class="grid grid-cols-1 md:grid-cols-4 gap-8 border-b border-gray-300 pb-8">

                <!-- 1. Logo/Brand Section -->
                <div class="col-span-1 md:col-span-2">
                    <a href="../index.php" class="text-2xl font-extrabold text-white tracking-wider">
                        Mutalex Academy
                    </a>
                    <p class="mt-4 text-gray-100 text-sm max-w-sm">
                        Empowering learners with quality courses and educational resources.
                    </p>
                    <div class="mt-6 flex space-x-4">
                        <!-- Placeholder for Logo/Image (using text here) -->
                        <div class="h-10 w-10 bg-white text-green-600 rounded-lg flex items-center justify-center font-bold text-lg">MA</div>
                    </div>
                </div>

                <!-- 2. Quick Links -->
                <div>
                    <h4 class="text-lg font-semibold text-white mb-4">Quick Links</h4>
                    <ul class="space-y-2">
                        <li><a href="../index.php" class="text-gray-100 hover:text-white transition duration-300">Home</a></li>
                        <li><a href="catalog.php" class="text-gray-100 hover:text-white transition duration-300">Courses</a></li>
                        <li><a href="../category.php" class="text-gray-100 hover:text-white transition duration-300">Categories</a></li>
                        <li><a href="../student/dashboard.php" class="text-gray-100 hover:text-white transition duration-300">Dashboard</a></li>
                        <li><a href="../login.php" class="text-gray-100 hover:text-white transition duration-300">Login</a></li>
                    </ul>
                </div>

                <!-- 3. Connect/Social Media -->
                <div>
                    <h4 class="text-lg font-semibold text-white mb-4">Connect</h4>
                    <div class="flex space-x-6">
                        <a href="#" class="text-gray-100 hover:text-white transition duration-300">
                            <i class="fab fa-facebook-f text-xl"></i>
                        </a>
                        <a href="#" class="text-gray-100 hover:text-white transition duration-300">
                            <i class="fab fa-twitter text-xl"></i>
                        </a>
                        <a href="#" class="text-gray-100 hover:text-white transition duration-300">
                            <i class="fab fa-linkedin-in text-xl"></i>
                        </a>
                        <a href="#" class="text-gray-100 hover:text-white transition duration-300">
                            <i class="fab fa-instagram text-xl"></i>
                        </a>
                    </div>
                </div>

            </div>

            <!-- Copyright and Final Links Bar -->
            <div class="mt-8 pt-4 flex flex-col md:flex-row justify-between items-center text-sm text-gray-100">
                <p class="order-2 md:order-1 mt-4 md:mt-0">
                    &copy; 2025 Mutalex Academy. All rights reserved.
                </p>

                <div class="order-1 md:order-2 flex space-x-6">
                    <a href="#" class="hover:text-white transition duration-300">Privacy Policy</a>
                    <a href="#" class="hover:text-white transition duration-300">Terms of Use</a>
                </div>
            </div>

        </div>
    </footer>
    <!-- END OF FOOTER -->