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

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

if (!$courseId) {
    // If no course ID, show course catalog
    header('Location: catalog.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: catalog.php');
    exit;
}

// Get course lessons/curriculum
$stmt = $db->prepare("
    SELECT * FROM course_lessons
    WHERE course_id = ?
    ORDER BY sort_order
");
$stmt->execute([$courseId]);
$lessons = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Check if user is enrolled
$userEnrolled = false;
$userProgress = 0;
$enrollment = null;
if (isLoggedIn()) {
    $userId = $_SESSION['user_id'];
    $stmt = $db->prepare("
        SELECT * 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'];
    }
}

// Calculate progress stats
$completedLessons = 0;
$totalTimeSpent = 0;
if ($userEnrolled) {
    $stmt = $db->prepare("
        SELECT COUNT(*) as completed, SUM(time_spent) as total_time
        FROM course_lesson_progress
        WHERE enrollment_id = ? AND status = 'completed'
    ");
    $stmt->execute([$enrollment['id']]);
    $progressStats = $stmt->fetch(PDO::FETCH_ASSOC);
    $completedLessons = $progressStats['completed'] ?? 0;
    $totalTimeSpent = $progressStats['total_time'] ?? 0;
}

$progressPercentage = count($lessons) > 0 ? round(($completedLessons / count($lessons)) * 100) : 0;

$pageTitle = htmlspecialchars($course['title']) . ' - Mutalex Academy';
include '../includes/header.php';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($course['title']); ?> - Course Details</title>
    <!-- Load Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Use Inter font family -->
    <style>
        @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;
            }
        }
    </style>
</head>
<body class="antialiased">

