<?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 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);

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

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

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

<style>
        /* Modern Color Palette */
        :root {
            --primary: #6366f1;
            --primary-dark: #4f46e5;
            --primary-light: #a5b4fc;
            --secondary: #64748b;
            --success: #10b981;
            --danger: #ef4444;
            --warning: #f59e0b;
            --info: #06b6d4;
            --gray-50: #f8fafc;
            --gray-100: #f1f5f9;
            --gray-200: #e2e8f0;
            --gray-300: #cbd5e1;
            --gray-400: #94a3b8;
            --gray-500: #64748b;
            --gray-600: #475569;
            --gray-700: #334155;
            --gray-800: #1e293b;
            --gray-900: #0f172a;
        }

        /* Modern Typography */
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
            line-height: 1.6;
            color: var(--gray-800);
        }

        /* Gradient Backgrounds */
        .bg-gradient-primary {
            background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%);
        }

        .bg-gradient-secondary {
            background: linear-gradient(135deg, var(--gray-100) 0%, var(--gray-200) 100%);
        }

        .bg-gradient-card {
            background: linear-gradient(135deg, rgba(255,255,255,0.9) 0%, rgba(255,255,255,0.7) 100%);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255,255,255,0.2);
        }

        /* Enhanced Shadows */
        .shadow-modern {
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }

        .shadow-modern-lg {
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }

        .shadow-modern-xl {
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
        }

        /* Rating Stars */
        .rating .fas.fa-star {
            color: var(--gray-300);
            transition: all 0.3s ease;
        }
        .rating .fas.fa-star.filled {
            color: var(--warning);
            filter: drop-shadow(0 0 2px rgba(245, 158, 11, 0.3));
        }

        /* Modern Animations */
        .animate-fade-in {
            animation: fadeIn 0.6s cubic-bezier(0.4, 0, 0.2, 1);
        }

        .animate-slide-up {
            animation: slideUp 0.6s cubic-bezier(0.4, 0, 0.2, 1);
        }

        .animate-scale-in {
            animation: scaleIn 0.4s cubic-bezier(0.4, 0, 0.2, 1);
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        @keyframes slideUp {
            from { opacity: 0; transform: translateY(30px); }
            to { opacity: 1; transform: translateY(0); }
        }

        @keyframes scaleIn {
            from { opacity: 0; transform: scale(0.95); }
            to { opacity: 1; transform: scale(1); }
        }

        /* Hover Effects */
        .hover-lift {
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        .hover-lift:hover {
            transform: translateY(-4px);
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.15);
        }

        /* Modern Buttons */
        .btn-modern {
            background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%);
            color: white;
            border: none;
            padding: 0.75rem 1.5rem;
            border-radius: 0.75rem;
            font-weight: 600;
            font-size: 0.875rem;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            box-shadow: 0 4px 14px 0 rgba(99, 102, 241, 0.3);
        }

        .btn-modern:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px 0 rgba(99, 102, 241, 0.4);
        }

        .btn-modern:active {
            transform: translateY(0);
        }

        /* Glassmorphism Effect */
        .glass {
            background: rgba(255, 255, 255, 0.25);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.18);
        }

        /* Modern Progress Bar */
        .progress-modern {
            background: linear-gradient(90deg, var(--success) 0%, var(--success) var(--progress), var(--gray-200) var(--progress), var(--gray-200) 100%);
            border-radius: 0.5rem;
            height: 0.5rem;
            position: relative;
            overflow: hidden;
        }
        
        .progress-modern::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.4), transparent);
            animation: shimmer 2s infinite;
        }
        
        @keyframes shimmer {
            0% { transform: translateX(-100%); }
            100% { transform: translateX(100%); }
        }
        
        /* Responsive Enhancements */
        @media (max-width: 768px) {
            .hero-title {
                font-size: 2.5rem !important;
                line-height: 1.2 !important;
            }
        
            .course-stats-grid {
                grid-template-columns: repeat(2, 1fr) !important;
                gap: 1rem !important;
            }
        
            .tab-navigation {
                flex-wrap: wrap !important;
            }
        
            .tab-button {
                flex: 1 1 50% !important;
                min-width: 140px !important;
            }
        
            .sidebar-sticky {
                position: static !important;
                margin-bottom: 2rem !important;
            }
        
            .instructor-grid {
                grid-template-columns: 1fr !important;
                text-align: center !important;
            }
        
            .review-card {
                padding: 1.5rem !important;
            }
        
            .related-courses-grid {
                grid-template-columns: 1fr !important;
                gap: 1.5rem !important;
            }
        }
        
        @media (max-width: 480px) {
            .hero-title {
                font-size: 2rem !important;
            }
        
            .course-stats-grid {
                grid-template-columns: 1fr !important;
            }
        
            .tab-button {
                flex: 1 1 100% !important;
                padding: 0.75rem !important;
            }
        
            .tab-button div {
                font-size: 0.875rem !important;
            }
        
            .tab-button i {
                font-size: 1rem !important;
            }
        
            .btn-modern {
                padding: 0.75rem 1.5rem !important;
                font-size: 0.875rem !important;
            }
        
            .glass-card {
                padding: 1rem !important;
            }
        
            .rating-stars {
                gap: 0.25rem !important;
            }
        
            .rating-stars i {
                font-size: 0.875rem !important;
            }
        }
        
        /* Touch-friendly interactions */
        @media (hover: none) and (pointer: coarse) {
            .hover-lift:hover {
                transform: none !important;
            }
        
            .btn-modern:hover {
                transform: none !important;
                box-shadow: 0 4px 14px 0 rgba(99, 102, 241, 0.3) !important;
            }
        }
        
        /* High contrast mode support */
        @media (prefers-contrast: high) {
            .glass {
                background: rgba(255, 255, 255, 0.95) !important;
                border: 2px solid #000 !important;
            }
        
            .bg-gradient-card {
                background: #fff !important;
                border: 2px solid #000 !important;
            }
        }
        
        /* Reduced motion support */
        @media (prefers-reduced-motion: reduce) {
            .animate-fade-in,
            .animate-slide-up,
            .animate-scale-in {
                animation: none !important;
            }
        
            .hover-lift {
                transition: none !important;
            }
        
            .progress-modern::after {
                animation: none !important;
            }
        }
    </style>
