<?php
require_once '../includes/middleware.php';
require_once '../config/database.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, u.email as instructor_email,
           up.first_name, up.last_name, up.bio, up.avatar,
           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();

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

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

// Get course reviews
$stmt = $db->prepare("
    SELECT cr.*, u.username, up.first_name, up.last_name, up.avatar
    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();

// Check enrollment status
$isEnrolled = false;
$enrollment = null;
if (isLoggedIn()) {
    $stmt = $db->prepare("SELECT * FROM course_enrollments WHERE course_id = ? AND student_id = ?");
    $stmt->execute([$courseId, $_SESSION['user_id']]);
    $enrollment = $stmt->fetch();
    $isEnrolled = $enrollment !== false;
}

// Get similar courses
$stmt = $db->prepare("
    SELECT c.*, cat.name as category_name,
           COUNT(DISTINCT ce.id) as enrollment_count,
           AVG(cr.rating) as average_rating
    FROM courses c
    LEFT JOIN course_categories cat ON c.category_id = cat.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.category_id = ? AND c.id != ? AND c.status = 'published'
    GROUP BY c.id
    ORDER BY c.created_at DESC
    LIMIT 4
");
$stmt->execute([$course['category_id'], $courseId]);
$similarCourses = $stmt->fetchAll();

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

<!-- Modern Course Hero Section -->
<section class="course-hero">
    <div class="hero-background" style="background: linear-gradient(135deg, <?php echo htmlspecialchars($course['category_color'] ?? '#667eea'); ?> 0%, <?php echo htmlspecialchars($course['category_color'] ?? '#764ba2'); ?> 100%);">
        <div class="hero-overlay">
            <div class="container">
                <div class="hero-content">
                    <div class="hero-main">
                        <!-- Category and Badges -->
                        <div class="hero-badges">
                            <?php if ($course['category_name']): ?>
                                <span class="badge-modern category-badge">
                                    <i class="<?php echo htmlspecialchars($course['category_icon']); ?>"></i>
                                    <?php echo htmlspecialchars($course['category_name']); ?>
                                </span>
                            <?php endif; ?>
                            <span class="badge-modern level-badge"><?php echo htmlspecialchars(ucfirst($course['level'])); ?></span>
                            <?php if ($course['is_featured']): ?>
                                <span class="badge-modern featured-badge">
                                    <i class="fas fa-star"></i>Featured
                                </span>
                            <?php endif; ?>
                        </div>

                        <!-- Course Title -->
                        <h1 class="hero-title"><?php echo htmlspecialchars($course['title']); ?></h1>

                        <!-- Course Description -->
                        <p class="hero-description"><?php echo htmlspecialchars($course['short_description'] ?? ''); ?></p>

                        <!-- Course Stats -->
                        <div class="hero-stats">
                            <div class="stat-item">
                                <div class="stat-icon">
                                    <i class="fas fa-users"></i>
                                </div>
                                <div class="stat-content">
                                    <div class="stat-value"><?php echo number_format($course['enrollment_count']); ?></div>
                                    <div class="stat-label">Students</div>
                                </div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-icon">
                                    <i class="fas fa-clock"></i>
                                </div>
                                <div class="stat-content">
                                    <div class="stat-value"><?php echo $course['duration_hours']; ?>h</div>
                                    <div class="stat-label">Duration</div>
                                </div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-icon">
                                    <i class="fas fa-star"></i>
                                </div>
                                <div class="stat-content">
                                    <div class="stat-value">
                                        <?php if ($course['average_rating']): ?>
                                            <?php echo number_format($course['average_rating'], 1); ?>
                                        <?php else: ?>
                                            N/A
                                        <?php endif; ?>
                                    </div>
                                    <div class="stat-label">Rating</div>
                                </div>
                            </div>
                        </div>

                        <!-- Rating Display -->
                        <?php if ($course['average_rating']): ?>
                            <div class="hero-rating">
                                <div class="rating-stars">
                                    <?php for ($i = 1; $i <= 5; $i++): ?>
                                        <i class="fas fa-star <?php echo $i <= round($course['average_rating']) ? 'filled' : ''; ?>"></i>
                                    <?php endfor; ?>
                                </div>
                                <span class="rating-text"><?php echo number_format($course['average_rating'], 1); ?> (<?php echo $course['review_count']; ?> reviews)</span>
                            </div>
                        <?php endif; ?>

                        <!-- Action Buttons -->
                        <div class="hero-actions">
                            <?php if (isLoggedIn()): ?>
                                <?php if ($isEnrolled): ?>
                                    <a href="content.php?id=<?php echo $course['id']; ?>" class="btn-modern primary">
                                        <i class="fas fa-play"></i>
                                        <span>Continue Learning</span>
                                    </a>
                                <?php elseif (hasPermission('enroll_course')): ?>
                                    <?php if ($course['is_free']): ?>
                                        <button class="btn-modern primary" onclick="enrollCourse(<?php echo $course['id']; ?>)">
                                            <i class="fas fa-plus"></i>
                                            <span>Enroll Now</span>
                                        </button>
                                    <?php else: ?>
                                        <button class="btn-modern primary" onclick="showPaymentModal(<?php echo $course['id']; ?>, '<?php echo addslashes($course['title']); ?>', <?php echo $course['price']; ?>, '<?php echo $course['currency'] ?: 'USD'; ?>')">
                                            <i class="fas fa-credit-card"></i>
                                            <span>Purchase Course</span>
                                        </button>
                                    <?php endif; ?>
                                <?php endif; ?>
                            <?php else: ?>
                                <a href="../login.php?redirect=courses/course.php?id=<?php echo $course['id']; ?>" class="btn-modern primary">
                                    <i class="fas fa-sign-in-alt"></i>
                                    <span>Login to Enroll</span>
                                </a>
                            <?php endif; ?>

                            <!-- Price Display -->
                            <div class="price-display">
                                <?php if ($course['is_free']): ?>
                                    <span class="price-free">Free</span>
                                <?php else: ?>
                                    <span class="price-amount">$<?php echo number_format($course['price'], 2); ?></span>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Course Preview Card -->
                    <div class="hero-sidebar">
                        <div class="preview-card">
                            <div class="preview-image">
                                <?php if ($course['thumbnail']): ?>
                                    <img src="<?php echo htmlspecialchars($course['thumbnail']); ?>" alt="Course thumbnail">
                                <?php else: ?>
                                    <div class="image-placeholder">
                                        <i class="<?php echo htmlspecialchars($course['category_icon'] ?? 'fas fa-graduation-cap'); ?>"></i>
                                    </div>
                                <?php endif; ?>
                            </div>

                            <div class="preview-content">
                                <h3>What you'll learn</h3>
                                <?php if ($course['learning_objectives']): ?>
                                    <?php $objectives = json_decode($course['learning_objectives'], true); ?>
                                    <?php if (is_array($objectives)): ?>
                                        <ul class="learning-objectives">
                                            <?php foreach (array_slice($objectives, 0, 4) as $objective): ?>
                                                <li>
                                                    <i class="fas fa-check"></i>
                                                    <span><?php echo htmlspecialchars($objective); ?></span>
                                                </li>
                                            <?php endforeach; ?>
                                        </ul>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Main Course Content -->
<section class="course-content-section">
    <div class="container">
        <div class="content-grid">

            <!-- Main Content Column -->
            <div class="main-content">

                <!-- Course Description Card -->
                <div class="content-card">
                    <div class="card-header-modern">
                        <div class="card-icon">
                            <i class="fas fa-info-circle"></i>
                        </div>
                        <div class="card-title-section">
                            <h2>About This Course</h2>
                            <p>Learn what this course offers and how it can help you</p>
                        </div>
                    </div>
                    <div class="card-body-modern">
                        <div class="course-description">
                            <?php echo nl2br(htmlspecialchars($course['description'])); ?>
                        </div>
                    </div>
                </div>

                <!-- Curriculum Card -->
                <div class="content-card">
                    <div class="card-header-modern">
                        <div class="card-icon">
                            <i class="fas fa-list-ul"></i>
                        </div>
                        <div class="card-title-section">
                            <h2>Course Curriculum</h2>
                            <p><?php echo count($lessons); ?> lessons • <?php echo array_sum(array_column($lessons, 'estimated_time')); ?> minutes total</p>
                        </div>
                        <div class="card-badge">
                            <span class="badge-modern primary"><?php echo count($lessons); ?> lessons</span>
                        </div>
                    </div>
                    <div class="card-body-modern">
                        <?php if (empty($lessons)): ?>
                            <div class="empty-state">
                                <div class="empty-icon">
                                    <i class="fas fa-book-open"></i>
                                </div>
                                <h3>No Lessons Yet</h3>
                                <p>The curriculum for this course is being prepared.</p>
                            </div>
                        <?php else: ?>
                            <div class="curriculum-list">
                                <?php foreach ($lessons as $index => $lesson): ?>
                                    <div class="curriculum-item <?php echo $index === 0 ? 'expanded' : ''; ?>">
                                        <div class="curriculum-header" onclick="toggleCurriculumItem(this)">
                                            <div class="lesson-info">
                                                <div class="lesson-icon">
                                                    <i class="fas fa-<?php echo $lesson['lesson_type'] === 'video' ? 'play-circle' : ($lesson['lesson_type'] === 'quiz' ? 'question-circle' : 'file-alt'); ?>"></i>
                                                </div>
                                                <div class="lesson-details">
                                                    <h4><?php echo htmlspecialchars($lesson['title']); ?></h4>
                                                    <div class="lesson-meta">
                                                        <span class="lesson-type"><?php echo ucfirst($lesson['lesson_type']); ?></span>
                                                        <?php if ($lesson['estimated_time']): ?>
                                                            <span class="lesson-duration"><?php echo $lesson['estimated_time']; ?> min</span>
                                                        <?php endif; ?>
                                                        <?php if ($lesson['is_preview']): ?>
                                                            <span class="preview-badge">Preview</span>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="curriculum-toggle">
                                                <i class="fas fa-chevron-down"></i>
                                            </div>
                                        </div>
                                        <div class="curriculum-content">
                                            <div class="content-text">
                                                <p><?php echo htmlspecialchars($lesson['description'] ?? 'No description available.'); ?></p>
                                                <?php if ($lesson['is_preview'] && !$isEnrolled): ?>
                                                    <div class="preview-notice">
                                                        <i class="fas fa-eye"></i>
                                                        <span>This is a preview lesson. Enroll to access all content.</span>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Instructor Card -->
                <div class="content-card">
                    <div class="card-header-modern">
                        <div class="card-icon">
                            <i class="fas fa-user-graduate"></i>
                        </div>
                        <div class="card-title-section">
                            <h2>Your Instructor</h2>
                            <p>Learn from industry experts</p>
                        </div>
                    </div>
                    <div class="card-body-modern">
                        <div class="instructor-profile">
                            <div class="instructor-avatar">
                                <?php if ($course['avatar']): ?>
                                    <img src="<?php echo htmlspecialchars($course['avatar']); ?>" alt="Instructor">
                                <?php else: ?>
                                    <div class="avatar-placeholder">
                                        <i class="fas fa-user"></i>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <div class="instructor-details">
                                <h3><?php echo htmlspecialchars($course['first_name'] && $course['last_name'] ? $course['first_name'] . ' ' . $course['last_name'] : $course['instructor_name']); ?></h3>
                                <?php if ($course['bio']): ?>
                                    <p class="instructor-bio"><?php echo htmlspecialchars(substr($course['bio'], 0, 200)); ?>...</p>
                                <?php endif; ?>
                                <a href="mailto:<?php echo htmlspecialchars($course['instructor_email']); ?>" class="btn-modern outline">
                                    <i class="fas fa-envelope"></i>
                                    <span>Contact Instructor</span>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Reviews Card -->
                <div class="content-card">
                    <div class="card-header-modern">
                        <div class="card-icon">
                            <i class="fas fa-star"></i>
                        </div>
                        <div class="card-title-section">
                            <h2>Student Reviews</h2>
                            <p>What our students say about this course</p>
                        </div>
                        <?php if ($course['review_count'] > 0): ?>
                            <div class="card-badge">
                                <span class="badge-modern success"><?php echo $course['review_count']; ?> reviews</span>
                            </div>
                        <?php endif; ?>
                    </div>
                    <div class="card-body-modern">
                        <?php if (empty($reviews)): ?>
                            <div class="empty-state">
                                <div class="empty-icon">
                                    <i class="fas fa-comments"></i>
                                </div>
                                <h3>No Reviews Yet</h3>
                                <p>Be the first to review this course after completing it!</p>
                            </div>
                        <?php else: ?>
                            <div class="reviews-grid">
                                <?php foreach ($reviews as $review): ?>
                                    <div class="review-card-modern">
                                        <div class="review-header-modern">
                                            <div class="reviewer-avatar">
                                                <?php if ($review['avatar']): ?>
                                                    <img src="<?php echo htmlspecialchars($review['avatar']); ?>" alt="Reviewer">
                                                <?php else: ?>
                                                    <div class="avatar-placeholder-small">
                                                        <i class="fas fa-user"></i>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                            <div class="reviewer-info">
                                                <h4><?php echo htmlspecialchars($review['first_name'] && $review['last_name'] ? $review['first_name'] . ' ' . $review['last_name'] : $review['username']); ?></h4>
                                                <div class="review-rating">
                                                    <?php for ($i = 1; $i <= 5; $i++): ?>
                                                        <i class="fas fa-star <?php echo $i <= $review['rating'] ? 'filled' : ''; ?>"></i>
                                                    <?php endfor; ?>
                                                </div>
                                            </div>
                                            <div class="review-date">
                                                <span><?php echo date('M j, Y', strtotime($review['created_at'])); ?></span>
                                            </div>
                                        </div>
                                        <div class="review-content-modern">
                                            <?php if ($review['review_title']): ?>
                                                <h5><?php echo htmlspecialchars($review['review_title']); ?></h5>
                                            <?php endif; ?>
                                            <p><?php echo htmlspecialchars($review['review_text']); ?></p>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

            </div>

            <!-- Sidebar -->
            <div class="sidebar-content">

                <!-- Course Stats Card -->
                <div class="sidebar-card">
                    <div class="card-header-modern">
                        <div class="card-icon">
                            <i class="fas fa-chart-bar"></i>
                        </div>
                        <div class="card-title-section">
                            <h3>Course Stats</h3>
                        </div>
                    </div>
                    <div class="card-body-modern">
                        <div class="stats-grid">
                            <div class="stat-box">
                                <div class="stat-icon-modern">
                                    <i class="fas fa-users"></i>
                                </div>
                                <div class="stat-info">
                                    <div class="stat-value"><?php echo number_format($course['enrollment_count']); ?></div>
                                    <div class="stat-label">Students</div>
                                </div>
                            </div>
                            <div class="stat-box">
                                <div class="stat-icon-modern">
                                    <i class="fas fa-book-open"></i>
                                </div>
                                <div class="stat-info">
                                    <div class="stat-value"><?php echo count($lessons); ?></div>
                                    <div class="stat-label">Lessons</div>
                                </div>
                            </div>
                            <div class="stat-box">
                                <div class="stat-icon-modern">
                                    <i class="fas fa-clock"></i>
                                </div>
                                <div class="stat-info">
                                    <div class="stat-value"><?php echo $course['duration_hours']; ?>h</div>
                                    <div class="stat-label">Duration</div>
                                </div>
                            </div>
                            <div class="stat-box">
                                <div class="stat-icon-modern">
                                    <i class="fas fa-signal"></i>
                                </div>
                                <div class="stat-info">
                                    <div class="stat-value"><?php echo htmlspecialchars(ucfirst($course['level'])); ?></div>
                                    <div class="stat-label">Level</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Course Requirements Card -->
                <div class="sidebar-card">
                    <div class="card-header-modern">
                        <div class="card-icon">
                            <i class="fas fa-clipboard-check"></i>
                        </div>
                        <div class="card-title-section">
                            <h3>Requirements</h3>
                        </div>
                    </div>
                    <div class="card-body-modern">
                        <?php if ($course['prerequisites']): ?>
                            <div class="requirements-list">
                                <?php
                                $prerequisites = explode("\n", $course['prerequisites']);
                                foreach ($prerequisites as $prereq):
                                    if (trim($prereq)):
                                ?>
                                    <div class="requirement-item">
                                        <i class="fas fa-check-circle"></i>
                                        <span><?php echo htmlspecialchars(trim($prereq)); ?></span>
                                    </div>
                                <?php
                                    endif;
                                endforeach;
                                ?>
                            </div>
                        <?php else: ?>
                            <div class="empty-state-small">
                                <i class="fas fa-info-circle"></i>
                                <span>No specific prerequisites required</span>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Similar Courses Card -->
                <?php if (!empty($similarCourses)): ?>
                    <div class="sidebar-card">
                        <div class="card-header-modern">
                            <div class="card-icon">
                                <i class="fas fa-th-large"></i>
                            </div>
                            <div class="card-title-section">
                                <h3>Similar Courses</h3>
                            </div>
                        </div>
                        <div class="card-body-modern">
                            <div class="similar-courses-list">
                                <?php foreach ($similarCourses as $similar): ?>
                                    <a href="course.php?id=<?php echo $similar['id']; ?>" class="similar-course-item">
                                        <div class="course-thumbnail-small">
                                            <?php if ($similar['thumbnail']): ?>
                                                <img src="<?php echo htmlspecialchars($similar['thumbnail']); ?>" alt="Course">
                                            <?php else: ?>
                                                <div class="thumbnail-placeholder-small">
                                                    <i class="fas fa-graduation-cap"></i>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                        <div class="course-info-small">
                                            <h4><?php echo htmlspecialchars(substr($similar['title'], 0, 35)); ?><?php echo strlen($similar['title']) > 35 ? '...' : ''; ?></h4>
                                            <div class="course-meta-small">
                                                <span class="enrollment-count">
                                                    <i class="fas fa-users"></i>
                                                    <?php echo number_format($similar['enrollment_count']); ?>
                                                </span>
                                                <?php if ($similar['average_rating']): ?>
                                                    <span class="rating-small">
                                                        <i class="fas fa-star"></i>
                                                        <?php echo number_format($similar['average_rating'], 1); ?>
                                                    </span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>

            </div>
        </div>
    </div>
</section>

<style>
/* Modern Course Page Styles */

/* Hero Section */
.course-hero {
    position: relative;
    overflow: hidden;
}

.hero-background {
    position: relative;
    padding: 80px 0 60px;
}

.hero-overlay {
    position: relative;
    z-index: 2;
}

.hero-content {
    max-width: 1400px;
    margin: 0 auto;
    padding: 0 2rem;
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 4rem;
    align-items: start;
}

.hero-main {
    color: white;
}

.hero-badges {
    display: flex;
    gap: 0.75rem;
    margin-bottom: 1.5rem;
    flex-wrap: wrap;
}

.badge-modern {
    padding: 0.5rem 1rem;
    border-radius: 25px;
    font-size: 0.875rem;
    font-weight: 600;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    text-decoration: none;
    transition: all 0.3s ease;
}

.badge-modern.category-badge {
    background: rgba(255, 255, 255, 0.2);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.3);
    color: white;
}

.badge-modern.level-badge {
    background: rgba(255, 255, 255, 0.15);
    color: white;
}

.badge-modern.featured-badge {
    background: linear-gradient(135deg, #f59e0b, #d97706);
    color: white;
}

.hero-title {
    font-size: 3.5rem;
    font-weight: 800;
    line-height: 1.1;
    margin-bottom: 1rem;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.hero-description {
    font-size: 1.25rem;
    line-height: 1.6;
    opacity: 0.9;
    margin-bottom: 2rem;
    max-width: 600px;
}

.hero-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
    gap: 1.5rem;
    margin-bottom: 2rem;
}

.stat-item {
    display: flex;
    align-items: center;
    gap: 1rem;
    padding: 1rem;
    background: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(10px);
    border-radius: 12px;
    border: 1px solid rgba(255, 255, 255, 0.2);
}

.stat-icon {
    width: 48px;
    height: 48px;
    border-radius: 12px;
    background: rgba(255, 255, 255, 0.2);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.25rem;
}

.stat-content {
    flex: 1;
}

.stat-value {
    font-size: 1.5rem;
    font-weight: 700;
    display: block;
    line-height: 1;
}

.stat-label {
    font-size: 0.875rem;
    opacity: 0.8;
}

.hero-rating {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    margin-bottom: 2rem;
}

.rating-stars {
    display: flex;
    gap: 0.25rem;
}

.rating-stars .fa-star {
    color: #f59e0b;
    font-size: 1rem;
}

.rating-stars .fa-star:not(.filled) {
    color: rgba(255, 255, 255, 0.5);
}

.rating-text {
    font-size: 1rem;
    opacity: 0.9;
}

.hero-actions {
    display: flex;
    align-items: center;
    gap: 1.5rem;
    margin-bottom: 2rem;
    flex-wrap: wrap;
}

.btn-modern {
    padding: 1rem 2rem;
    border-radius: 12px;
    font-weight: 600;
    font-size: 1rem;
    display: inline-flex;
    align-items: center;
    gap: 0.75rem;
    text-decoration: none;
    transition: all 0.3s ease;
    border: none;
    cursor: pointer;
}

.btn-modern.primary {
    background: white;
    color: #1e293b;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}

.btn-modern.primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.3);
}

.btn-modern.outline {
    background: transparent;
    color: white;
    border: 2px solid rgba(255, 255, 255, 0.3);
}

.btn-modern.outline:hover {
    background: rgba(255, 255, 255, 0.1);
    border-color: rgba(255, 255, 255, 0.5);
}

.price-display {
    display: flex;
    align-items: center;
}

.price-free {
    font-size: 1.5rem;
    font-weight: 700;
    color: #10b981;
    background: rgba(16, 185, 129, 0.1);
    padding: 0.5rem 1rem;
    border-radius: 8px;
    border: 1px solid rgba(16, 185, 129, 0.3);
}

.price-amount {
    font-size: 1.5rem;
    font-weight: 700;
    color: white;
}

.hero-sidebar {
    position: relative;
}

.preview-card {
    background: white;
    border-radius: 16px;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    position: sticky;
    top: 2rem;
}

.preview-image {
    height: 200px;
    overflow: hidden;
    position: relative;
}

.preview-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.image-placeholder {
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, #f3f4f6, #e5e7eb);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 3rem;
    color: #9ca3af;
}

.preview-content {
    padding: 2rem;
}

.preview-content h3 {
    font-size: 1.25rem;
    font-weight: 700;
    color: #1e293b;
    margin-bottom: 1.5rem;
}

.learning-objectives {
    display: flex;
    flex-direction: column;
    gap: 0.75rem;
}

.learning-objectives li {
    display: flex;
    align-items: flex-start;
    gap: 0.75rem;
    font-size: 0.9rem;
    color: #4b5563;
    line-height: 1.5;
}

.learning-objectives li i {
    color: #10b981;
    margin-top: 0.125rem;
    flex-shrink: 0;
}

/* Main Content Section */
.course-content-section {
    padding: 4rem 0;
    background: #f8fafc;
}

.content-grid {
    max-width: 1400px;
    margin: 0 auto;
    padding: 0 2rem;
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 3rem;
}

.main-content {
    display: flex;
    flex-direction: column;
    gap: 2rem;
}

.sidebar-content {
    display: flex;
    flex-direction: column;
    gap: 2rem;
    position: sticky;
    top: 2rem;
    height: fit-content;
}

/* Content Cards */
.content-card, .sidebar-card {
    background: white;
    border-radius: 16px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
    border: 1px solid #e5e7eb;
    overflow: hidden;
    transition: all 0.3s ease;
}

.content-card:hover, .sidebar-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}

