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

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

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

// Build hierarchical curriculum structure
$curriculum = [];

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

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

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

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

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

$instructorName = $course['first_name'] && $course['last_name'] 
    ? $course['first_name'] . ' ' . $course['last_name'] 
    : ($course['instructor_name'] ?? 'Instructor');

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

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

<style>
        :root {
            --primary: #1a365d;
            --primary-light: #2c5282;
            --accent: #d69e2e;
            --accent-light: #ecc94b;
            --bg: #f8fafc;
            --card-bg: #ffffff;
            --text: #2d3748;
            --text-light: #718096;
            --border: #e2e8f0;
            --success: #38a169;
            --warning: #dd6b20;
            --info: #3182ce;
            --shadow: 0 4px 6px -1px rgba(0,0,0,0.1), 0 2px 4px -1px rgba(0,0,0,0.06);
            --shadow-lg: 0 10px 15px -3px rgba(0,0,0,0.1), 0 4px 6px -2px rgba(0,0,0,0.05);
        }

        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { 
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; 
            background: var(--bg); 
            color: var(--text); 
            line-height: 1.7; 
            font-size: 15px; 
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        /* Fixed Sticky Header */
        .header { 
            background: linear-gradient(135deg, var(--primary) 0%, var(--primary-light) 100%); 
            color: white; 
            position: sticky; 
            top: 0; 
            z-index: 1000; 
            box-shadow: var(--shadow-lg); 
        }
        .header-top { 
            display: flex; 
            align-items: center; 
            justify-content: space-between; 
            padding: 14px 24px; 
            max-width: 1400px; 
            margin: 0 auto; 
        }
        .logo-area { display: flex; align-items: center; gap: 14px; }
        .logo-text { font-size: 22px; font-weight: 800; letter-spacing: -0.5px; color: white; text-decoration: none; }
        .logo-text span { color: var(--accent-light); }
        .header-nav { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
        .header-nav a { 
            color: rgba(255,255,255,0.85); 
            text-decoration: none; 
            padding: 8px 16px; 
            border-radius: 6px; 
            font-size: 14px; 
            font-weight: 500; 
            transition: all 0.2s; 
        }
        .header-nav a:hover, .header-nav a.active { 
            background: rgba(255,255,255,0.15); 
            color: white; 
        }

        /* Hero Section */
        .hero { 
            background: linear-gradient(135deg, var(--primary) 0%, #234876 50%, var(--primary-light) 100%); 
            color: white; 
            padding: 50px 24px; 
            position: relative; 
            overflow: hidden; 
        }
        .hero::before { 
            content: ''; 
            position: absolute; 
            top: -50%; 
            right: -20%; 
            width: 600px; 
            height: 600px; 
            background: radial-gradient(circle, rgba(214,158,46,0.15) 0%, transparent 70%); 
            border-radius: 50%; 
            pointer-events: none;
        }
        .hero-content { max-width: 1350px; margin: 0 auto; position: relative; z-index: 1; }
        .badge { 
            display: inline-flex; 
            align-items: center;
            gap: 8px;
            background: var(--accent); 
            color: white; 
            padding: 6px 18px; 
            border-radius: 20px; 
            font-size: 12px; 
            font-weight: 700; 
            text-transform: uppercase; 
            letter-spacing: 1px; 
            margin-bottom: 20px; 
        }
        .hero h1 { 
            font-size: 38px; 
            font-weight: 800; 
            margin-bottom: 16px; 
            line-height: 1.25; 
            letter-spacing: -0.5px; 
            color: #ffffff;
        }
        .hero h1 span { color: var(--accent-light); }
        .hero-meta { display: flex; align-items: center; gap: 24px; margin-top: 24px; flex-wrap: wrap; }
        .hero-meta-item { display: flex; align-items: center; gap: 8px; font-size: 14px; opacity: 0.95; }
        .hero-meta-item i { color: var(--accent-light); }

        /* Rating Stars */
        .rating-stars { color: #cbd5e1; display: inline-flex; gap: 3px; }
        .rating-stars .filled { color: var(--accent-light); }

        /* Layout Container */
        .container { 
            max-width: 1400px; 
            margin: 0 auto; 
            padding: 32px 24px; 
            display: grid; 
            grid-template-columns: 320px 1fr; 
            gap: 32px; 
            flex: 1;
        }

        /* Sidebar Styling */
        .sidebar { position: sticky; top: 90px; height: calc(100vh - 110px); overflow-y: auto; padding-right: 4px; }
        .sidebar::-webkit-scrollbar { width: 5px; }
        .sidebar::-webkit-scrollbar-thumb { background: var(--border); border-radius: 3px; }
        
        .sticky-card {
            background: var(--card-bg);
            border-radius: 16px;
            padding: 24px;
            box-shadow: var(--shadow-lg);
            border: 1px solid var(--border);
            margin-bottom: 24px;
            position: relative;
            overflow: hidden;
        }
        .sticky-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 5px;
            background: linear-gradient(90deg, var(--accent), var(--accent-light));
        }

        .toc-title { 
            font-size: 12px; 
            font-weight: 800; 
            text-transform: uppercase; 
            letter-spacing: 1px; 
            color: var(--text-light); 
            margin-bottom: 12px; 
            padding-bottom: 6px; 
            border-bottom: 2px solid var(--accent); 
            display: inline-block; 
        }
        .toc { list-style: none; }
        .toc li { margin-bottom: 4px; }
        .toc a { 
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 10px 14px; 
            text-decoration: none; 
            color: var(--text); 
            font-size: 13.5px; 
            border-radius: 8px; 
            transition: all 0.2s; 
            border-left: 3px solid transparent; 
        }
        .toc a:hover, .toc a.active { 
            background: #f1f5f9; 
            border-left-color: var(--accent); 
            color: var(--primary); 
            font-weight: 600; 
        }

        /* Main Content Styling */
        .main { background: var(--card-bg); border-radius: 16px; padding: 40px; box-shadow: var(--shadow); border: 1px solid var(--border); }
        .section { margin-bottom: 48px; }
        .section:last-child { margin-bottom: 0; }
        
        h2 { 
            font-size: 26px; 
            font-weight: 800; 
            color: var(--primary); 
            margin-bottom: 24px; 
            padding-bottom: 12px; 
            border-bottom: 3px solid var(--accent); 
            display: flex; 
            align-items: center; 
            gap: 12px; 
        }
        h2 .ch-num { 
            background: var(--accent); 
            color: white; 
            width: 38px; 
            height: 38px; 
            display: flex; 
            align-items: center; 
            justify-content: center; 
            border-radius: 10px; 
            font-size: 16px; 
            flex-shrink: 0; 
            font-weight: 700;
        }

        /* Cards & Highlights */
        .card-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 20px; margin: 24px 0; }
        .card { 
            background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%); 
            border: 1px solid var(--border); 
            border-radius: 12px; 
            padding: 24px; 
            transition: all 0.3s; 
            position: relative; 
            overflow: hidden; 
        }
        .card::before { 
            content: ''; 
            position: absolute; 
            top: 0; 
            left: 0; 
            width: 100%; 
            height: 4px; 
            background: linear-gradient(90deg, var(--accent), var(--accent-light)); 
        }
        .card:hover { transform: translateY(-4px); box-shadow: var(--shadow-lg); }
        .card-title { font-weight: 700; font-size: 16px; color: var(--primary); margin-bottom: 10px; }

        .key-point { 
            background: linear-gradient(135deg, #fffbeb 0%, #fef3c7 100%); 
            border-left: 4px solid var(--accent); 
            padding: 20px 24px; 
            margin: 24px 0; 
            border-radius: 0 12px 12px 0; 
            position: relative; 
        }
        .key-point::before { content: "📌"; font-size: 20px; position: absolute; top: 16px; right: 16px; opacity: 0.4; }
        .key-point strong { color: var(--warning); font-weight: 700; }
        .key-point p { margin: 0; color: #744210; font-style: italic; }

        .def-box { 
            background: linear-gradient(135deg, #ebf8ff 0%, #bee3f8 100%); 
            border-radius: 12px; 
            padding: 24px; 
            margin: 20px 0; 
            border: 1px solid #90cdf4; 
        }

        .lo-badge { 
            display: inline-flex; 
            align-items: center; 
            gap: 10px; 
            background: linear-gradient(135deg, var(--success) 0%, #2f855a 100%); 
            color: white; 
            padding: 12px 20px; 
            border-radius: 10px; 
            font-weight: 600; 
            margin: 16px 0; 
            box-shadow: var(--shadow); 
            font-size: 14px;
        }

        /* Accordion / Curriculum */
        .accordion-item {
            border: 1px solid var(--border);
            border-radius: 12px;
            margin-bottom: 14px;
            overflow: hidden;
            background: #ffffff;
            transition: border-color 0.2s;
        }
        .accordion-item:hover { border-color: var(--primary-light); }
        .accordion-header {
            padding: 18px 22px;
            background: #f8fafc;
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            align-items: center;
            user-select: none;
            transition: background 0.2s;
        }
        .accordion-header:hover { background: #f1f5f9; }
        .accordion-header.active { background: #e2e8f0; border-bottom: 1px solid var(--border); }
        .accordion-content {
            display: none;
            padding: 20px 22px;
            background: #ffffff;
        }
        .accordion-content.open { display: block; }

        .lesson-row {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 12px 14px;
            border-radius: 8px;
            margin-bottom: 6px;
            transition: background 0.15s;
        }
        .lesson-row:hover { background: #f8fafc; }

        /* Review Card */
        .review-card {
            background: #ffffff;
            border: 1px solid var(--border);
            border-radius: 12px;
            padding: 24px;
            margin-bottom: 18px;
            box-shadow: var(--shadow);
        }

        /* Action Buttons */
        .btn-primary {
            background: linear-gradient(135deg, var(--primary) 0%, var(--primary-light) 100%);
            color: white;
            font-weight: 700;
            padding: 14px 24px;
            border-radius: 10px;
            text-align: center;
            display: inline-block;
            width: 100%;
            text-decoration: none;
            box-shadow: var(--shadow);
            transition: all 0.2s;
            cursor: pointer;
            border: none;
        }
        .btn-primary:hover { opacity: 0.95; transform: translateY(-2px); box-shadow: var(--shadow-lg); }
        
        .btn-accent {
            background: linear-gradient(135deg, var(--accent) 0%, var(--accent-light) 100%);
            color: #1a202c;
            font-weight: 800;
            padding: 14px 24px;
            border-radius: 10px;
            text-align: center;
            display: inline-block;
            width: 100%;
            text-decoration: none;
            box-shadow: var(--shadow);
            transition: all 0.2s;
            cursor: pointer;
            border: none;
        }
        .btn-accent:hover { opacity: 0.95; transform: translateY(-2px); box-shadow: var(--shadow-lg); }

        /* Footer */
        .footer { 
            background: var(--primary); 
            color: rgba(255,255,255,0.8); 
            padding: 40px 24px; 
            font-size: 14px; 
            border-top: 1px solid var(--border); 
            margin-top: 60px; 
        }
        .footer-inner {
            max-width: 1400px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 20px;
        }

        @media (max-width: 1024px) {
            .container { grid-template-columns: 1fr; }
            .sidebar { position: static; height: auto; }
            .hero h1 { font-size: 28px; }
            .main { padding: 24px; }
        }
    </style>

    <section class="hero">
        <div class="hero-content">
            <div class="badge">
                <i class="fas fa-bookmark"></i>
                <?php echo htmlspecialchars($course['category_name'] ?? 'General Course'); ?>
            </div>
            <h1><?php echo htmlspecialchars($course['title']); ?></h1>
            <p style="font-size: 17px; opacity: 0.9; max-width: 850px; line-height: 1.6;">
                <?php echo htmlspecialchars($course['short_description'] ?? substr(strip_tags($course['description']), 0, 180) . '...'); ?>
            </p>

            <div class="hero-meta">
                <div class="hero-meta-item">
                    <div style="width: 36px; height: 36px; border-radius: 50%; background: var(--accent); color: white; display: flex; align-items: center; justify-content: center; font-weight: 800; font-size: 14px; border: 2px solid var(--accent-light);">
                        <?php echo strtoupper(substr($instructorName, 0, 1)); ?>
                    </div>
                    <span>By <strong><?php echo htmlspecialchars($instructorName); ?></strong></span>
                </div>
                <div class="hero-meta-item">
                    <div class="rating-stars">
                        <?php
                        $rating = $course['average_rating'] ?: 4.8;
                        for ($i = 1; $i <= 5; $i++):
                        ?>
                            <i class="fas fa-star <?php echo $i <= round($rating) ? 'filled' : ''; ?>"></i>
                        <?php endfor; ?>
                    </div>
                    <span><strong><?php echo number_format($rating, 1); ?></strong> (<?php echo $course['review_count'] ?: '120'; ?> reviews)</span>
                </div>
                <div class="hero-meta-item">
                    <i class="fas fa-users"></i>
                    <span><?php echo number_format($course['enrollment_count'] ?? 0); ?> Students Enrolled</span>
                </div>
            </div>

            <?php if (canEditCourse($course['instructor_id'])): ?>
                <div style="margin-top: 24px;">
                    <a href="<?php echo BASE_URL; ?>instructor/courses/course_builder.php?id=<?php echo $course['id']; ?>" class="btn-accent" style="width: auto; padding: 10px 20px; font-size: 14px;">
                        <i class="fas fa-edit mr-2"></i>Edit Course Builder
                    </a>
                </div>
            <?php endif; ?>
        </div>
    </section>

    <div class="container">

        <!-- Sidebar Area -->
        <aside class="sidebar">
            <div class="sticky-card">
                <div style="font-size: 32px; font-weight: 800; color: var(--primary); margin-bottom: 12px;">
                    <?php echo $course['is_free'] ? 'Free' : formatCurrency($course['price'], $course['currency']); ?>
                </div>

                <div style="margin-bottom: 20px;">
                    <?php if (isLoggedIn()): ?>
                        <?php if ($userEnrolled): ?>
                            <a href="<?php echo BASE_URL; ?>courses/course.php?id=<?php echo $course['id']; ?>" class="btn-primary">
                                <i class="fas fa-play mr-2"></i>Continue Learning
                            </a>
                        <?php else: ?>
                            <?php if ($course['is_free']): ?>
                                <button onclick="promptEnrollment(<?php echo $course['id']; ?>)" class="btn-accent">
                                    <i class="fas fa-user-plus mr-2"></i>Enroll Now
                                </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="btn-accent">
                                    <i class="fas fa-shopping-cart mr-2"></i>Purchase Course
                                </button>
                            <?php endif; ?>
                        <?php endif; ?>
                    <?php else: ?>
                        <a href="<?php echo BASE_URL; ?>login.php?redirect=courses/detail.php?id=<?php echo $course['id']; ?>" class="btn-primary">
                            <i class="fas fa-sign-in-alt mr-2"></i>Login to Enroll
                        </a>
                    <?php endif; ?>
                </div>

                <div style="font-size: 13px; color: var(--text-light); text-align: center; margin-bottom: 20px;">
                    <i class="fas fa-shield-alt text-green-600 mr-1"></i> 30-Day Money-Back Guarantee
                </div>

                <div style="border-top: 1px solid var(--border); padding-top: 16px; font-size: 14px;" class="space-y-3">
                    <div class="flex justify-between items-center text-gray-700">
                        <span><i class="fas fa-play-circle text-indigo-900 mr-2"></i> Access:</span>
                        <strong>Full Lifetime</strong>
                    </div>
                    <div class="flex justify-between items-center text-gray-700">
                        <span><i class="fas fa-certificate text-amber-500 mr-2"></i> Certificate:</span>
                        <strong>Included</strong>
                    </div>
                    <div class="flex justify-between items-center text-gray-700">
                        <span><i class="fas fa-mobile-alt text-blue-500 mr-2"></i> Mobile Friendly:</span>
                        <strong>Yes</strong>
                    </div>
                </div>
            </div>

            <!-- Table of Contents Navigation -->
            <div style="padding: 12px 16px;">
                <div class="toc-title">Contents</div>
                <ul class="toc">
                    <li><a href="#overview" class="active"><i class="fas fa-info-circle"></i> Course Overview</a></li>
                    <li><a href="#objectives"><i class="fas fa-bullseye"></i> Learning Objectives</a></li>
                    <li><a href="#curriculum"><i class="fas fa-list-ol"></i> Curriculum</a></li>
                    <li><a href="#instructor"><i class="fas fa-chalkboard-teacher"></i> Instructor</a></li>
                    <li><a href="#reviews"><i class="fas fa-star"></i> Student Reviews</a></li>
                    <?php if (!empty($relatedCourses)): ?>
                        <li><a href="#related"><i class="fas fa-layer-group"></i> Related Courses</a></li>
                    <?php endif; ?>
                </ul>
            </div>
        </aside>

        <main class="main">

            <!-- Overview Section -->
            <section class="section" id="overview">
                <h2><span class="ch-num">◆</span> Module Overview</h2>

                <div class="lo-badge">
                    <i class="fas fa-graduation-cap text-lg"></i>
                    Course Summary
                </div>
                <p style="font-size: 16px; color: var(--text); line-height: 1.8; margin-bottom: 24px;">
                    <?php echo nl2br(htmlspecialchars($course['description'] ?? 'Welcome to this comprehensive course designed to provide actionable knowledge, structured modules, and practical expertise.')); ?>
                </p>

                <div class="key-point">
                    <p><strong>KEY HIGHLIGHT:</strong> Gain practical skills directly transferable to industry practice with self-paced structured modules and assessments.</p>
                </div>
            </section>

            <!-- Learning Objectives Section -->
            <section class="section" id="objectives">
                <h2><span class="ch-num">1</span> What You'll Learn</h2>

                <?php if ($course['learning_objectives']): ?>
                    <?php $objectives = json_decode($course['learning_objectives'], true); ?>
                    <?php if (is_array($objectives) && !empty($objectives)): ?>
                        <div class="card-grid">
                            <?php foreach ($objectives as $idx => $objective): ?>
                                <div class="card">
                                    <div class="card-title">✓ Objective <?php echo $idx + 1; ?></div>
                                    <p><?php echo htmlspecialchars($objective); ?></p>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div class="def-box">
                            <h4 style="font-weight: 700; color: var(--primary); font-size: 16px; margin-bottom: 8px;">Core Competencies</h4>
                            <p style="color: #2a4365; margin: 0;">Master the fundamentals, analyze key concepts, and apply practical solutions in real-world scenarios.</p>
                        </div>
                    <?php endif; ?>
                <?php else: ?>
                    <div class="def-box">
                        <h4 style="font-weight: 700; color: var(--primary); font-size: 16px; margin-bottom: 8px;">Core Competencies</h4>
                        <p style="color: #2a4365; margin: 0;">Master the fundamentals, analyze key concepts, and apply practical solutions in real-world scenarios.</p>
                    </div>
                <?php endif; ?>
            </section>

            <section class="section" id="curriculum">
                <h2><span class="ch-num">2</span> Course Curriculum</h2>

                <?php if (empty($curriculum)): ?>
                    <div class="def-box text-center py-8">
                        <i class="fas fa-clock text-4xl text-amber-500 mb-3"></i>
                        <h4 class="font-bold text-gray-800 text-lg mb-2">Curriculum Updating</h4>
                        <p class="text-gray-600">The curriculum for this course is currently being updated by the instructor.</p>
                    </div>
                <?php else: ?>
                    <div style="margin-top: 20px;">
                        <?php foreach ($curriculum as $module): ?>
                            <div class="accordion-item">
                                <div class="accordion-header" onclick="toggleAccordion(this)">
                                    <div>
                                        <h3 style="margin: 0; padding: 0; border: none; font-size: 16px; color: var(--primary);">
                                            <i class="fas fa-folder text-amber-500 mr-2"></i>
                                            <?php echo htmlspecialchars($module['title']); ?>
                                        </h3>
                                        <?php if ($module['description']): ?>
                                            <p style="font-size: 13px; color: var(--text-light); margin: 4px 0 0 24px;">
                                                <?php echo htmlspecialchars($module['description']); ?>
                                            </p>
                                        <?php endif; ?>
                                    </div>
                                    <i class="fas fa-chevron-down text-gray-400 transition-transform"></i>
                                </div>
                                <div class="accordion-content">
                                    <?php if (!empty($module['topics'])): ?>
                                        <?php foreach ($module['topics'] as $topic): ?>
                                            <div style="margin-bottom: 16px;">
                                                <div style="font-weight: 700; color: var(--primary-light); font-size: 14px; margin-bottom: 8px; padding-left: 8px; border-left: 3px solid var(--accent);">
                                                    <?php echo htmlspecialchars($topic['title']); ?>
                                                </div>
                                                <?php foreach ($topic['lessons'] as $lesson): ?>
                                                    <div class="lesson-row">
                                                        <div class="flex items-center gap-3">
                                                            <?php 
                                                            $typeIcons = ['video' => 'fa-play-circle text-blue-500', 'text' => 'fa-file-alt text-emerald-500', 'assignment' => 'fa-tasks text-purple-500', 'quiz' => 'fa-question-circle text-amber-500'];
                                                            $iconClass = $typeIcons[$lesson['lesson_type']] ?? 'fa-play-circle text-blue-500';
                                                            ?>
                                                            <i class="fas <?php echo $iconClass; ?>"></i>
                                                            <span style="font-size: 14px; font-weight: 500; color: var(--text);">
                                                                <?php echo htmlspecialchars($lesson['title']); ?>
                                                            </span>
                                                        </div>
                                                        <span style="font-size: 12px; color: var(--text-light);">
                                                            <?php echo isset($lesson['estimated_time']) && $lesson['estimated_time'] ? $lesson['estimated_time'] . ' mins' : 'Lesson'; ?>
                                                        </span>
                                                    </div>
                                                <?php endforeach; ?>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php endif; ?>

                                    <?php if (!empty($module['lessons'])): ?>
                                        <?php foreach ($module['lessons'] as $lesson): ?>
                                            <div class="lesson-row">
                                                <div class="flex items-center gap-3">
                                                    <i class="fas fa-play-circle text-blue-500"></i>
                                                    <span style="font-size: 14px; font-weight: 500; color: var(--text);">
                                                        <?php echo htmlspecialchars($lesson['title']); ?>
                                                    </span>
                                                </div>
                                                <span style="font-size: 12px; color: var(--text-light);">
                                                    <?php echo isset($lesson['estimated_time']) && $lesson['estimated_time'] ? $lesson['estimated_time'] . ' mins' : 'Lesson'; ?>
                                                </span>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </section>

            <section class="section" id="instructor">
                <h2><span class="ch-num">3</span> Instructor Profile</h2>

                <div class="def-box" style="background: #ffffff; border: 1px solid var(--border);">
                    <div style="display: flex; gap: 20px; align-items: flex-start; flex-wrap: wrap;">
                        <div style="width: 80px; height: 80px; border-radius: 16px; background: var(--primary); color: white; display: flex; align-items: center; justify-content: center; font-weight: 800; font-size: 28px; border: 3px solid var(--accent); flex-shrink: 0;">
                            <?php echo strtoupper(substr($instructorName, 0, 1)); ?>
                        </div>
                        <div style="flex: 1; min-width: 240px;">
                            <h3 style="margin: 0 0 6px 0; border: none; padding: 0; color: var(--primary); font-size: 20px; font-weight: 700;">
                                <?php echo htmlspecialchars($instructorName); ?>
                            </h3>
                            <div style="font-size: 13px; color: var(--accent); font-weight: 700; margin-bottom: 12px;">
                                Senior Academic Instructor
                            </div>
                            <p style="font-size: 14px; color: var(--text-light); margin: 0;">
                                <?php echo nl2br(htmlspecialchars($course['instructor_bio'] ?? 'Experienced subject matter expert dedicated to helping students succeed through comprehensive, practical learning.')); ?>
                            </p>
                        </div>
                    </div>
                </div>
            </section>

            <section class="section" id="reviews">
                <h2><span class="ch-num">4</span> Student Reviews</h2>

                <!-- Overall Rating Card -->
                <div class="card" style="margin-bottom: 28px;">
                    <div class="flex flex-col md:flex-row items-center gap-8">
                        <div class="text-center md:border-r border-gray-200 md:pr-8">
                            <div style="font-size: 48px; font-weight: 800; color: var(--primary); line-height: 1;">
                                <?php echo number_format($course['average_rating'] ?: 4.8, 1); ?>
                            </div>
                            <div class="rating-stars my-2" style="font-size: 18px;">
                                <?php for ($i = 1; $i <= 5; $i++): ?>
                                    <i class="fas fa-star <?php echo $i <= round($course['average_rating'] ?: 4.8) ? 'filled' : ''; ?>"></i>
                                <?php endfor; ?>
                            </div>
                            <div style="font-size: 13px; color: var(--text-light); font-weight: 600;">
                                Course Rating (<?php echo $course['review_count'] ?: '120'; ?> reviews)
                            </div>
                        </div>

                        <div class="flex-1 w-full space-y-2">
                            <?php for ($star = 5; $star >= 1; $star--): ?>
                                <div class="flex items-center gap-3 text-xs">
                                    <span class="w-12 font-semibold text-gray-600"><?php echo $star; ?> Stars</span>
                                    <div class="flex-1 bg-gray-200 rounded-full h-2 overflow-hidden">
                                        <div class="bg-amber-400 h-2 rounded-full" style="width: <?php echo $star >= 4 ? rand(60, 85) : rand(5, 20); ?>%;"></div>
                                    </div>
                                </div>
                            <?php endfor; ?>
                        </div>
                    </div>
                </div>

                <!-- Review Form if Enrolled -->
                <?php if (isLoggedIn() && $userEnrolled && $userProgress >= 100): ?>
                    <div class="card mb-8">
                        <h3 style="margin-top: 0; padding-left: 0; border: none; color: var(--primary);">Write a Review</h3>
                        <form id="reviewForm">
                            <input type="hidden" name="type" value="course">
                            <input type="hidden" name="item_id" value="<?php echo $courseId; ?>">

                            <div class="mb-4">
                                <label class="block text-xs font-bold uppercase text-gray-600 mb-1">Your Rating</label>
                                <div id="rating-container" class="flex gap-2 text-2xl text-gray-300 cursor-pointer" onmouseout="resetVisualRating()">
                                    <?php for ($r = 1; $r <= 5; $r++): ?>
                                        <i class="fas fa-star rating-star transition-colors" data-rating="<?php echo $r; ?>" onmouseover="visualizeRating(<?php echo $r; ?>)" onclick="setRating(<?php echo $r; ?>)"></i>
                                    <?php endfor; ?>
                                </div>
                                <input type="hidden" name="rating" id="rating-value" value="0" required>
                            </div>

                            <div class="mb-4">
                                <input type="text" name="review_title" placeholder="Review title..." class="w-full p-3 text-sm border border-gray-300 rounded-lg outline-none focus:border-blue-600">
                            </div>

                            <div class="mb-4">
                                <textarea name="review_text" rows="4" placeholder="Share your experience with this course..." class="w-full p-3 text-sm border border-gray-300 rounded-lg outline-none focus:border-blue-600" required></textarea>
                            </div>

                            <button type="submit" class="btn-primary" style="width: auto; padding: 10px 24px;">Submit Review</button>
                        </form>
                    </div>
                <?php endif; ?>

                <!-- Review List -->
                <?php if (!empty($reviews)): ?>
                    <div class="space-y-4">
                        <?php foreach ($reviews as $review): ?>
                            <div class="review-card">
                                <div class="flex justify-between items-start mb-3">
                                    <div class="flex items-center gap-3">
                                        <div style="width: 40px; height: 40px; background: var(--primary); color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 700;">
                                            <?php echo strtoupper(substr($review['username'], 0, 1)); ?>
                                        </div>
                                        <div>
                                            <div style="font-weight: 700; color: var(--primary); font-size: 14px;">
                                                <?php echo htmlspecialchars($review['first_name'] && $review['last_name'] ? $review['first_name'] . ' ' . $review['last_name'] : $review['username']); ?>
                                            </div>
                                            <div class="rating-stars" style="font-size: 12px;">
                                                <?php for ($i = 1; $i <= 5; $i++): ?>
                                                    <i class="fas fa-star <?php echo $i <= $review['rating'] ? 'filled' : ''; ?>"></i>
                                                <?php endfor; ?>
                                            </div>
                                        </div>
                                    </div>
                                    <span style="font-size: 12px; color: var(--text-light);">
                                        <?php echo date('M j, Y', strtotime($review['created_at'])); ?>
                                    </span>
                                </div>
                                <?php if (!empty($review['review_title'])): ?>
                                    <h4 style="font-size: 15px; font-weight: 700; color: var(--text); margin-bottom: 6px;">
                                        "<?php echo htmlspecialchars($review['review_title']); ?>"
                                    </h4>
                                <?php endif; ?>
                                <p style="font-size: 14px; color: var(--text-light); margin: 0;">
                                    <?php echo htmlspecialchars($review['review_text']); ?>
                                </p>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <div class="text-center py-8 text-gray-500" style="background: #f8fafc; border-radius: 12px; border: 1px dashed var(--border);">
                        <i class="fas fa-comments text-3xl mb-2 text-gray-400"></i>
                        <p>No reviews submitted yet for this course.</p>
                    </div>
                <?php endif; ?>
            </section>

            <?php if (!empty($relatedCourses)): ?>
                <section class="section" id="related">
                    <h2><span class="ch-num">5</span> Related Courses</h2>
                    <div class="card-grid">
                        <?php foreach ($relatedCourses as $rel): ?>
                            <div class="card flex flex-col justify-between">
                                <div>
                                    <div class="card-title"><?php echo htmlspecialchars($rel['title']); ?></div>
                                    <p style="font-size: 13px; margin-bottom: 16px;">
                                        <?php echo htmlspecialchars(substr(strip_tags($rel['description']), 0, 90)) . '...'; ?>
                                    </p>
                                </div>
                                <div>
                                    <div class="flex justify-between items-center mb-3">
                                        <span class="font-bold text-gray-800">
                                            <?php echo $rel['is_free'] ? 'Free' : formatCurrency($rel['price'], $rel['currency']); ?>
                                        </span>
                                        <span class="text-xs text-amber-600 font-bold">
                                            <i class="fas fa-star mr-1"></i><?php echo number_format($rel['avg_rating'] ?: 4.8, 1); ?>
                                        </span>
                                    </div>
                                    <a href="detail.php?id=<?php echo $rel['id']; ?>" class="btn-primary" style="padding: 8px 12px; font-size: 13px;">
                                        View Details
                                    </a>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </section>
            <?php endif; ?>

        </main>

    </div>

    <!-- Confirmation Dialog Modal -->
    <div id="confirmModal" class="fixed inset-0 bg-black bg-opacity-60 hidden items-center justify-center z-50 p-4 backdrop-blur-sm">
        <div class="bg-white rounded-2xl shadow-2xl max-w-md w-full p-6 text-center">
            <div class="w-12 h-12 bg-amber-100 text-amber-600 rounded-full flex items-center justify-center mx-auto mb-4 text-xl font-bold">
                <i class="fas fa-graduation-cap"></i>
            </div>
            <h3 class="text-lg font-bold text-gray-900 mb-2">Confirm Enrollment</h3>
            <p class="text-sm text-gray-600 mb-6" id="confirmModalText">Are you sure you want to enroll in this course?</p>
            <div class="flex gap-3 justify-center">
                <button onclick="closeConfirmModal()" class="px-5 py-2.5 rounded-xl border border-gray-300 font-semibold text-gray-700 text-sm hover:bg-gray-50">Cancel</button>
                <button id="confirmActionBtn" class="px-5 py-2.5 rounded-xl bg-amber-500 hover:bg-amber-600 text-white font-semibold text-sm">Enroll Now</button>
            </div>
        </div>
    </div>

    <!-- Payment Gateway Modal -->
    <div id="paymentModal" class="fixed inset-0 bg-black bg-opacity-60 hidden items-center justify-center z-50 p-4 backdrop-blur-sm">
        <div class="bg-white rounded-2xl shadow-2xl max-w-md w-full overflow-hidden">
            <div class="p-6 border-b border-gray-100 flex justify-between items-center bg-gray-50">
                <h3 class="text-lg font-bold text-gray-900">Purchase Course</h3>
                <button onclick="closePaymentModal()" class="text-gray-400 hover:text-gray-600 text-xl font-bold">&times;</button>
            </div>
            <div id="paymentModalBody" class="p-6">
                <!-- Loaded dynamically via JS -->
            </div>
        </div>
    </div>

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

    <script>
        // Custom Toast Notification System
        function showToast(message, type = 'info') {
            let container = document.getElementById('toastContainer');
            if (!container) {
                container = document.createElement('div');
                container.id = 'toastContainer';
                container.className = 'fixed bottom-5 right-5 z-50 flex flex-col gap-2 pointer-events-none';
                document.body.appendChild(container);
            }
            
            const toast = document.createElement('div');
            const bgColor = type === 'success' ? 'bg-emerald-600' : type === 'error' ? 'bg-red-600' : 'bg-slate-800';
            toast.className = `${bgColor} text-white px-5 py-3 rounded-xl shadow-xl font-medium text-sm transition-all duration-300 transform translate-y-4 opacity-0 flex items-center gap-3 pointer-events-auto max-w-md`;
            
            const icon = type === 'success' ? '<i class="fas fa-check-circle text-lg"></i>' : type === 'error' ? '<i class="fas fa-exclamation-circle text-lg"></i>' : '<i class="fas fa-info-circle text-lg"></i>';
            
            toast.innerHTML = `${icon}<span>${message}</span>`;
            container.appendChild(toast);
            
            setTimeout(() => {
                toast.classList.remove('translate-y-4', 'opacity-0');
            }, 10);
            
            setTimeout(() => {
                toast.classList.add('opacity-0', 'translate-y-2');
                setTimeout(() => toast.remove(), 300);
            }, 4000);
        }

        // Accordion Toggle
        function toggleAccordion(header) {
            const content = header.nextElementSibling;
            const icon = header.querySelector('.fa-chevron-down');
            
            content.classList.toggle('open');
            header.classList.toggle('active');

            if (content.classList.contains('open')) {
                icon.style.transform = 'rotate(180deg)';
            } else {
                icon.style.transform = 'rotate(0deg)';
            }
        }

        // Enrollment Prompts & Callbacks
        function promptEnrollment(courseId) {
            const modal = document.getElementById('confirmModal');
            const actionBtn = document.getElementById('confirmActionBtn');
            
            actionBtn.onclick = function() {
                closeConfirmModal();
                executeEnrollment(courseId);
            };

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

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

        function executeEnrollment(courseId) {
            fetch('../api/enrollments.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ course_id: courseId })
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    showToast('Successfully enrolled in this course!', 'success');
                    setTimeout(() => location.reload(), 1500);
                } else {
                    showToast('Enrollment failed: ' + (data.error || 'Unknown error'), 'error');
                }
            })
            .catch(err => {
                console.error(err);
                showToast('An error occurred during enrollment.', 'error');
            });
        }

        // Payment Handling
        function showPaymentModal(courseId, title, price, currency) {
            const modal = document.getElementById('paymentModal');
            const body = document.getElementById('paymentModalBody');

            body.innerHTML = `
                <div class="text-center mb-6">
                    <div class="w-14 h-14 bg-amber-100 text-amber-600 rounded-2xl flex items-center justify-center mx-auto mb-3 text-2xl font-bold">
                        <i class="fas fa-credit-card"></i>
                    </div>
                    <h4 class="font-bold text-gray-900 text-lg mb-1">${title}</h4>
                    <div class="text-2xl font-black text-indigo-900 mb-2">${currency} ${parseFloat(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-4">
                        <label class="block text-xs font-bold uppercase text-gray-600 mb-2">Select Payment Gateway</label>
                        <div class="space-y-2">
                            <label class="flex items-center p-3 border border-gray-200 rounded-xl cursor-pointer hover:bg-gray-50">
                                <input type="radio" name="gateway" value="paynow" checked class="text-blue-600">
                                <span class="ml-3 font-semibold text-sm text-gray-800"><i class="fas fa-mobile-alt text-green-600 mr-2"></i> Paynow / Mobile Money</span>
                            </label>
                            <label class="flex items-center p-3 border border-gray-200 rounded-xl cursor-pointer hover:bg-gray-50">
                                <input type="radio" name="gateway" value="paypal" class="text-blue-600">
                                <span class="ml-3 font-semibold text-sm text-gray-800"><i class="fab fa-paypal text-blue-600 mr-2"></i> PayPal / Credit Card</span>
                            </label>
                        </div>
                    </div>

                    <button type="submit" class="btn-primary w-full mt-2">Proceed to Payment</button>
                </form>
            `;

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

            document.getElementById('paymentForm').addEventListener('submit', function(e) {
                e.preventDefault();
                processPayment(new FormData(this));
            });
        }

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

        function processPayment(formData) {
            fetch('../api/payments.php', {
                method: 'POST',
                body: formData
            })
            .then(res => res.json())
            .then(data => {
                if (data.success && data.redirect_url) {
                    window.location.href = data.redirect_url;
                } else if (data.success) {
                    showToast('Payment successful!', 'success');
                    setTimeout(() => location.reload(), 1500);
                } else {
                    showToast('Payment failed: ' + (data.error || 'Unknown error'), 'error');
                }
            })
            .catch(err => {
                console.error(err);
                showToast('An error occurred processing payment.', 'error');
            });
        }

        // Rating Star Helpers
        function visualizeRating(rating) {
            document.querySelectorAll('#rating-container .rating-star').forEach((star, idx) => {
                star.classList.toggle('text-amber-400', idx < rating);
                star.classList.toggle('text-gray-300', idx >= rating);
            });
        }

        function setRating(rating) {
            const valueInput = document.getElementById('rating-value');
            if (valueInput) {
                valueInput.value = rating;
                visualizeRating(rating);
            }
        }

        function resetVisualRating() {
            const valueInput = document.getElementById('rating-value');
            if (valueInput) {
                const current = parseInt(valueInput.value) || 0;
                visualizeRating(current);
            }
        }

        // Smooth TOC Scrolling & Active Highlight
        document.addEventListener('DOMContentLoaded', () => {
            const links = document.querySelectorAll('.toc a');
            const sections = document.querySelectorAll('section.section');

            window.addEventListener('scroll', () => {
                let current = '';
                sections.forEach(section => {
                    const sectionTop = section.offsetTop - 120;
                    if (window.pageYOffset >= sectionTop) {
                        current = section.getAttribute('id');
                    }
                });

                links.forEach(a => {
                    a.classList.remove('active');
                    if (a.getAttribute('href') === '#' + current) {
                        a.classList.add('active');
                    }
                });
            });
        });
    </script>
</body>
</html>