</head>
<body class="antialiased">

<!-- Course Header -->
<section class="bg-gradient-secondary py-16 animate-fade-in">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-12">
            <!-- Course Info -->
            <div class="lg:col-span-2 space-y-8">
                <div class="flex items-center gap-3 animate-slide-up">
                    <div class="flex items-center gap-3 glass px-6 py-3 rounded-full shadow-modern hover-lift">
                        <i class="<?php echo htmlspecialchars($course['category_icon']); ?> text-2xl" style="color: <?php echo htmlspecialchars($course['category_color']); ?>; filter: drop-shadow(0 0 8px rgba(0,0,0,0.1));"></i>
                        <span class="text-sm font-semibold text-gray-700 tracking-wide"><?php echo htmlspecialchars($course['category_name']); ?></span>
                    </div>
                </div>

                <h1 class="hero-title text-5xl font-black text-gray-900 leading-tight animate-slide-up" style="animation-delay: 0.1s; background: linear-gradient(135deg, var(--gray-900) 0%, var(--gray-700) 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text;"><?php echo htmlspecialchars($course['title']); ?></h1>

                <p class="text-xl text-gray-600 leading-relaxed animate-slide-up max-w-3xl" style="animation-delay: 0.2s;"><?php echo htmlspecialchars($course['description']); ?></p>

                <div class="course-stats-grid grid grid-cols-2 md:grid-cols-4 gap-6 animate-slide-up" style="animation-delay: 0.3s;">
                    <div class="glass p-4 rounded-xl hover-lift">
                        <div class="flex items-center gap-3">
                            <div class="w-10 h-10 bg-gradient-primary rounded-lg flex items-center justify-center">
                                <i class="fas fa-user text-white text-sm"></i>
                            </div>
                            <div>
                                <p class="text-xs text-gray-500 uppercase tracking-wider font-semibold">Instructor</p>
                                <p class="text-sm font-medium text-gray-800"><?php echo htmlspecialchars($course['first_name'] && $course['last_name'] ? $course['first_name'] . ' ' . $course['last_name'] : $course['instructor_name']); ?></p>
                            </div>
                        </div>
                    </div>

                    <div class="glass p-4 rounded-xl hover-lift">
                        <div class="flex items-center gap-3">
                            <div class="w-10 h-10 bg-gradient-to-br from-green-400 to-green-600 rounded-lg flex items-center justify-center">
                                <i class="fas fa-clock text-white text-sm"></i>
                            </div>
                            <div>
                                <p class="text-xs text-gray-500 uppercase tracking-wider font-semibold">Duration</p>
                                <p class="text-sm font-medium text-gray-800"><?php echo $course['duration_hours']; ?> hours</p>
                            </div>
                        </div>
                    </div>

                    <div class="glass p-4 rounded-xl hover-lift">
                        <div class="flex items-center gap-3">
                            <div class="w-10 h-10 bg-gradient-to-br from-purple-400 to-purple-600 rounded-lg flex items-center justify-center">
                                <i class="fas fa-signal text-white text-sm"></i>
                            </div>
                            <div>
                                <p class="text-xs text-gray-500 uppercase tracking-wider font-semibold">Level</p>
                                <p class="text-sm font-medium text-gray-800"><?php echo ucfirst($course['level']); ?></p>
                            </div>
                        </div>
                    </div>

                    <div class="glass p-4 rounded-xl hover-lift">
                        <div class="flex items-center gap-3">
                            <div class="w-10 h-10 bg-gradient-to-br from-orange-400 to-orange-600 rounded-lg flex items-center justify-center">
                                <i class="fas fa-users text-white text-sm"></i>
                            </div>
                            <div>
                                <p class="text-xs text-gray-500 uppercase tracking-wider font-semibold">Students</p>
                                <p class="text-sm font-medium text-gray-800"><?php echo $course['enrollment_count']; ?> enrolled</p>
                            </div>
                        </div>
                    </div>
                </div>

                <?php if ($course['average_rating']): ?>
                    <div class="flex items-center gap-4 animate-slide-up glass p-4 rounded-xl" style="animation-delay: 0.4s;">
                        <div class="rating flex gap-1">
                            <?php for ($i = 1; $i <= 5; $i++): ?>
                                <i class="fas fa-star text-lg <?php echo $i <= round($course['average_rating']) ? 'filled' : ''; ?>"></i>
                            <?php endfor; ?>
                        </div>
                        <span class="text-2xl font-bold text-gray-900"><?php echo number_format($course['average_rating'], 1); ?></span>
                        <span class="text-gray-600 font-medium">(<?php echo $course['review_count']; ?> reviews)</span>
                        <div class="w-px h-6 bg-gray-300"></div>
                        <div class="flex items-center gap-2">
                            <i class="fas fa-certificate text-yellow-500"></i>
                            <span class="text-sm font-medium text-gray-700">Verified Reviews</span>
                        </div>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Course Sidebar -->
            <div class="lg:col-span-1">
                <div class="bg-gradient-card rounded-2xl shadow-modern-xl p-8 sidebar-sticky sticky top-6 animate-scale-in hover-lift">
                    <div class="mb-8">
                        <?php if ($course['thumbnail']): ?>
                            <div class="relative overflow-hidden rounded-xl shadow-modern">
                                <img src="<?php echo htmlspecialchars($course['thumbnail']); ?>" alt="<?php echo htmlspecialchars($course['title']); ?>" class="w-full h-56 object-cover transition-transform duration-300 hover:scale-105">
                                <div class="absolute inset-0 bg-gradient-to-t from-black/20 to-transparent"></div>
                            </div>
                        <?php else: ?>
                            <div class="w-full h-56 bg-gradient-primary rounded-xl flex items-center justify-center shadow-modern relative overflow-hidden">
                                <div class="absolute inset-0 bg-gradient-to-br from-white/20 to-transparent"></div>
                                <i class="<?php echo htmlspecialchars($course['category_icon'] ?? 'fas fa-graduation-cap'); ?> fa-5x text-white opacity-90"></i>
                                <div class="absolute bottom-4 left-4 right-4">
                                    <div class="bg-white/20 backdrop-blur-sm rounded-lg px-3 py-1">
                                        <span class="text-white text-sm font-medium"><?php echo htmlspecialchars($course['category_name']); ?></span>
                                    </div>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>

                    <div class="text-center space-y-6">
                        <?php if ($course['is_free']): ?>
                            <div class="text-4xl font-black text-green-500 mb-2 animate-pulse">FREE</div>
                            <div class="text-sm text-gray-600 font-medium">No payment required</div>
                        <?php else: ?>
                            <div class="text-4xl font-black text-gray-900 mb-2"><?php echo formatCurrency($course['price'], $course['currency']); ?></div>
                            <div class="text-sm text-gray-600 font-medium">One-time payment</div>
                        <?php endif; ?>

                        <?php if (isLoggedIn()): ?>
                            <?php if ($userEnrolled): ?>
                                <div class="space-y-6">
                                    <div class="glass p-4 rounded-xl">
                                        <div class="flex justify-between text-sm font-semibold text-gray-700 mb-3">
                                            <span>Your Progress</span>
                                            <span class="text-primary"><?php echo round($userProgress); ?>%</span>
                                        </div>
                                        <div class="progress-modern rounded-full h-3" style="--progress: <?php echo $userProgress; ?>%">
                                            <div class="h-full bg-gradient-to-r from-green-400 to-green-600 rounded-full transition-all duration-500 ease-out" style="width: <?php echo $userProgress; ?>%"></div>
                                        </div>
                                        <div class="mt-2 text-xs text-gray-600 text-center">
                                            <?php echo round($userProgress); ?>% completed
                                        </div>
                                    </div>

                                    <a href="learn.php?id=<?php echo $course['id']; ?>" class="w-full btn-modern flex items-center justify-center gap-3 py-4 text-lg font-semibold">
                                        <i class="fas fa-play text-xl"></i>
                                        <span>Continue Learning</span>
                                    </a>
                                </div>
                            <?php else: ?>
                                <?php if ($course['is_free']): ?>
                                    <button onclick="enrollCourse(<?php echo $course['id']; ?>)" class="w-full btn-modern flex items-center justify-center gap-3 py-4 text-lg font-semibold">
                                        <i class="fas fa-plus text-xl"></i>
                                        <span>Enroll Now - Free</span>
                                    </button>
                                <?php else: ?>
                                    <button onclick="showPaymentModal(<?php echo $course['id']; ?>, '<?php echo addslashes($course['title']); ?>', <?php echo $course['price']; ?>, '<?php echo $course['currency'] ?: 'USD'; ?>')" class="w-full btn-modern flex items-center justify-center gap-3 py-4 text-lg font-semibold">
                                        <i class="fas fa-credit-card text-xl"></i>
                                        <span>Purchase Course</span>
                                    </button>
                                <?php endif; ?>
                            <?php endif; ?>
                        <?php else: ?>
                            <a href="../login.php?redirect=courses/detail.php?id=<?php echo $course['id']; ?>" class="w-full glass border-2 border-primary text-primary py-4 px-6 rounded-xl font-bold hover:bg-primary hover:text-white transition-all duration-300 flex items-center justify-center gap-3 text-lg">
                                <i class="fas fa-sign-in-alt text-xl"></i>
                                <span>Login to Enroll</span>
                            </a>
                        <?php endif; ?>

                        <!-- Course Features -->
                        <div class="pt-6 border-t border-gray-200">
                            <h4 class="text-sm font-bold text-gray-800 uppercase tracking-wider mb-4">Course Includes</h4>
                            <div class="space-y-3 text-left">
                                <div class="flex items-center gap-3">
                                    <i class="fas fa-video text-green-500 text-sm"></i>
                                    <span class="text-sm text-gray-700">Video Lectures</span>
                                </div>
                                <div class="flex items-center gap-3">
                                    <i class="fas fa-file-alt text-blue-500 text-sm"></i>
                                    <span class="text-sm text-gray-700">Downloadable Resources</span>
                                </div>
                                <div class="flex items-center gap-3">
                                    <i class="fas fa-certificate text-purple-500 text-sm"></i>
                                    <span class="text-sm text-gray-700">Certificate of Completion</span>
                                </div>
                                <div class="flex items-center gap-3">
                                    <i class="fas fa-infinity text-orange-500 text-sm"></i>
                                    <span class="text-sm text-gray-700">Lifetime Access</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Course Content Tabs -->