.card-header-modern {
    padding: 2rem;
    border-bottom: 1px solid #e5e7eb;
    display: flex;
    align-items: center;
    gap: 1rem;
    background: linear-gradient(135deg, #f8fafc, #f1f5f9);
}

.card-icon {
    width: 48px;
    height: 48px;
    border-radius: 12px;
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.25rem;
    flex-shrink: 0;
}

.card-title-section h2, .card-title-section h3 {
    font-size: 1.5rem;
    font-weight: 700;
    color: #1e293b;
    margin: 0 0 0.25rem 0;
}

.card-title-section p {
    font-size: 0.9rem;
    color: #64748b;
    margin: 0;
}

.card-badge {
    margin-left: auto;
}

.badge-modern.primary {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
}

.badge-modern.success {
    background: linear-gradient(135deg, #10b981, #059669);
    color: white;
}

.card-body-modern {
    padding: 2rem;
}

/* Course Description */
.course-description {
    font-size: 1.1rem;
    line-height: 1.7;
    color: #374151;
}

/* Curriculum */
.curriculum-list {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
}

.curriculum-item {
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    overflow: hidden;
    transition: all 0.3s ease;
}

.curriculum-item:hover {
    border-color: #667eea;
    box-shadow: 0 2px 8px rgba(102, 126, 234, 0.1);
}

.curriculum-item.expanded {
    border-color: #667eea;
    box-shadow: 0 2px 8px rgba(102, 126, 234, 0.1);
}

.curriculum-header {
    padding: 1.5rem;
    display: flex;
    align-items: center;
    justify-content: space-between;
    cursor: pointer;
    background: white;
    transition: all 0.3s ease;
}

.curriculum-header:hover {
    background: #f8fafc;
}

.lesson-info {
    display: flex;
    align-items: center;
    gap: 1rem;
    flex: 1;
}

.lesson-icon {
    width: 40px;
    height: 40px;
    border-radius: 8px;
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1rem;
    flex-shrink: 0;
}

.lesson-details {
    flex: 1;
}

.lesson-details h4 {
    font-size: 1rem;
    font-weight: 600;
    color: #1e293b;
    margin: 0 0 0.5rem 0;
}

.lesson-meta {
    display: flex;
    align-items: center;
    gap: 1rem;
    font-size: 0.875rem;
    color: #64748b;
}

.lesson-type {
    background: #e5e7eb;
    color: #374151;
    padding: 0.25rem 0.5rem;
    border-radius: 4px;
    font-weight: 500;
}

.lesson-duration {
    color: #6b7280;
}

.preview-badge {
    background: #fef3c7;
    color: #d97706;
    padding: 0.25rem 0.5rem;
    border-radius: 4px;
    font-size: 0.75rem;
    font-weight: 600;
}

.curriculum-toggle {
    color: #6b7280;
    transition: transform 0.3s ease;
}

.curriculum-item.expanded .curriculum-toggle {
    transform: rotate(180deg);
}

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

.curriculum-item.expanded .curriculum-content {
    max-height: 200px;
}

.content-text {
    padding: 0 1.5rem 1.5rem;
}

.content-text p {
    margin: 0;
    color: #4b5563;
    line-height: 1.6;
}

.preview-notice {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    margin-top: 1rem;
    padding: 0.75rem;
    background: #fef3c7;
    border-radius: 6px;
    font-size: 0.875rem;
    color: #d97706;
}

.preview-notice i {
    flex-shrink: 0;
}

/* Instructor Profile */
.instructor-profile {
    display: flex;
    align-items: flex-start;
    gap: 1.5rem;
}

.instructor-avatar {
    width: 80px;
    height: 80px;
    border-radius: 12px;
    overflow: hidden;
    flex-shrink: 0;
}

.instructor-avatar img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.avatar-placeholder {
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, #f3f4f6, #e5e7eb);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 2rem;
    color: #9ca3af;
}

.instructor-details h3 {
    font-size: 1.25rem;
    font-weight: 700;
    color: #1e293b;
    margin: 0 0 0.5rem 0;
}

.instructor-bio {
    color: #4b5563;
    line-height: 1.6;
    margin-bottom: 1rem;
}

/* Reviews */
.reviews-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
    gap: 1.5rem;
}

.review-card-modern {
    background: #f8fafc;
    border: 1px solid #e5e7eb;
    border-radius: 12px;
    padding: 1.5rem;
    transition: all 0.3s ease;
}

.review-card-modern:hover {
    background: white;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.review-header-modern {
    display: flex;
    align-items: flex-start;
    gap: 1rem;
    margin-bottom: 1rem;
}

.reviewer-avatar {
    width: 48px;
    height: 48px;
    border-radius: 8px;
    overflow: hidden;
    flex-shrink: 0;
}

.reviewer-avatar img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.avatar-placeholder-small {
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, #667eea, #764ba2);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 1.25rem;
}

.reviewer-info h4 {
    font-size: 1rem;
    font-weight: 600;
    color: #1e293b;
    margin: 0 0 0.5rem 0;
}

.review-rating {
    display: flex;
    gap: 0.25rem;
}

.review-rating .fa-star {
    color: #e5e7eb;
    font-size: 0.875rem;
}

.review-rating .fa-star.filled {
    color: #f59e0b;
}

.review-date {
    margin-left: auto;
    font-size: 0.875rem;
    color: #6b7280;
}

.review-content-modern h5 {
    font-size: 1rem;
    font-weight: 600;
    color: #1e293b;
    margin: 0 0 0.5rem 0;
}

.review-content-modern p {
    margin: 0;
    color: #4b5563;
    line-height: 1.6;
}

/* Sidebar Stats */
.stats-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 1rem;
}

.stat-box {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    padding: 1rem;
    background: #f8fafc;
    border-radius: 8px;
    border: 1px solid #e5e7eb;
}

.stat-icon-modern {
    width: 40px;
    height: 40px;
    border-radius: 8px;
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1rem;
    flex-shrink: 0;
}

.stat-info {
    flex: 1;
}

.stat-value {
    font-size: 1.25rem;
    font-weight: 700;
    color: #1e293b;
    line-height: 1;
}

.stat-label {
    font-size: 0.875rem;
    color: #64748b;
}

/* Requirements */
.requirements-list {
    display: flex;
    flex-direction: column;
    gap: 0.75rem;
}

.requirement-item {
    display: flex;
    align-items: flex-start;
    gap: 0.75rem;
    font-size: 0.9rem;
    color: #4b5563;
    line-height: 1.5;
}

.requirement-item i {
    color: #10b981;
    margin-top: 0.125rem;
    flex-shrink: 0;
}

.empty-state-small {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    padding: 1rem;
    background: #f8fafc;
    border-radius: 8px;
    font-size: 0.9rem;
    color: #6b7280;
}

.empty-state-small i {
    color: #9ca3af;
}

/* Similar Courses */
.similar-courses-list {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.similar-course-item {
    display: flex;
    align-items: center;
    gap: 1rem;
    padding: 1rem;
    background: #f8fafc;
    border-radius: 8px;
    text-decoration: none;
    transition: all 0.3s ease;
    border: 1px solid #e5e7eb;
}

.similar-course-item:hover {
    background: white;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transform: translateX(4px);
}

.course-thumbnail-small {
    width: 60px;
    height: 40px;
    border-radius: 6px;
    overflow: hidden;
    flex-shrink: 0;
}

.course-thumbnail-small img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.thumbnail-placeholder-small {
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, #f3f4f6, #e5e7eb);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.25rem;
    color: #9ca3af;
}

.course-info-small h4 {
    font-size: 0.9rem;
    font-weight: 600;
    color: #1e293b;
    margin: 0 0 0.5rem 0;
    line-height: 1.3;
}

.course-meta-small {
    display: flex;
    align-items: center;
    gap: 1rem;
    font-size: 0.8rem;
    color: #6b7280;
}

.enrollment-count, .rating-small {
    display: flex;
    align-items: center;
    gap: 0.25rem;
}

.enrollment-count i, .rating-small i {
    font-size: 0.75rem;
}

/* Empty States */
.empty-state {
    text-align: center;
    padding: 3rem 2rem;
}

.empty-icon {
    font-size: 3rem;
    color: #cbd5e1;
    margin-bottom: 1rem;
}

.empty-state h3 {
    font-size: 1.25rem;
    font-weight: 600;
    color: #475569;
    margin-bottom: 0.5rem;
}

.empty-state p {
    color: #64748b;
    max-width: 300px;
    margin: 0 auto;
}

/* Responsive Design */
@media (max-width: 1024px) {
    .hero-content {
        grid-template-columns: 1fr;
        gap: 2rem;
    }

    .content-grid {
        grid-template-columns: 1fr;
        gap: 2rem;
    }

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

    .hero-stats {
        grid-template-columns: repeat(2, 1fr);
    }

    .reviews-grid {
        grid-template-columns: 1fr;
    }
}

@media (max-width: 768px) {
    .hero-background {
        padding: 60px 0 40px;
    }

    .hero-content {
        padding: 0 1rem;
        gap: 1.5rem;
    }

    .hero-title {
        font-size: 2rem;
    }

    .hero-stats {
        grid-template-columns: 1fr;
    }

    .hero-actions {
        flex-direction: column;
        align-items: stretch;
    }

    .btn-modern {
        justify-content: center;
    }

    .stats-grid {
        grid-template-columns: 1fr;
    }

    .curriculum-header {
        padding: 1rem;
    }

    .lesson-details h4 {
        font-size: 0.9rem;
    }

    .instructor-profile {
        flex-direction: column;
        text-align: center;
    }

    .review-header-modern {
        flex-direction: column;
        gap: 0.75rem;
        text-align: center;
    }

    .similar-course-item {
        padding: 0.75rem;
    }
}
</style>

<script>
// Curriculum accordion functionality
function toggleCurriculumItem(header) {
    const item = header.closest('.curriculum-item');
    const content = item.querySelector('.curriculum-content');
    const toggle = item.querySelector('.curriculum-toggle');

    // Close other expanded items
    document.querySelectorAll('.curriculum-item.expanded').forEach(expandedItem => {
        if (expandedItem !== item) {
            expandedItem.classList.remove('expanded');
            const expandedContent = expandedItem.querySelector('.curriculum-content');
            const expandedToggle = expandedItem.querySelector('.curriculum-toggle');
            expandedContent.style.maxHeight = '0';
            expandedToggle.style.transform = 'rotate(0deg)';
        }
    });

    // Toggle current item
    const isExpanded = item.classList.contains('expanded');
    item.classList.toggle('expanded');

    if (isExpanded) {
        content.style.maxHeight = '0';
        toggle.style.transform = 'rotate(0deg)';
    } else {
        content.style.maxHeight = content.scrollHeight + 'px';
        toggle.style.transform = 'rotate(180deg)';
    }
}
</script>

<!-- 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>
function enrollCourse(courseId) {
    if (confirm('Are you sure you want to enroll in this course?')) {
        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) {
                location.reload();
            } else {
                alert('Error: ' + data.error);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('An error occurred. Please try again.');
        });
    }
}

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

    content.innerHTML = `
        <div class="text-center mb-4">
            <h4>${courseTitle}</h4>
            <p class="text-muted">Complete your purchase to access this course</p>
            <div class="h3 text-primary">${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-3">
                <label class="form-label">Discount Code (Optional)</label>
                <input type="text" class="form-control" name="discount_code" placeholder="Enter discount code">
                <div id="discountMessage" class="form-text"></div>
            </div>

            <div class="mb-3">
                <label class="form-label">Payment Method</label>
                <div class="payment-methods">
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="gateway" value="paynow" id="paynow" checked>
                        <label class="form-check-label" for="paynow">
                            <i class="fas fa-mobile-alt me-2"></i>Paynow (Mobile Money)
                        </label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="gateway" value="paypal" id="paypal">
                        <label class="form-check-label" for="paypal">
                            <i class="fab fa-paypal me-2"></i>PayPal
                        </label>
                    </div>
                </div>
            </div>

            <div id="finalAmount" class="alert alert-info">
                <strong>Final Amount: ${currency} ${price.toFixed(2)}</strong>
            </div>

            <div class="text-center">
                <button type="submit" class="btn btn-primary btn-lg" id="payButton">
                    <i class="fas fa-credit-card me-2"></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.show();
}

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

    // This would typically call an API to validate the discount
    // For now, we'll just show a message
    document.getElementById('discountMessage').innerHTML = '<small class="text-muted">Validating discount code...</small>';

    // Simulate API call
    setTimeout(() => {
        // For demo purposes, accept any code starting with 'TEST'
        if (code.toUpperCase().startsWith('TEST')) {
            const discountAmount = originalPrice * 0.1; // 10% discount
            document.getElementById('discountMessage').innerHTML = '<small class="text-success">10% discount applied!</small>';
            updateFinalAmount(originalPrice, discountAmount, currency);
        } else {
            document.getElementById('discountMessage').innerHTML = '<small class="text-danger">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 me-2"></i>Processing...';

    fetch('../api/payments.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            if (data.redirect_url) {
                // Redirect to payment gateway
                window.location.href = data.redirect_url;
            } else {
                alert('Payment initiated successfully!');
                location.reload();
            }
        } else {
            alert('Payment failed: ' + (data.error || 'Unknown error'));
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred. Please try again.');
    })
    .finally(() => {
        payButton.disabled = false;
        payButton.innerHTML = originalText;
    });
}
</script>

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