<!-- Header & Hero Section -->
<header class="bg-indigo-700 py-16 text-white shadow-lg">
    <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">
                <span class="text-yellow-400">★</span>
                <span class="text-lg font-semibold text-white"><?php echo $course['average_rating'] ? number_format($course['average_rating'], 1) : '4.7'; ?></span>
                <span class="text-indigo-200 text-sm">(<?php echo $course['review_count'] ?: '1,250'; ?> ratings)</span>
            </div>
        </div>

        <!-- 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/lesson_preview.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 Snapshot/Stats Section -->
        <div class="bg-white p-6 rounded-xl shadow-md border border-gray-100">
            <h2 class="text-xl font-bold text-gray-800 mb-4">Course Snapshot</h2>
            <div class="grid grid-cols-2 sm:grid-cols-4 gap-6 text-center">

                <div class="p-3 rounded-lg bg-indigo-50">
                    <p class="text-3xl font-extrabold text-indigo-700" data-target="<?php echo $course['enrollment_count']; ?>">0</p>
                    <p class="text-sm text-gray-500">Students Enrolled</p>
                </div>

                <div class="p-3 rounded-lg bg-green-50">
                    <p class="text-3xl font-extrabold text-green-700" data-target="<?php echo $course['duration_hours']; ?>">0</p>
                    <p class="text-sm text-gray-500">Hours of Content</p>
                </div>

                <div class="p-3 rounded-lg bg-red-50">
                    <p class="text-3xl font-extrabold text-red-700" data-target="<?php echo count($lessons); ?>">0</p>
                    <p class="text-sm text-gray-500">Modules</p>
                </div>

                <div class="p-3 rounded-lg bg-yellow-50">
                    <p class="text-3xl font-extrabold text-yellow-700" data-target="<?php echo $course['review_count']; ?>">0</p>
                    <p class="text-sm text-gray-500">Reviews</p>
                </div>
            </div>
        </div>

        <!-- 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>
            <ul class="list-disc list-inside space-y-2 text-gray-600 ml-4">
                <li>Deep understanding of Promises, Async/Await, and Generators for asynchronous tasks.</li>
                <li>Mastering Array methods like `map`, `reduce`, and `filter` for cleaner code.</li>
                <li>How to structure large-scale applications using modern module patterns.</li>
                <li>Implementing error handling and debugging techniques in modern browsers.</li>
                <li>Practical use of cutting-edge ES2024+ features in real-world projects.</li>
            </ul>

            <h2 class="text-2xl font-bold text-gray-800 mt-8 mb-4">Course Details</h2>
            <p class="text-gray-700 leading-relaxed">
                This course is designed for developers who already have a basic understanding of JavaScript and want to level up their skills to a professional standard. We start with fundamental concepts and quickly dive into advanced topics, ensuring you build both theoretical knowledge and practical experience. Each module includes coding exercises, quizzes, and a final capstone project.
            </p>
            <p class="text-gray-700 leading-relaxed mt-4">
                You will build several mini-projects throughout the course, including a collaborative to-do list, a real-time chat application (mocked with simple front-end logic), and a complex data visualization dashboard using d3.js (mocked).
            </p>
        </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 foreach ($lessons as $lesson): ?>
                    <div class="border border-gray-200 rounded-lg overflow-hidden">
                        <button class="w-full text-left p-4 bg-white font-semibold text-gray-700 flex justify-between items-center hover:bg-gray-50 transition duration-150">
                            <span><?php echo htmlspecialchars($lesson['title']); ?></span>
                            <span class="text-sm font-normal text-gray-500"><?php echo isset($lesson['duration_minutes']) && $lesson['duration_minutes'] ? $lesson['duration_minutes'] . ' mins' : 'Duration TBD'; ?></span>
                        </button>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <!-- Right Column: Instructor & Mock Sticky Sidebar -->
    <div class="lg:col-span-1 space-y-10">

        <!-- Instructor Card -->
        <div class="bg-white p-6 rounded-xl shadow-lg border border-gray-100">
            <h2 class="text-xl font-bold text-gray-800 mb-4 border-b pb-3">About the Instructor</h2>
            <div class="flex items-center space-x-4 mb-4">
                <!-- Image tag updated for lazy loading demonstration -->
                <img data-src="https://placehold.co/80x80/6366f1/ffffff?text=<?php echo strtoupper(substr($course['first_name'] ?? $course['instructor_name'], 0, 1)); ?>" alt="Instructor <?php echo htmlspecialchars($course['first_name'] ?? $course['instructor_name']); ?>" class="w-20 h-20 rounded-full object-cover loading-shimmer" onerror="this.onerror=null;this.src='https://placehold.co/80x80/6366f1/ffffff?text=<?php echo strtoupper(substr($course['first_name'] ?? $course['instructor_name'], 0, 1)); ?>'">
                <div>
                    <p class="text-xl font-semibold text-gray-900"><?php echo htmlspecialchars($course['first_name'] && $course['last_name'] ? $course['first_name'] . ' ' . $course['last_name'] : $course['instructor_name']); ?></p>
                    <p class="text-sm text-indigo-600">Senior Full-Stack Developer</p>
                </div>
            </div>
            <p class="text-gray-600 text-sm leading-relaxed">
                <?php echo htmlspecialchars($course['instructor_bio'] ?? 'Experienced instructor with years of industry experience.'); ?>
            </p>
            <a href="#" class="text-indigo-600 hover:text-indigo-800 text-sm font-medium mt-3 inline-block">View Full Profile →</a>
        </div>

        <!-- Key Features / Certification -->
        <div class="bg-indigo-700 text-white p-6 rounded-xl shadow-lg">
            <h3 class="text-xl font-bold mb-3">What You Get</h3>
            <ul class="space-y-3 text-sm">
                <li class="flex items-center"><svg class="w-5 h-5 mr-2 text-yellow-300" 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 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg> Full Lifetime Access</li>
                <li class="flex items-center"><svg class="w-5 h-5 mr-2 text-yellow-300" 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="M8 14v3m4-3v3m4-3v3M3 21h18M3 10h18M3 7l9-4 9 4M4 10h16v11H4V10z"></path></svg> Complete Certification</li>
                <li class="flex items-center"><svg class="w-5 h-5 mr-2 text-yellow-300" 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="M12 8c1.657 0 3 .895 3 2s-1.343 2-3 2h-1a2 2 0 00-2 2v3m-2-3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg> Code Downloadable Assets</li>
            </ul>
        </div>

    </div>
</main>

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

<!-- Payment Modal -->
<div class="modal fade" id="paymentModal" tabindex="-1">
<div class="modal-dialog modal-lg">
    <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title">Purchase Course</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
            <div id="paymentContent">
                <!-- Payment form will be loaded here -->
            </div>
        </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'
}`;

const icon = type === 'success' ? 'check-circle' : 'exclamation-triangle';

toast.innerHTML = `
    <div class="flex items-center gap-3">
        <i data-lucide="${icon}" class="w-6 h-6 flex-shrink-0"></i>
        <div class="flex-1">
            <p class="font-semibold text-sm">${message}</p>
        </div>
        <button onclick="this.parentElement.parentElement.remove()" class="text-white/70 hover:text-white transition-colors">
            <i data-lucide="x" class="w-4 h-4"></i>
        </button>
    </div>
`;

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

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

<!-- Footer for context -->
<footer class="bg-gray-800 py-6 text-center text-gray-400 text-sm">
    <div class="container mx-auto px-4">
        &copy; 2025 E-Learning Platform. All rights reserved.
    </div>
</footer>

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