<section class="py-20 bg-gradient-secondary">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <!-- Tab Navigation -->
        <div class="bg-gradient-card rounded-2xl shadow-modern-xl overflow-hidden mb-12 animate-fade-in">
            <div class="relative">
                <nav class="tab-navigation flex relative">
                    <button onclick="switchTab('overview')" id="overview-tab" class="tab-button active flex-1 py-6 px-8 text-center font-bold text-primary border-b-4 border-primary bg-gradient-to-b from-primary/5 to-transparent transition-all duration-300 hover:bg-primary/10 relative group">
                        <div class="flex items-center justify-center gap-3">
                            <i class="fas fa-info-circle text-lg"></i>
                            <span class="text-lg">Overview</span>
                        </div>
                        <div class="absolute bottom-0 left-0 right-0 h-1 bg-gradient-primary transform scale-x-0 group-hover:scale-x-100 transition-transform duration-300"></div>
                    </button>
                    <button onclick="switchTab('curriculum')" id="curriculum-tab" class="tab-button flex-1 py-6 px-8 text-center font-bold text-gray-600 hover:text-primary transition-all duration-300 hover:bg-primary/5 relative group">
                        <div class="flex items-center justify-center gap-3">
                            <i class="fas fa-list-ul text-lg"></i>
                            <span class="text-lg">Curriculum</span>
                        </div>
                        <div class="absolute bottom-0 left-0 right-0 h-1 bg-gradient-primary transform scale-x-0 group-hover:scale-x-100 transition-transform duration-300"></div>
                    </button>
                    <button onclick="switchTab('instructor')" id="instructor-tab" class="tab-button flex-1 py-6 px-8 text-center font-bold text-gray-600 hover:text-primary transition-all duration-300 hover:bg-primary/5 relative group">
                        <div class="flex items-center justify-center gap-3">
                            <i class="fas fa-user-tie text-lg"></i>
                            <span class="text-lg">Instructor</span>
                        </div>
                        <div class="absolute bottom-0 left-0 right-0 h-1 bg-gradient-primary transform scale-x-0 group-hover:scale-x-100 transition-transform duration-300"></div>
                    </button>
                    <button onclick="switchTab('reviews')" id="reviews-tab" class="tab-button flex-1 py-6 px-8 text-center font-bold text-gray-600 hover:text-primary transition-all duration-300 hover:bg-primary/5 relative group">
                        <div class="flex items-center justify-center gap-3">
                            <i class="fas fa-star text-lg"></i>
                            <span class="text-lg">Reviews</span>
                        </div>
                        <div class="absolute bottom-0 left-0 right-0 h-1 bg-gradient-primary transform scale-x-0 group-hover:scale-x-100 transition-transform duration-300"></div>
                    </button>
                </nav>
                <!-- Active tab indicator -->
                <div id="tab-indicator" class="absolute bottom-0 h-1 bg-gradient-primary transition-all duration-300 ease-out"></div>
            </div>

            <!-- Tab Content -->
            <div class="p-12">
                <!-- Overview Tab -->
                <div id="overview-content" class="tab-content animate-fade-in">
                    <div class="space-y-12">
                        <?php if ($course['learning_objectives']): ?>
                            <div class="animate-slide-up">
                                <div class="flex items-center gap-4 mb-8">
                                    <div class="w-12 h-12 bg-gradient-primary rounded-xl flex items-center justify-center shadow-modern">
                                        <i class="fas fa-lightbulb text-white text-xl"></i>
                                    </div>
                                    <h3 class="text-3xl font-black text-gray-900">What you'll learn</h3>
                                </div>
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                    <?php
                                    $objectives = json_decode($course['learning_objectives'], true);
                                    if ($objectives):
                                        foreach ($objectives as $index => $objective):
                                    ?>
                                        <div class="glass p-6 rounded-xl hover-lift animate-fade-in" style="animation-delay: <?php echo $index * 0.1; ?>s;">
                                            <div class="flex items-start gap-4">
                                                <div class="w-8 h-8 bg-gradient-to-br from-green-400 to-green-600 rounded-lg flex items-center justify-center flex-shrink-0 shadow-modern">
                                                    <i class="fas fa-check text-white text-sm font-bold"></i>
                                                </div>
                                                <span class="text-gray-700 font-medium leading-relaxed"><?php echo htmlspecialchars($objective); ?></span>
                                            </div>
                                        </div>
                                    <?php endforeach; endif; ?>
                                </div>
                            </div>
                        <?php endif; ?>

                        <?php if ($course['prerequisites']): ?>
                            <div class="animate-slide-up glass p-8 rounded-2xl">
                                <div class="flex items-center gap-4 mb-6">
                                    <div class="w-12 h-12 bg-gradient-to-br from-orange-400 to-orange-600 rounded-xl flex items-center justify-center shadow-modern">
                                        <i class="fas fa-exclamation-triangle text-white text-xl"></i>
                                    </div>
                                    <h3 class="text-3xl font-black text-gray-900">Prerequisites</h3>
                                </div>
                                <div class="bg-orange-50 border border-orange-200 rounded-xl p-6">
                                    <p class="text-gray-700 leading-relaxed text-lg"><?php echo nl2br(htmlspecialchars($course['prerequisites'])); ?></p>
                                </div>
                            </div>
                        <?php endif; ?>

                        <?php if ($course['tags']): ?>
                            <div class="animate-slide-up">
                                <div class="flex items-center gap-4 mb-8">
                                    <div class="w-12 h-12 bg-gradient-to-br from-purple-400 to-purple-600 rounded-xl flex items-center justify-center shadow-modern">
                                        <i class="fas fa-tags text-white text-xl"></i>
                                    </div>
                                    <h3 class="text-3xl font-black text-gray-900">Course Tags</h3>
                                </div>
                                <div class="flex flex-wrap gap-4">
                                    <?php
                                    $tags = json_decode($course['tags'], true);
                                    if ($tags):
                                        foreach ($tags as $index => $tag):
                                    ?>
                                        <span class="glass px-6 py-3 rounded-full text-sm font-bold text-gray-700 hover-lift animate-fade-in transition-all duration-300 hover:bg-primary hover:text-white" style="animation-delay: <?php echo $index * 0.05; ?>s;">
                                            <i class="fas fa-hashtag text-xs mr-2"></i><?php echo htmlspecialchars($tag); ?>
                                        </span>
                                    <?php endforeach; endif; ?>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Curriculum Tab -->
                <div id="curriculum-content" class="tab-content hidden">
                    <div class="animate-fade-in">
                        <div class="flex items-center gap-4 mb-12">
                            <div class="w-12 h-12 bg-gradient-primary rounded-xl flex items-center justify-center shadow-modern">
                                <i class="fas fa-list-ul text-white text-xl"></i>
                            </div>
                            <h3 class="text-3xl font-black text-gray-900">Course Curriculum</h3>
                        </div>

                        <?php if (!empty($lessons)): ?>
                            <div class="space-y-6">
                                <?php foreach ($lessons as $index => $lesson): ?>
                                    <div class="bg-gradient-card rounded-2xl p-8 hover-lift shadow-modern animate-slide-up border border-white/50" style="animation-delay: <?php echo $index * 0.1; ?>s;">
                                        <div class="flex items-start gap-6">
                                            <div class="w-16 h-16 rounded-2xl flex items-center justify-center flex-shrink-0 shadow-modern relative overflow-hidden group">
                                                <div class="absolute inset-0 bg-gradient-primary opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
                                                <i class="fas fa-<?php
                                                    echo $lesson['lesson_type'] === 'video' ? 'play-circle text-2xl text-blue-600 group-hover:text-white' :
                                                          ($lesson['lesson_type'] === 'quiz' ? 'question-circle text-2xl text-green-600 group-hover:text-white' :
                                                          ($lesson['lesson_type'] === 'assignment' ? 'pencil-alt text-2xl text-purple-600 group-hover:text-white' : 'file-alt text-2xl text-gray-600 group-hover:text-white'));
                                                ?> relative z-10 transition-colors duration-300"></i>
                                            </div>
                                            <div class="flex-1">
                                                <div class="flex items-start justify-between mb-4">
                                                    <h4 class="text-xl font-bold text-gray-900 leading-tight"><?php echo htmlspecialchars($lesson['title']); ?></h4>
                                                    <?php if ($lesson['is_preview']): ?>
                                                        <span class="glass px-4 py-2 rounded-full text-sm font-bold text-green-700 bg-green-50 border border-green-200">
                                                            <i class="fas fa-eye mr-2"></i>Preview Available
                                                        </span>
                                                    <?php endif; ?>
                                                </div>
                                                <p class="text-gray-600 mb-6 leading-relaxed text-lg"><?php echo htmlspecialchars($lesson['description']); ?></p>
                                                <div class="flex items-center gap-6">
                                                    <div class="flex items-center gap-2">
                                                        <i class="fas fa-tag text-primary text-sm"></i>
                                                        <span class="text-sm font-semibold text-gray-700 capitalize"><?php echo $lesson['lesson_type']; ?></span>
                                                    </div>
                                                    <?php if ($lesson['estimated_time']): ?>
                                                        <div class="flex items-center gap-2">
                                                            <i class="fas fa-clock text-orange-500 text-sm"></i>
                                                            <span class="text-sm font-semibold text-gray-700"><?php echo $lesson['estimated_time']; ?> min</span>
                                                        </div>
                                                    <?php endif; ?>
                                                    <div class="flex items-center gap-2">
                                                        <i class="fas fa-play-circle text-blue-500 text-sm"></i>
                                                        <span class="text-sm font-semibold text-gray-700">Lesson <?php echo $index + 1; ?></span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>

                            <!-- Curriculum Summary -->
                            <div class="mt-12 glass p-8 rounded-2xl bg-gradient-to-r from-primary/5 to-purple-500/5">
                                <div class="grid grid-cols-1 md:grid-cols-3 gap-8 text-center">
                                    <div>
                                        <div class="text-3xl font-black text-primary mb-2"><?php echo count($lessons); ?></div>
                                        <div class="text-sm font-semibold text-gray-600 uppercase tracking-wider">Total Lessons</div>
                                    </div>
                                    <div>
                                        <div class="text-3xl font-black text-green-600 mb-2"><?php echo array_sum(array_column($lessons, 'estimated_time')); ?> min</div>
                                        <div class="text-sm font-semibold text-gray-600 uppercase tracking-wider">Total Duration</div>
                                    </div>
                                    <div>
                                        <div class="text-3xl font-black text-purple-600 mb-2"><?php echo count(array_filter($lessons, function($l) { return $l['is_preview']; })); ?></div>
                                        <div class="text-sm font-semibold text-gray-600 uppercase tracking-wider">Preview Lessons</div>
                                    </div>
                                </div>
                            </div>
                        <?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-modern">
                                    <i class="fas fa-book-open text-4xl text-gray-400"></i>
                                </div>
                                <h4 class="text-2xl font-bold text-gray-900 mb-4">Curriculum Coming Soon</h4>
                                <p class="text-gray-600 text-lg max-w-md mx-auto">The course content is being carefully prepared and will be available soon. Stay tuned!</p>
                                <div class="mt-8">
                                    <div class="inline-flex items-center gap-2 glass px-6 py-3 rounded-full">
                                        <i class="fas fa-clock text-orange-500"></i>
                                        <span class="text-sm font-medium text-gray-700">Expected release: Soon</span>
                                    </div>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Instructor Tab -->
                <div id="instructor-content" class="tab-content hidden">
                    <div class="animate-fade-in">
                        <div class="flex items-center gap-4 mb-12">
                            <div class="w-12 h-12 bg-gradient-primary rounded-xl flex items-center justify-center shadow-modern">
                                <i class="fas fa-user-tie text-white text-xl"></i>
                            </div>
                            <h3 class="text-3xl font-black text-gray-900">Meet Your Instructor</h3>
                        </div>

                        <div class="bg-gradient-card rounded-2xl p-8 shadow-modern-xl">
                            <div class="instructor-grid flex flex-col lg:flex-row items-start gap-8">
                                <div class="flex-shrink-0">
                                    <div class="relative">
                                        <div class="w-40 h-40 bg-gradient-primary rounded-2xl overflow-hidden shadow-modern-xl">
                                            <?php if (!empty($course['avatar'])): ?>
                                                <img src="<?php echo htmlspecialchars($course['avatar']); ?>" alt="Instructor" class="w-full h-full object-cover">
                                            <?php else: ?>
                                                <div class="w-full h-full bg-gradient-to-br from-gray-200 to-gray-400 flex items-center justify-center">
                                                    <i class="fas fa-user text-6xl text-white"></i>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                        <div class="absolute -bottom-4 -right-4 w-12 h-12 bg-gradient-to-br from-green-400 to-green-600 rounded-xl flex items-center justify-center shadow-modern">
                                            <i class="fas fa-check text-white text-sm font-bold"></i>
                                        </div>
                                    </div>
                                </div>

                                <div class="flex-1 space-y-6">
                                    <div>
                                        <h4 class="text-3xl font-black text-gray-900 mb-2"><?php echo htmlspecialchars($course['first_name'] && $course['last_name'] ? $course['first_name'] . ' ' . $course['last_name'] : $course['instructor_name']); ?></h4>
                                        <div class="flex items-center gap-4">
                                            <span class="glass px-4 py-2 rounded-full text-sm font-bold text-primary bg-primary/10">
                                                <i class="fas fa-graduation-cap mr-2"></i>Expert Instructor
                                            </span>
                                            <span class="glass px-4 py-2 rounded-full text-sm font-bold text-green-700 bg-green-50">
                                                <i class="fas fa-star mr-2"></i>Top Rated
                                            </span>
                                        </div>
                                    </div>

                                    <?php if ($course['instructor_bio']): ?>
                                        <div class="bg-gray-50 rounded-xl p-6 border border-gray-100">
                                            <h5 class="text-lg font-bold text-gray-900 mb-4">About the Instructor</h5>
                                            <p class="text-gray-700 leading-relaxed text-lg"><?php echo htmlspecialchars($course['instructor_bio']); ?></p>
                                        </div>
                                    <?php endif; ?>

                                    <!-- Instructor Stats -->
                                    <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                                        <div class="glass p-4 rounded-xl text-center hover-lift">
                                            <div class="text-2xl font-black text-primary mb-1"><?php echo $course['enrollment_count']; ?>+</div>
                                            <div class="text-xs font-semibold text-gray-600 uppercase tracking-wider">Students Taught</div>
                                        </div>
                                        <div class="glass p-4 rounded-xl text-center hover-lift">
                                            <div class="text-2xl font-black text-green-600 mb-1"><?php echo number_format($course['average_rating'], 1); ?></div>
                                            <div class="text-xs font-semibold text-gray-600 uppercase tracking-wider">Average Rating</div>
                                        </div>
                                        <div class="glass p-4 rounded-xl text-center hover-lift">
                                            <div class="text-2xl font-black text-purple-600 mb-1">5+</div>
                                            <div class="text-xs font-semibold text-gray-600 uppercase tracking-wider">Years Experience</div>
                                        </div>
                                        <div class="glass p-4 rounded-xl text-center hover-lift">
                                            <div class="text-2xl font-black text-orange-600 mb-1">15+</div>
                                            <div class="text-xs font-semibold text-gray-600 uppercase tracking-wider">Courses Created</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Reviews Tab -->
                <div id="reviews-content" class="tab-content hidden">
                    <div class="animate-fade-in">
                        <div class="flex items-center gap-4 mb-12">
                            <div class="w-12 h-12 bg-gradient-primary rounded-xl flex items-center justify-center shadow-modern">
                                <i class="fas fa-star text-white text-xl"></i>
                            </div>
                            <h3 class="text-3xl font-black text-gray-900">Student Reviews</h3>
                        </div>

                        <?php if (!empty($reviews)): ?>
                            <!-- Overall Rating Card -->
                            <div class="bg-gradient-card rounded-2xl p-8 mb-12 shadow-modern-xl">
                                <div class="flex flex-col md:flex-row items-center gap-8">
                                    <div class="text-center">
                                        <div class="text-6xl font-black text-gray-900 mb-4"><?php echo number_format($course['average_rating'], 1); ?></div>
                                        <div class="rating flex justify-center gap-2 mb-4">
                                            <?php for ($i = 1; $i <= 5; $i++): ?>
                                                <i class="fas fa-star text-2xl <?php echo $i <= round($course['average_rating']) ? 'filled' : ''; ?>"></i>
                                            <?php endfor; ?>
                                        </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="review-card bg-gradient-card rounded-2xl p-8 shadow-modern hover-lift animate-slide-up border border-white/50" 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-primary rounded-2xl flex items-center justify-center shadow-modern">
                                                    <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="glass 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="glass px-4 py-2 rounded-full text-sm font-medium text-gray-700 hover:bg-gray-100 transition-colors">
                                                <i class="fas fa-thumbs-up mr-2"></i>Helpful
                                            </button>
                                            <button class="glass px-4 py-2 rounded-full text-sm font-medium text-gray-700 hover:bg-gray-100 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="btn-modern px-8 py-4 text-lg">
                                        <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-modern">
                                    <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 glass 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>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Related Courses -->
<?php if (!empty($relatedCourses)): ?>
<section class="py-20 bg-gradient-secondary">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="text-center mb-16 animate-fade-in">
            <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-primary rounded-lg flex items-center justify-center">
                    <i class="fas fa-compass text-white text-sm"></i>
                </div>
                <span class="text-sm font-bold text-gray-700 uppercase tracking-wider">Explore More</span>
            </div>
            <h3 class="text-4xl font-black text-gray-900 mb-4">Related Courses</h3>
            <p class="text-xl text-gray-600 max-w-2xl mx-auto">Discover more courses in this category to expand your knowledge</p>
        </div>

        <div class="related-courses-grid grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
            <?php foreach ($relatedCourses as $index => $related): ?>
                <div class="bg-gradient-card rounded-2xl overflow-hidden shadow-modern hover-lift animate-slide-up border border-white/50 group" style="animation-delay: <?php echo $index * 0.1; ?>s;">
                    <div class="relative h-56 overflow-hidden">
                        <?php if ($related['thumbnail']): ?>
                            <img src="<?php echo htmlspecialchars($related['thumbnail']); ?>" alt="<?php echo htmlspecialchars($related['title']); ?>" class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110">
                        <?php else: ?>
                            <div class="w-full h-full bg-gradient-primary flex items-center justify-center relative">
                                <div class="absolute inset-0 bg-gradient-to-br from-white/20 to-transparent"></div>
                                <i class="fas fa-graduation-cap text-5xl text-white relative z-10"></i>
                            </div>
                        <?php endif; ?>
                        <div class="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
                        <div class="absolute top-4 left-4">
                            <span class="glass px-3 py-1 rounded-full text-xs font-bold text-white bg-black/30 backdrop-blur-sm">
                                <i class="fas fa-tag mr-1"></i>Related
                            </span>
                        </div>
                    </div>

                    <div class="p-8">
                        <h4 class="text-xl font-bold text-gray-900 mb-4 leading-tight group-hover:text-primary transition-colors duration-300">
                            <a href="detail.php?id=<?php echo $related['id']; ?>" class="hover:text-primary transition-colors duration-300"><?php echo htmlspecialchars($related['title']); ?></a>
                        </h4>

                        <?php if ($related['avg_rating']): ?>
                            <div class="flex items-center gap-3 mb-6">
                                <div class="rating flex gap-1">
                                    <?php for ($i = 1; $i <= 5; $i++): ?>
                                        <i class="fas fa-star text-sm <?php echo $i <= round($related['avg_rating']) ? 'filled' : ''; ?>"></i>
                                    <?php endfor; ?>
                                </div>
                                <span class="text-sm font-bold text-gray-700"><?php echo number_format($related['avg_rating'], 1); ?></span>
                                <span class="text-sm text-gray-600">(<?php echo $related['review_count']; ?> reviews)</span>
                            </div>
                        <?php endif; ?>

                        <div class="flex items-center justify-between">
                            <div class="flex items-center gap-2">
                                <i class="fas fa-users text-primary text-sm"></i>
                                <span class="text-sm text-gray-600">Students enrolled</span>
                            </div>
                            <a href="detail.php?id=<?php echo $related['id']; ?>" class="glass px-6 py-3 rounded-xl text-sm font-bold text-primary hover:bg-primary hover:text-white transition-all duration-300">
                                View Course
                                <i class="fas fa-arrow-right ml-2"></i>
                            </a>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <!-- View All Related Courses -->
        <div class="text-center mt-16">
            <a href="catalog.php?category=<?php echo $course['category_id']; ?>" class="btn-modern px-8 py-4 text-lg inline-flex items-center gap-3">
                <i class="fas fa-th-large"></i>
                <span>View All <?php echo htmlspecialchars($course['category_name']); ?> Courses</span>
                <i class="fas fa-arrow-right"></i>
            </a>
        </div>
    </div>
</section>
<?php endif; ?>

<!-- Payment Modal -->
<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>
// Toast notification system
function showToast(message, type = 'success') {
    // Remove existing toasts
    const existingToasts = document.querySelectorAll('.toast-notification');
    existingToasts.forEach(toast => toast.remove());

    // Create toast element
    const toast = document.createElement('div');
    toast.className = `toast-notification fixed top-4 right-4 z-50 p-4 rounded-lg shadow-lg transform translate-x-full transition-all duration-300 ${
        type === 'success' ? 'bg-green-500 text-white' : 'bg-red-500 text-white'
    }`;
    toast.innerHTML = `
        <div class="flex items-center gap-3">
            <i class="fas ${type === 'success' ? 'fa-check-circle' : 'fa-exclamation-triangle'}"></i>
            <span>${message}</span>
        </div>
    `;

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

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

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

// Tab switching functionality
function switchTab(tabName) {
    // Hide all tab contents
    const contents = document.querySelectorAll('.tab-content');
    contents.forEach(content => content.classList.add('hidden'));

    // Remove active class from all tab buttons
    const buttons = document.querySelectorAll('.tab-button');
    buttons.forEach(button => {
        button.classList.remove('active', 'text-primary', 'border-b-4', 'border-primary', 'bg-gradient-to-b', 'from-primary/5', 'to-transparent');
        button.classList.add('text-gray-600');
    });

    // Show selected tab content with animation
    const selectedContent = document.getElementById(tabName + '-content');
    selectedContent.classList.remove('hidden');
    selectedContent.classList.add('animate-fade-in');

    // Activate selected tab button
    const selectedTab = document.getElementById(tabName + '-tab');
    selectedTab.classList.add('active', 'text-primary', 'border-b-4', 'border-primary', 'bg-gradient-to-b', 'from-primary/5', 'to-transparent');
    selectedTab.classList.remove('text-gray-600');

    // Update tab indicator position
    updateTabIndicator(tabName);
}

function updateTabIndicator(tabName) {
    const indicator = document.getElementById('tab-indicator');
    const activeTab = document.getElementById(tabName + '-tab');

    if (indicator && activeTab) {
        const tabRect = activeTab.getBoundingClientRect();
        const navRect = activeTab.parentElement.getBoundingClientRect();

        indicator.style.width = tabRect.width + 'px';
        indicator.style.left = (tabRect.left - navRect.left) + 'px';
    }
}

// Initialize tab indicator on page load
document.addEventListener('DOMContentLoaded', function() {
    updateTabIndicator('overview');
});

// Update tab indicator on window resize
window.addEventListener('resize', function() {
    const activeTab = document.querySelector('.tab-button.active');
    if (activeTab) {
        const tabName = activeTab.id.replace('-tab', '');
        updateTabIndicator(tabName);
    }
});

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

    fetch('../api/enrollments.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ course_id: courseId })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Show success message
            showToast('Successfully enrolled in the course!', 'success');
            // Reload page after a short delay to show the updated state
            setTimeout(() => {
                location.reload();
            }, 1500);
        } else {
            showToast('Error: ' + data.error, 'error');
            button.disabled = false;
            button.innerHTML = originalText;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('An error occurred. Please try again.', 'error');
        button.disabled = false;
        button.innerHTML = originalText;
    });
}

function showPaymentModal(courseId, courseTitle, price, currency) {
    const modal = document.getElementById('paymentModal');
    const content = document.getElementById('paymentContent');

    content.innerHTML = `
        <div class="text-center mb-6">
            <h3 class="text-xl font-semibold text-gray-900 mb-2">${courseTitle}</h3>
            <p class="text-gray-600 mb-4">Complete your purchase to access this course</p>
            <div class="text-3xl font-bold text-blue-600">${currency} ${price.toFixed(2)}</div>
        </div>

        <form id="paymentForm" class="space-y-6">
            <input type="hidden" name="item_type" value="course">
            <input type="hidden" name="item_id" value="${courseId}">

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

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-3">Payment Method</label>
                <div class="space-y-3">
                    <div class="flex items-center">
                        <input class="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 focus:ring-blue-500" type="radio" name="gateway" value="paynow" id="paynow" checked>
                        <label class="ml-3 text-sm font-medium text-gray-700" for="paynow">
                            <i class="fas fa-mobile-alt mr-2 text-blue-500"></i>Paynow (Mobile Money)
                        </label>
                    </div>
                    <div class="flex items-center">
                        <input class="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 focus:ring-blue-500" type="radio" name="gateway" value="paypal" id="paypal">
                        <label class="ml-3 text-sm font-medium text-gray-700" for="paypal">
                            <i class="fab fa-paypal mr-2 text-blue-500"></i>PayPal
                        </label>
                    </div>
                </div>
            </div>

            <div id="finalAmount" class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <strong class="text-blue-900">Final Amount: ${currency} ${price.toFixed(2)}</strong>
            </div>

            <div class="text-center">
                <button type="submit" class="bg-blue-600 text-white px-8 py-3 rounded-lg font-semibold hover:bg-blue-700 transition duration-200 flex items-center justify-center gap-2 mx-auto" id="payButton">
                    <i class="fas fa-credit-card"></i>Proceed to Payment
                </button>
            </div>
        </form>
    `;

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

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

    modal.classList.remove('hidden');
    modal.classList.add('flex');
}

function closePaymentModal() {
    const modal = document.getElementById('paymentModal');
    modal.classList.add('hidden');
    modal.classList.remove('flex');
}

function validateDiscountCode(code, originalPrice, currency) {
    if (!code.trim()) {
        document.getElementById('discountMessage').innerHTML = '';
        updateFinalAmount(originalPrice, 0, currency);
        return;
    }

    document.getElementById('discountMessage').innerHTML = '<small class="text-gray-500">Validating discount code...</small>';

    setTimeout(() => {
        if (code.toUpperCase().startsWith('TEST')) {
            const discountAmount = originalPrice * 0.1;
            document.getElementById('discountMessage').innerHTML = '<small class="text-green-600">10% discount applied!</small>';
            updateFinalAmount(originalPrice, discountAmount, currency);
        } else {
            document.getElementById('discountMessage').innerHTML = '<small class="text-red-600">Invalid discount code</small>';
            updateFinalAmount(originalPrice, 0, currency);
        }
    }, 500);
}

function updateFinalAmount(originalPrice, discountAmount, currency) {
    const finalAmount = originalPrice - discountAmount;
    document.getElementById('finalAmount').innerHTML = `<strong>Final Amount: ${currency} ${finalAmount.toFixed(2)}</strong>`;
}

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

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

    fetch('../api/payments.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            if (data.redirect_url) {
                window.location.href = data.redirect_url;
            } else {
                showToast('Payment initiated successfully!', 'success');
                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;
    });
}
</script>

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