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

studentOrHigher();

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

// Get site settings
$siteName = getSiteSetting('site_name') ?: 'Mutalex Academy';
$siteLogo = getSiteSetting('site_logo') ?: 'fas fa-newspaper';

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

// Get course details
$stmt = $db->prepare("
    SELECT c.*, cat.name as category_name,
           COUNT(DISTINCT cl.id) as total_lessons
    FROM courses c
    LEFT JOIN course_categories cat ON c.category_id = cat.id
    LEFT JOIN course_lessons cl ON c.id = cl.course_id
    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;
}

// Check enrollment
$stmt = $db->prepare("
    SELECT * FROM course_enrollments
    WHERE course_id = ? AND student_id = ?
");
$stmt->execute([$courseId, $userId]);
$enrollment = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$enrollment) {
    $_SESSION['error_message'] = 'You are not enrolled in this course.';
    header('Location: detail.php?id=' . $courseId);
    exit;
}

// Handle quiz submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_quiz'])) {
    $lesson_id = (int)$_POST['lesson_id'];
    $answer = trim($_POST['answer']);
    if ($answer === '4') {
        // Mark lesson as completed
        $stmt = $db->prepare("
            INSERT INTO course_lesson_progress (enrollment_id, lesson_id, status, completed_at, last_accessed)
            VALUES (?, ?, 'completed', NOW(), NOW())
            ON DUPLICATE KEY UPDATE status = 'completed', completed_at = NOW(), last_accessed = NOW()
        ");
        $stmt->execute([$enrollment['id'], $lesson_id]);

        // Recalculate progress and update enrollment
        $stmt = $db->prepare("
            SELECT COUNT(*) as total_lessons,
                   SUM(CASE WHEN clp.status = 'completed' THEN 1 ELSE 0 END) as completed_lessons
            FROM course_lessons cl
            LEFT JOIN course_lesson_progress clp ON cl.id = clp.lesson_id AND clp.enrollment_id = ?
            WHERE cl.course_id = ?
        ");
        $stmt->execute([$enrollment['id'], $courseId]);
        $progress = $stmt->fetch(PDO::FETCH_ASSOC);
        $progressPercentage = $progress['total_lessons'] > 0 ? round(($progress['completed_lessons'] / $progress['total_lessons']) * 100) : 0;
        $newStatus = $progressPercentage >= 100 ? 'completed' : 'in_progress';

        $stmt = $db->prepare("UPDATE course_enrollments SET status = ?, progress_percentage = ?, updated_at = NOW() WHERE id = ?");
        $stmt->execute([$newStatus, $progressPercentage, $enrollment['id']]);

        $_SESSION['success_message'] = 'Quiz passed! Lesson marked as completed.';
        header('Location: learn.php?id=' . $courseId . '&lesson=' . $lesson_id);
        exit;
    } else {
        $error = 'Incorrect answer. Please try again.';
    }
}

// Get course lessons using hierarchical structure from Curriculum Builder
$stmt = $db->prepare("
    SELECT cl.*,
           COALESCE(clp.status, 'not_started') as progress_status,
           clp.completed_at,
           clp.time_spent,
           ct.id as topic_id,
           ct.title as topic_name,
           ct.sort_order as topic_sort_order,
           cm.id as module_id,
           cm.title as module_name,
           cm.sort_order as module_sort_order
    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.topic_id IS NULL AND cl.module_id = cm.id))
    LEFT JOIN course_lesson_progress clp ON cl.id = clp.lesson_id AND clp.enrollment_id = ?
    WHERE cm.course_id = ?
    ORDER BY cm.sort_order ASC, ct.sort_order ASC, cl.sort_order ASC
");
$stmt->execute([$enrollment['id'], $courseId]);
$lessons = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get current lesson (first incomplete or requested)
$currentLessonId = $_GET['lesson'] ?? null;
$currentLesson = null;
$prevLesson = null;
$nextLesson = null;

if ($currentLessonId) {
    foreach ($lessons as $lesson) {
        if ($lesson['id'] == $currentLessonId) {
            $currentLesson = $lesson;
            break;
        }
    }
}

if (!$currentLesson) {
    // Find first incomplete lesson
    foreach ($lessons as $lesson) {
        if ($lesson['progress_status'] !== 'completed') {
            $currentLesson = $lesson;
            break;
        }
    }
    // If all completed, show first lesson
    if (!$currentLesson && !empty($lessons)) {
        $currentLesson = $lessons[0];
    }
}

// Calculate previous and next lessons
$lessonIndex = null;
if ($currentLesson) {
    foreach ($lessons as $index => $lesson) {
        if ($lesson['id'] == $currentLesson['id']) {
            $lessonIndex = $index;
            break;
        }
    }
}
if ($lessonIndex !== null) {
    $prevLesson = $lessonIndex > 0 ? $lessons[$lessonIndex - 1] : null;
    $nextLesson = $lessonIndex < count($lessons) - 1 ? $lessons[$lessonIndex + 1] : null;
}

// Calculate progress
$completedLessons = 0;
$totalTimeSpent = 0;
foreach ($lessons as $lesson) {
    if ($lesson['progress_status'] === 'completed') {
        $completedLessons++;
    }
    $totalTimeSpent += $lesson['time_spent'] ?? 0;
}

$progressPercentage = $course['total_lessons'] > 0 ? round(($completedLessons / $course['total_lessons']) * 100) : 0;

// Update enrollment progress
$stmt = $db->prepare("
    UPDATE course_enrollments
    SET progress_percentage = ?, updated_at = NOW()
    WHERE id = ?
");
$stmt->execute([$progressPercentage, $enrollment['id']]);

$page_title = htmlspecialchars($course['title']) . ' - Learning - Mutalex Academy';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($page_title); ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary-color: #4F46E5; /* Indigo 600 */
            --secondary-color: #FFFFFF; /* White for sidebar */
        }
        body {
            font-family: 'Inter', sans-serif;
            background-color: #F9FAFB; /* Light Gray Background */
        }
        /* Custom scrollbar for lesson list (if it overflows) */
        #lesson-list::-webkit-scrollbar {
            width: 5px;
        }
        #lesson-list::-webkit-scrollbar-thumb {
            background: rgba(0, 0, 0, 0.2);
            border-radius: 10px;
        }

        /* Collapsible Sidebar Styles */
        .module-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            cursor: pointer;
            user-select: none;
            transition: background-color 0.15s ease;
        }

        .module-header:hover {
            background-color: #f3f4f6;
        }

        .module-header:focus {
            outline: 2px solid #4F46E5;
            outline-offset: 2px;
        }

        .module-icon {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 20px;
            height: 20px;
            transition: transform 0.3s ease;
            color: #6b7280;
        }

        .module-icon.expanded {
            transform: rotate(90deg);
        }

        .module-content {
            max-height: 1000px;
            overflow: hidden;
            transition: max-height 0.3s ease, opacity 0.3s ease;
            opacity: 1;
        }

        .module-content.collapsed {
            max-height: 0;
            opacity: 0;
        }

        .topic-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            cursor: pointer;
            user-select: none;
            transition: background-color 0.15s ease;
        }

        .topic-header:hover {
            background-color: #f3f4f6;
        }

        .topic-header:focus {
            outline: 2px solid #4F46E5;
            outline-offset: 2px;
        }

        .topic-icon {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 18px;
            height: 18px;
            transition: transform 0.3s ease;
            color: #9ca3af;
            margin-right: 4px;
        }

        .topic-icon.expanded {
            transform: rotate(90deg);
        }

        .topic-content {
            max-height: 1000px;
            overflow: hidden;
            transition: max-height 0.3s ease, opacity 0.3s ease;
            opacity: 1;
        }

        .topic-content.collapsed {
            max-height: 0;
            opacity: 0;
        }

        .lesson-item {
            transition: all 0.2s ease;
        }

        .lesson-item a {
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }

        /* Accessibility focus styles */
        .module-header:focus-visible,
        .topic-header:focus-visible {
            outline: 2px solid #4F46E5;
            outline-offset: -2px;
            border-radius: 0.5rem;
        }

        /* Responsive adjustments */
        @media (max-width: 767px) {
            #sidebar {
                position: fixed;
                left: -100%;
                top: 4rem;
                width: 100%;
                height: calc(100vh - 4rem);
                transition: left 0.3s ease;
                z-index: 40;
            }

            #sidebar.mobile-open {
                left: 0;
            }

            .sidebar-overlay {
                display: none;
                position: fixed;
                inset: 0;
                background-color: rgba(0, 0, 0, 0.5);
                z-index: 30;
            }

            .sidebar-overlay.mobile-open {
                display: block;
            }
        }
    </style>
</head>

<!-- Tailwind CSS configuration for custom colors and plugins -->
<script>
    tailwind.config = {
        theme: {
            extend: {
                colors: {
                    primary: '#4F46E5', // Indigo 600
                    'primary-dark': '#4338CA', // Indigo 700
                },
            }
        }
    }
</script>

<body class="min-h-screen"> <!-- Removed flex-col as fixed elements handle height -->

<!-- 1. FIXED HEADER -->
<header class="fixed top-0 w-full z-20 bg-white border-b border-gray-200 shadow-sm">
    <div class="max-w-full mx-auto px-4 sm:px-6 lg:px-8 h-16 flex items-center justify-between">
        <!-- Left: Course Navigation/Branding -->
        <div class="flex items-center space-x-4">
            <!-- Mobile Menu Button -->
            <button id="mobile-menu-toggle" class="md:hidden p-2 rounded-lg text-gray-700 hover:bg-gray-100" aria-label="Toggle sidebar" aria-expanded="false">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M4 6h16M4 12h16M4 18h16" />
                </svg>
            </button>
            <a href="dashboard.php" class="flex items-center space-x-2 text-xl font-bold text-primary">
                <?php if (strpos($siteLogo, 'assets/images/') === 0): ?>
                    <img src="../<?php echo htmlspecialchars($siteLogo); ?>" alt="Logo" class="h-8 w-auto">
                <?php else: ?>
                    <i class="<?php echo htmlspecialchars($siteLogo); ?>"></i>
                <?php endif; ?>
                <span><?php echo htmlspecialchars($siteName); ?></span>
            </a>
            <span class="text-sm text-gray-400 hidden sm:inline">|</span>
            <nav class="hidden sm:block">
                <ol class="flex items-center space-x-2 text-sm">
                    <li><a href="courses.php" class="text-gray-500 hover:text-primary">My courses</a></li>
                    <li class="text-gray-400">/</li>
                    <li class="font-medium text-gray-700 truncate max-w-xs"><?php echo htmlspecialchars($course['title']); ?></li>
                </ol>
            </nav>
            <div class="hidden lg:flex items-center text-sm text-gray-600 space-x-2">
              <span id="progress-text" class="font-medium whitespace-nowrap">Progress: <?php echo $progressPercentage; ?>%</span>
              <div class="w-32 bg-gray-200 rounded-full h-2">
                <div id="progress-bar" class="bg-green-500 h-2 rounded-full transition-all duration-500" style="width: <?php echo $progressPercentage; ?>%"></div>
              </div>
            </div>
        </div>

        <!-- Right: User/Exit Actions -->
        <div class="flex items-center space-x-4">
            <button onclick="window.location.href='dashboard.php'" class="text-sm font-medium text-gray-600 hover:text-gray-700 transition duration-150 p-2 rounded-full hover:bg-gray-50">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 inline-block mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2H5a2 2 0 00-2-2z" />
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 5a2 2 0 012-2h4a2 2 0 012 2v2H8V5z" />
                </svg>
                Dashboard
            </button>
            <button onclick="window.location.href='dashboard.php'" class="text-sm font-medium text-red-600 hover:text-red-700 transition duration-150 p-2 rounded-full hover:bg-red-50">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 inline-block mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1m-6 0h6m-6-4v-1" />
                </svg>
                Exit Course
            </button>
        </div>
    </div>
</header>


<!-- 2. MAIN CONTENT AREA (Sidebar + Lesson View) -->

<?php if (isset($_SESSION['success_message'])): ?>
<div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4" role="alert">
<?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
</div>
<?php endif; ?>

<!-- 2.1. SIDEBAR (Sticky, Scrollable, Mobile-Hidden) -->
<div id="sidebar" class="w-full sm:w-80 flex-shrink-0 bg-secondary text-white shadow-lg flex-col fixed top-16 left-0 h-[calc(100vh-4rem)] z-10 flex">
    <div class="p-6 flex-shrink-0 border-b border-gray-300 relative">
      <h2 class="text-xl font-semibold text-gray-900 truncate"><?php echo htmlspecialchars($course['title']); ?></h2>
      <!-- Close button for mobile -->
      <button id="sidebar-close" class="md:hidden absolute top-4 right-4 p-2 rounded-lg text-gray-700 hover:bg-gray-100" aria-label="Close sidebar">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
          <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
        </svg>
      </button>
    </div>

        <!-- Lesson List -->
        <div id="lesson-list" class="flex-grow overflow-y-auto p-4 space-y-3">
            <?php
            // Build hierarchical curriculum structure to prevent duplicates
            $curriculum = [];
            $processedLessonIds = [];

            foreach ($lessons as $lesson) {
                $lessonId = $lesson['id'];
                
                // Skip if lesson already processed (prevent duplicates)
                // Only skip if lessonId is not empty/null
                if ($lessonId && in_array($lessonId, $processedLessonIds)) {
                    continue;
                }
                if ($lessonId) {
                    $processedLessonIds[] = $lessonId;
                }
                
                $moduleId = $lesson['module_id'] ?? 'general';
                $topicId = $lesson['topic_id'] ?? 'general';

                // Initialize module if not exists
                if (!isset($curriculum[$moduleId])) {
                    $curriculum[$moduleId] = [
                        'id' => $lesson['module_id'],
                        'title' => $lesson['module_name'] ?? 'General',
                        'sort_order' => $lesson['module_sort_order'] ?? 9999,
                        'topics' => []
                    ];
                }

                // Initialize topic if not exists
                if (!isset($curriculum[$moduleId]['topics'][$topicId])) {
                    $curriculum[$moduleId]['topics'][$topicId] = [
                        'id' => $lesson['topic_id'],
                        'title' => $lesson['topic_name'] ?? 'General',
                        'sort_order' => $lesson['topic_sort_order'] ?? 9999,
                        'lessons' => []
                    ];
                }

                // Add lesson to topic
                $curriculum[$moduleId]['topics'][$topicId]['lessons'][] = $lesson;
            }

            // Sort modules by sort_order
            uasort($curriculum, function($a, $b) {
                return ($a['sort_order'] ?? 9999) <=> ($b['sort_order'] ?? 9999);
            });

            // Sort topics and lessons within each module
            foreach ($curriculum as &$module) {
                uasort($module['topics'], function($a, $b) {
                    return ($a['sort_order'] ?? 9999) <=> ($b['sort_order'] ?? 9999);
                });
                
                foreach ($module['topics'] as &$topic) {
                    usort($topic['lessons'], function($a, $b) {
                        return ($a['sort_order'] ?? 9999) <=> ($b['sort_order'] ?? 9999);
                    });
                }
            }
            unset($module, $topic);
            ?>

<?php if (empty($curriculum)): ?>
                <div class="text-center py-12 px-4 space-y-4">
                    <div class="w-20 h-20 bg-gradient-to-br from-gray-200 to-gray-300 rounded-2xl flex items-center justify-center mx-auto mb-6">
                        <i class="fas fa-book-open text-3xl text-gray-400"></i>
                    </div>
                    <div>
                        <h3 class="text-lg font-bold text-gray-900 mb-2">Curriculum Under Development</h3>
                        <p class="text-gray-600 max-w-md mx-auto mb-4">This course is still being built. The instructor is working on adding modules, topics, and lessons.</p>
                        <p class="text-sm text-gray-500 mb-6">You'll be notified when content is available!</p>
                        
                        <?php if (hasRole('instructor') && canEditCourse($course['instructor_id'])): ?>
                            <a href="../instructor/courses/course_builder.php?id=<?php echo $courseId; ?>" 
                               class="inline-flex items-center gap-2 bg-indigo-600 text-white px-6 py-3 rounded-xl font-semibold hover:bg-indigo-700 transition-all shadow-lg">
                                <i class="fas fa-hammer"></i>
                                Build Curriculum Now
                            </a>
                        <?php endif; ?>
                    </div>
                </div>
            <?php else: ?>
                <?php foreach ($curriculum as $moduleIndex => $module): ?>
                    <!-- Module Header -->
                    <div class="mt-4 first:mt-0">
<div class="module-header px-2 py-2 rounded-lg" 
                             role="button" 
                             tabindex="0"
                             data-module-id="<?php echo htmlspecialchars($module['id'] ?? 'general'); ?>"
                             aria-expanded="false"
                             aria-controls="module-content-<?php echo htmlspecialchars($module['id'] ?? 'general'); ?>"
                             aria-label="Toggle module: <?php echo htmlspecialchars($module['title']); ?>">
                             <div class="flex items-center flex-1">
                                 <svg class="module-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                     <polyline points="9 18 15 12 9 6"></polyline>
                                 </svg>
                                 <h3 class="text-xs font-bold text-gray-600 uppercase tracking-widest text-gray-700 ml-2">
                                     <?php echo htmlspecialchars($module['title']); ?>
                                 </h3>
                             </div>
                         </div>

                        <!-- Module Content -->
                        <div id="module-content-<?php echo htmlspecialchars($module['id'] ?? 'general'); ?>" 
                             class="module-content collapsed mt-2 space-y-1">
                            <?php foreach ($module['topics'] as $topicIndex => $topic): ?>
                                <!-- Topic Group -->
                                <div class="space-y-1">
                                    <?php if (count($module['topics']) > 1 || $topic['title'] !== 'General'): ?>
<div class="topic-header px-3 py-2 rounded-lg"
                                             role="button"
                                             tabindex="0"
                                             data-topic-id="<?php echo htmlspecialchars($topic['id'] ?? 'general'); ?>"
                                             data-module-id="<?php echo htmlspecialchars($module['id'] ?? 'general'); ?>"
                                             aria-expanded="false"
                                             aria-controls="topic-content-<?php echo htmlspecialchars($topic['id'] ?? 'general'); ?>"
                                             aria-label="Toggle topic: <?php echo htmlspecialchars($topic['title']); ?>">
                                             <div class="flex items-center flex-1">
                                                 <svg class="topic-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                                     <polyline points="9 18 15 12 9 6"></polyline>
                                                 </svg>
                                                 <p class="text-xs font-semibold text-gray-600">
                                                     <?php echo htmlspecialchars($topic['title']); ?>
                                                 </p>
                                             </div>
                                         </div>
                                    <?php endif; ?>

<!-- Topic Content -->
                                    <div id="topic-content-<?php echo htmlspecialchars($topic['id'] ?? 'general'); ?>" 
                                         class="topic-content collapsed space-y-1" 
                                         data-module-id="<?php echo htmlspecialchars($module['id'] ?? 'general'); ?>">
                                        <!-- Lessons in Topic -->
                                        <?php 
                                        $topicLessons = array_filter($topic['lessons'], function($l) { return !empty($l['id']); });
                                        if (empty($topicLessons)): ?>
                                            <p class="text-xs text-gray-400 px-4 py-2">No lessons added yet</p>
                                        <?php else: ?>
                                            <?php foreach ($topicLessons as $lesson): ?>
                                                <a href="?id=<?php echo $courseId; ?>&lesson=<?php echo $lesson['id']; ?>" 
                                                   class="lesson-item flex items-center gap-3 px-3 py-2.5 mx-2 rounded-lg transition-all duration-200
                                                   <?php echo ($currentLesson && $currentLesson['id'] == $lesson['id']) 
                                                       ? 'bg-primary-dark text-white shadow-md' 
                                                       : 'text-gray-700 hover:bg-gray-100 active:bg-gray-200'; ?>"
                                                   data-lesson-id="<?php echo $lesson['id']; ?>"
                                                   role="menuitem">
                                                 
                                                    <!-- Progress Icon -->
                                                    <?php if ($lesson['progress_status'] === 'completed'): ?>
                                                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 flex-shrink-0 text-green-500" fill="currentColor" viewBox="0 0 20 20" aria-label="Completed">
                                                            <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" />
                                                        </svg>
                                                    <?php else: ?>
                                                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 flex-shrink-0 <?php echo ($currentLesson && $currentLesson['id'] == $lesson['id']) ? 'text-white' : 'text-gray-400'; ?>" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2" aria-label="Not started">
                                                            <path stroke-linecap="round" stroke-linejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                                                        </svg>
                                                    <?php endif; ?>

                                                    <!-- Lesson Title -->
                                                    <span class="text-sm font-medium truncate flex-1">
                                                        <?php echo htmlspecialchars($lesson['title']); ?>
                                                    </span>
                                                </a>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>

    <!-- Sidebar Overlay for Mobile -->
    <div id="sidebar-overlay" class="sidebar-overlay"></div>

    <!-- 2.2. MAIN LESSON VIEWER -->
    <main class="flex-grow overflow-y-auto sm:ml-80 pt-16">
        <div class="max-w-7xl mx-auto py-8 px-4 sm:px-6 lg:px-8">

            <!-- Lesson Title Header -->
            <?php if ($currentLesson): ?>
            <div class="mb-6">
                <h1 class="text-4xl font-extrabold text-gray-900"><?php echo htmlspecialchars($currentLesson['title']); ?></h1>
            </div>
            <?php endif; ?>

            <!-- Lesson Content Area -->
            <div class="mb-8">
                <?php if ($currentLesson): ?>
                    <?php if ($currentLesson['lesson_type'] === 'video' && $currentLesson['video_url']): ?>
                        <div class="bg-gray-800 rounded-xl overflow-hidden shadow-2xl aspect-video">
                            <?php
                            $videoUrl = $currentLesson['video_url'];
                            $isHttpUrl = strpos($videoUrl, 'http://') === 0 || strpos($videoUrl, 'https://') === 0;

                            if ($isHttpUrl):
                                $isYouTube = strpos($videoUrl, 'youtube.com') !== false || strpos($videoUrl, 'youtu.be') !== false;
                                $isVimeo = strpos($videoUrl, 'vimeo.com') !== false;

                                if ($isYouTube || $isVimeo):
                                    if ($isYouTube) {
                                        if (preg_match('/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/', $videoUrl, $matches)) {
                                            $videoId = $matches[1];
                                            $embedUrl = "https://www.youtube.com/embed/{$videoId}";
                                        } else {
                                            $embedUrl = $videoUrl;
                                        }
                                    } elseif ($isVimeo) {
                                        if (preg_match('/vimeo\.com\/(\d+)/', $videoUrl, $matches)) {
                                            $videoId = $matches[1];
                                            $embedUrl = "https://player.vimeo.com/video/{$videoId}";
                                        } else {
                                            $embedUrl = $videoUrl;
                                        }
                                    } else {
                                        $embedUrl = $videoUrl;
                                    }
                            ?>
                                    <iframe 
                                        src="<?php echo htmlspecialchars($embedUrl); ?>" 
                                        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" 
                                        allowfullscreen 
                                        class="w-full h-full"
                                        loading="lazy"
                                        title="Video player">
                                    </iframe>
                                <?php else: ?>
                                    <?php
                                    // Comprehensive MIME type mapping for all common video/audio formats
                                    $fileExtension = strtolower(pathinfo(parse_url($videoUrl, PHP_URL_PATH), PATHINFO_EXTENSION));
                                    
                                    // Define MIME types for all common video and audio formats
                                    $mimeTypes = [
                                        // Video formats
                                        'mp4' => 'video/mp4',
                                        'webm' => 'video/webm',
                                        'ogg' => 'video/ogg',
                                        'ogv' => 'video/ogg',
                                        'avi' => 'video/x-msvideo',
                                        'mov' => 'video/quicktime',
                                        'wmv' => 'video/x-ms-wmv',
                                        'flv' => 'video/x-flv',
                                        'mkv' => 'video/x-matroska',
                                        '3gp' => 'video/3gpp',
                                        'm4v' => 'video/x-m4v',
                                        // Audio formats
                                        'mp3' => 'audio/mpeg',
                                        'wav' => 'audio/wav',
                                        'ogg' => 'audio/ogg',
                                        'oga' => 'audio/ogg',
                                        'aac' => 'audio/aac',
                                        'm4a' => 'audio/mp4',
                                        'flac' => 'audio/flac',
                                        'wma' => 'audio/x-ms-wma',
                                    ];
                                    
                                    // Determine if it's audio or video and get the correct MIME type
                                    $audioExtensions = ['mp3', 'wav', 'ogg', 'oga', 'aac', 'm4a', 'flac', 'wma'];
                                    $isAudio = in_array($fileExtension, $audioExtensions);
                                    $mimeType = isset($mimeTypes[$fileExtension]) ? $mimeTypes[$fileExtension] : ($isAudio ? 'audio/mpeg' : 'video/mp4');
                                    
                                    // Additional video format support - try to detect from URL if extension is not clear
                                    if (empty($fileExtension) || $fileExtension === 'php') {
                                        // Try to detect from URL pattern
                                        if (strpos($videoUrl, 'video') !== false || strpos($videoUrl, 'watch') !== false) {
                                            $mimeType = 'video/mp4';
                                            $isAudio = false;
                                        }
                                    }
                                    ?>
                                    <?php if ($isAudio): ?>
                                        <div class="bg-gray-900 rounded-xl p-8 flex items-center justify-center">
                                            <audio controls preload="metadata" class="w-full max-w-2xl" id="lesson-media" playsinline>
                                                <source src="<?php echo htmlspecialchars($videoUrl); ?>" type="<?php echo $mimeType; ?>">
                                                Your browser does not support the audio element.
                                            </audio>
                                        </div>
                                    <?php else: ?>
                                        <video controls preload="metadata" class="w-full h-full" id="lesson-media" playsinline crossorigin="anonymous">
                                            <source src="<?php echo htmlspecialchars($videoUrl); ?>" type="<?php echo $mimeType; ?>">
                                            <!-- Fallback for browsers that might not support the primary format -->
                                            <source src="<?php echo htmlspecialchars($videoUrl); ?>" type="video/mp4">
                                            <source src="<?php echo htmlspecialchars($videoUrl); ?>" type="video/webm">
                                            Your browser does not support the video tag.
                                        </video>
                                    <?php endif; ?>
                                    <script>
                                        // Add error handling for video player
                                        document.addEventListener('DOMContentLoaded', function() {
                                            var video = document.getElementById('lesson-media');
                                            if (video) {
                                                video.addEventListener('error', function(e) {
                                                    console.error('Video loading error:', video.error);
                                                    var errorMessage = document.getElementById('video-error-message');
                                                    if (errorMessage) {
                                                        errorMessage.classList.remove('hidden');
                                                    }
                                                });
                                                video.addEventListener('loadstart', function() {
                                                    console.log('Video loading started');
                                                });
                                                video.addEventListener('canplay', function() {
                                                    console.log('Video can play');
                                                });
                                            }
                                        });
                                    </script>
                                    <div id="video-error-message" class="hidden bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mt-4" role="alert">
                                        <p class="font-bold">Video Playback Error</p>
                                        <p>Unable to load the video. Please try a different browser or contact support if the problem persists.</p>
                                    </div>
                                <?php endif; ?>
                            <?php else: ?>
                                <?php
                                // Handle local/relative video URLs with proper MIME type detection
                                $localVideoUrl = $videoUrl;
                                $localFileExtension = strtolower(pathinfo(parse_url($localVideoUrl, PHP_URL_PATH), PATHINFO_EXTENSION));
                                
                                // Comprehensive MIME type mapping for local files
                                $localMimeTypes = [
                                    'mp4' => 'video/mp4',
                                    'webm' => 'video/webm',
                                    'ogg' => 'video/ogg',
                                    'ogv' => 'video/ogg',
                                    'avi' => 'video/x-msvideo',
                                    'mov' => 'video/quicktime',
                                    'wmv' => 'video/x-ms-wmv',
                                    'flv' => 'video/x-flv',
                                    'mkv' => 'video/x-matroska',
                                    '3gp' => 'video/3gpp',
                                    'm4v' => 'video/x-m4v',
                                ];
                                
                                $localMimeType = isset($localMimeTypes[$localFileExtension]) ? $localMimeTypes[$localFileExtension] : 'video/mp4';
                                ?>
                                <video controls preload="metadata" class="w-full h-full" id="lesson-media" playsinline crossorigin="anonymous">
                                    <source src="/<?php echo htmlspecialchars($localVideoUrl); ?>" type="<?php echo $localMimeType; ?>">
                                    <!-- Fallback for browsers that might not support the primary format -->
                                    <source src="/<?php echo htmlspecialchars($localVideoUrl); ?>" type="video/mp4">
                                    <source src="/<?php echo htmlspecialchars($localVideoUrl); ?>" type="video/webm">
                                    Your browser does not support the video tag.
                                </video>
                                <script>
                                    // Add error handling for local video player
                                    document.addEventListener('DOMContentLoaded', function() {
                                        var video = document.getElementById('lesson-media');
                                        if (video) {
                                            video.addEventListener('error', function(e) {
                                                console.error('Video loading error:', video.error);
                                                var container = video.closest('.aspect-video');
                                                if (container) {
                                                    var errorDiv = document.createElement('div');
                                                    errorDiv.className = 'bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded';
                                                    errorDiv.setAttribute('role', 'alert');
                                                    errorDiv.innerHTML = '<p class="font-bold">Video Playback Error</p><p>Unable to load the video from: /<?php echo htmlspecialchars($localVideoUrl); ?></p>';
                                                    container.innerHTML = '';
                                                    container.appendChild(errorDiv);
                                                }
                                            });
                                        }
                                    });
                                </script>
                            <?php endif; ?>
                        </div>

                        <!-- Display lesson content below video if provided -->
                        <?php if (!empty($currentLesson['content'])): ?>
                            <div class="bg-white p-6 rounded-xl shadow-lg mt-6">
                                <h2 class="text-2xl font-semibold text-gray-800 mb-3">Lesson Content</h2>
                                <div class="text-gray-600 leading-relaxed prose max-w-none">
                                    <?php echo $currentLesson['content']; ?>
                                </div>
                            </div>
                        <?php endif; ?>
                    <?php elseif ($currentLesson['lesson_type'] === 'text' && $currentLesson['content']): ?>
                        <div class="bg-white p-6 rounded-xl shadow-lg">
                            <h2 class="text-2xl font-semibold text-gray-800 mb-3">Lesson Content</h2>
                            <div class="text-gray-600 leading-relaxed prose max-w-none">
                                <?php echo $currentLesson['content']; ?>
                            </div>
                        </div>
                    <?php elseif ($currentLesson['lesson_type'] === 'quiz'): ?>
                        <?php if ($currentLesson['progress_status'] === 'completed'): ?>
                            <div class="bg-green-50 p-6 rounded-xl shadow-lg text-center">
                                <h2 class="text-2xl font-semibold text-green-800 mb-4">Quiz Completed</h2>
                                <p class="text-green-600">You have successfully completed this quiz.</p>
                            </div>
                        <?php else: ?>
                            <div class="bg-white p-6 rounded-xl shadow-lg">
                                <h2 class="text-2xl font-semibold text-gray-800 mb-4">Quiz</h2>
                                <p class="text-gray-600 mb-6"><?php echo htmlspecialchars($currentLesson['description'] ?? 'Answer the following question to complete the lesson.'); ?></p>
                                <?php if (isset($error)): ?>
                                    <p class="text-red-600 mb-4"><?php echo $error; ?></p>
                                <?php endif; ?>
                                <form method="post" action="">
                                    <input type="hidden" name="lesson_id" value="<?php echo $currentLesson['id']; ?>">
                                    <div class="mb-4">
                                        <label for="answer" class="block text-sm font-medium text-gray-700 mb-2">What is 2 + 2?</label>
                                        <input type="text" name="answer" id="answer" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent" required>
                                    </div>
                                    <button type="submit" name="submit_quiz" class="bg-primary text-white px-6 py-3 rounded-lg font-semibold hover:bg-primary-dark transition">
                                        Submit Quiz
                                    </button>
                                </form>
                            </div>
                        <?php endif; ?>
                    <?php elseif ($currentLesson['lesson_type'] === 'assignment'): ?>
                        <div class="bg-white p-6 rounded-xl shadow-lg">
                            <h2 class="text-2xl font-semibold text-gray-800 mb-4">Assignment Lesson</h2>
                            <p class="text-gray-600 mb-6"><?php echo htmlspecialchars($currentLesson['description'] ?? 'Complete this assignment.'); ?></p>
                            <div class="text-center">
                                <button onclick="showAssignmentModal()" class="inline-flex items-center gap-2 bg-primary text-white px-6 py-3 rounded-lg font-semibold hover:bg-primary-dark transition duration-150">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
                                    </svg>
                                    Submit Assignment
                                </button>
                            </div>
                        </div>
                    <?php elseif ($currentLesson['lesson_type'] === 'resource' && $currentLesson['attachment_url']): ?>
                        <div class="bg-white p-6 rounded-xl shadow-lg text-center">
                            <h2 class="text-2xl font-semibold text-gray-800 mb-4">Resource Lesson</h2>
                            <p class="text-gray-600 mb-6"><?php echo htmlspecialchars($currentLesson['description'] ?? 'Download the resource below.'); ?></p>
                            <a href="<?php echo htmlspecialchars($currentLesson['attachment_url']); ?>" download class="inline-flex items-center gap-2 bg-primary text-white px-6 py-3 rounded-lg font-semibold hover:bg-primary-dark transition duration-150">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                                </svg>
                                Download Resource
                            </a>
                        </div>
                    <?php else: ?>
                        <div class="bg-gray-800 rounded-xl overflow-hidden shadow-2xl aspect-video flex items-center justify-center text-white text-2xl font-light">
                            <p class="p-8"><?php echo ucfirst($currentLesson['lesson_type'] ?? 'unknown'); ?> Content Goes Here</p>
                        </div>
                    <?php endif; ?>
                <?php else: ?>
                    <div class="bg-gray-800 rounded-xl overflow-hidden shadow-2xl aspect-video flex items-center justify-center text-white text-2xl font-light">
                        <p class="p-8">Select a lesson to begin learning</p>
                    </div>
                <?php endif; ?>
            </div>

            <?php if ($currentLesson): ?>
            <div class="mt-8 flex justify-between items-center">
                <button <?php if ($prevLesson): ?>onclick="navigateLesson(<?php echo $prevLesson['id']; ?>)"<?php endif; ?> class="flex items-center gap-2 <?php echo $prevLesson ? 'bg-primary text-white hover:bg-primary-dark' : 'bg-gray-300 text-gray-500'; ?> px-6 py-3 rounded-lg font-semibold transition duration-150" <?php echo !$prevLesson ? 'disabled' : ''; ?>>
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 19l-7-7 7-7m8 14l-7-7 7-7" />
                    </svg>
                    Previous
                </button>
                <button id="mark-complete" onclick="markLessonComplete(<?php echo $currentLesson['id']; ?>)" class="flex items-center gap-2 bg-green-600 text-white hover:bg-green-700 px-6 py-3 rounded-lg font-semibold transition duration-150" <?php echo $currentLesson['progress_status'] === 'completed' ? 'disabled' : ''; ?>>
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    <?php echo $currentLesson['progress_status'] === 'completed' ? 'Completed' : 'Mark Complete'; ?>
                </button>
                <button <?php if ($nextLesson): ?>onclick="navigateLesson(<?php echo $nextLesson['id']; ?>)"<?php endif; ?> class="flex items-center gap-2 <?php echo $nextLesson ? 'bg-primary text-white hover:bg-primary-dark' : 'bg-gray-300 text-gray-500'; ?> px-6 py-3 rounded-lg font-semibold transition duration-150" <?php echo !$nextLesson ? 'disabled' : ''; ?>>
                    Next
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 5l7 7-7 7M5 5l7 7-7 7" />
                    </svg>
                </button>
            </div>
            <?php endif; ?>

            <!-- Lesson Details and Navigation -->
            <?php if ($currentLesson): ?>
            <div class="bg-white p-6 sm:p-8 rounded-xl shadow-lg">
                <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 border-b pb-4">
                
                
            </div>
            <?php else: ?>
                <div class="bg-white p-6 sm:p-8 rounded-xl shadow-lg text-center">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-16 w-16 text-gray-300 mx-auto mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.746 0 3.332.477 4.5 1.253v13C19.832 18.477 18.246 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
                    </svg>
                    <h3 class="text-xl font-semibold text-gray-900 mb-2">Welcome to <?php echo htmlspecialchars($course['title']); ?></h3>
                    <p class="text-gray-600">Select a lesson from the sidebar to begin your learning journey.</p>
                </div>
            <?php endif; ?>
        </div>
    </main>
</div>

<!-- Assignment Modal -->
<div id="assignmentModal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50">
    <div class="bg-white rounded-xl shadow-2xl max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
        <div class="p-6">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-2xl font-bold text-gray-900">Submit Assignment</h2>
                <button onclick="closeAssignmentModal()" class="text-gray-400 hover:text-gray-600">
                    <i data-lucide="x" class="w-6 h-6"></i>
                </button>
            </div>

            <form id="assignmentForm" enctype="multipart/form-data" class="space-y-6">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Assignment Submission</label>
                    <textarea name="submission_text" rows="6" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none" placeholder="Enter your assignment submission..."></textarea>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Attach Files (Optional)</label>
                    <input type="file" name="attachment" multiple class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100">
                </div>

                <div class="flex justify-end gap-3">
                    <button type="button" onclick="closeAssignmentModal()" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg font-medium hover:bg-gray-300 transition duration-200">
                        Cancel
                    </button>
                    <button type="submit" class="px-6 py-2 bg-blue-600 text-white rounded-lg font-medium hover:bg-blue-700 transition duration-200">
                        Submit Assignment
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>


<script>
// Global click handler for sidebar interactions - more reliable than event listeners
document.addEventListener('click', function(e) {
    // Check for module header click
    let moduleHeader = e.target.closest('.module-header');
    if (moduleHeader) {
        e.preventDefault();
        e.stopPropagation();
        const moduleId = moduleHeader.dataset.moduleId || moduleHeader.getAttribute('data-module-id');
        const contentId = 'module-content-' + moduleId;
        const content = document.getElementById(contentId);
        const icon = moduleHeader.querySelector('.module-icon');
        const isExpanded = moduleHeader.getAttribute('aria-expanded') === 'true';
        
        if (content) {
            if (isExpanded) {
                moduleHeader.setAttribute('aria-expanded', 'false');
                content.classList.add('collapsed');
                content.style.maxHeight = '0';
                if (icon) icon.classList.remove('expanded');
            } else {
                moduleHeader.setAttribute('aria-expanded', 'true');
                content.classList.remove('collapsed');
                content.style.maxHeight = content.scrollHeight + 'px';
                if (icon) icon.classList.add('expanded');
            }
            console.log('Module toggled:', moduleId, !isExpanded);
        }
        return;
    }
    
    // Check for topic header click
    let topicHeader = e.target.closest('.topic-header');
    if (topicHeader) {
        e.preventDefault();
        e.stopPropagation();
        const topicId = topicHeader.dataset.topicId || topicHeader.getAttribute('data-topic-id');
        const contentId = 'topic-content-' + topicId;
        const content = document.getElementById(contentId);
        const icon = topicHeader.querySelector('.topic-icon');
        const isExpanded = topicHeader.getAttribute('aria-expanded') === 'true';
        
        if (content) {
            if (isExpanded) {
                topicHeader.setAttribute('aria-expanded', 'false');
                content.classList.add('collapsed');
                content.style.maxHeight = '0';
                if (icon) icon.classList.remove('expanded');
            } else {
                topicHeader.setAttribute('aria-expanded', 'true');
                content.classList.remove('collapsed');
                content.style.maxHeight = content.scrollHeight + 'px';
                if (icon) icon.classList.add('expanded');
            }
            console.log('Topic toggled:', topicId, !isExpanded);
        }
        return;
    }
});

// Collapsible Sidebar Functionality
class CollapsibleSidebar {
    constructor() {
        this.storageKey = 'curriculum_state_' + currentCourseId;
        this.state = this.loadState();
        // Validate state structure
        if (!this.state || typeof this.state.modules !== 'object' || typeof this.state.topics !== 'object') {
            this.state = { modules: {}, topics: {} };
        }
        this.init();
    }

    init() {
        this.attachModuleListeners();
        this.attachTopicListeners();
        this.restoreState();
        this.expandCurrentPath();
    }

    attachModuleListeners() {
        document.querySelectorAll('.module-header').forEach(header => {
            header.addEventListener('click', (e) => this.toggleModule(e));
            header.addEventListener('keydown', (e) => this.handleModuleKeydown(e));
        });
    }

    attachTopicListeners() {
        document.querySelectorAll('.topic-header').forEach(header => {
            header.addEventListener('click', (e) => this.toggleTopic(e));
            header.addEventListener('keydown', (e) => this.handleTopicKeydown(e));
        });
    }

    toggleModule(event) {
        event.preventDefault();
        const header = event.currentTarget;
        const moduleId = header.getAttribute('data-module-id');
        const contentId = header.getAttribute('aria-controls');
        const content = document.getElementById(contentId);
        const icon = header.querySelector('.module-icon');
        const isExpanded = header.getAttribute('aria-expanded') === 'true';

        if (isExpanded) {
            this.collapseModule(header, content, icon, moduleId);
        } else {
            this.expandModule(header, content, icon, moduleId);
        }
    }

    expandModule(header, content, icon, moduleId) {
        header.setAttribute('aria-expanded', 'true');
        content.classList.remove('collapsed');
        icon.classList.add('expanded');
        this.updateState(moduleId, true, 'module');
    }

    collapseModule(header, content, icon, moduleId) {
        header.setAttribute('aria-expanded', 'false');
        content.classList.add('collapsed');
        icon.classList.remove('expanded');
        this.updateState(moduleId, false, 'module');
        // Collapse all topics in this module
        content.querySelectorAll('.topic-header').forEach(topicHeader => {
            const topicId = topicHeader.getAttribute('data-topic-id');
            const topicContentId = topicHeader.getAttribute('aria-controls');
            const topicContent = document.getElementById(topicContentId);
            const topicIcon = topicHeader.querySelector('.topic-icon');
            this.collapseTopic(topicHeader, topicContent, topicIcon, topicId);
        });
    }

    toggleTopic(event) {
        event.preventDefault();
        const header = event.currentTarget;
        const topicId = header.getAttribute('data-topic-id');
        const contentId = header.getAttribute('aria-controls');
        const content = document.getElementById(contentId);
        const icon = header.querySelector('.topic-icon');
        const isExpanded = header.getAttribute('aria-expanded') === 'true';

        if (isExpanded) {
            this.collapseTopic(header, content, icon, topicId);
        } else {
            this.expandTopic(header, content, icon, topicId);
        }
    }

    expandTopic(header, content, icon, topicId) {
        header.setAttribute('aria-expanded', 'true');
        content.classList.remove('collapsed');
        icon.classList.add('expanded');
        this.updateState(topicId, true, 'topic');
    }

    collapseTopic(header, content, icon, topicId) {
        header.setAttribute('aria-expanded', 'false');
        content.classList.add('collapsed');
        icon.classList.remove('expanded');
        this.updateState(topicId, false, 'topic');
    }

    handleModuleKeydown(event) {
        if (event.key === 'Enter' || event.key === ' ') {
            event.preventDefault();
            this.toggleModule(event);
        }
        // Arrow navigation
        if (event.key === 'ArrowRight') {
            event.preventDefault();
            const header = event.currentTarget;
            if (header.getAttribute('aria-expanded') === 'false') {
                this.toggleModule(event);
            }
        }
        if (event.key === 'ArrowLeft') {
            event.preventDefault();
            const header = event.currentTarget;
            if (header.getAttribute('aria-expanded') === 'true') {
                this.toggleModule(event);
            }
        }
    }

    handleTopicKeydown(event) {
        if (event.key === 'Enter' || event.key === ' ') {
            event.preventDefault();
            this.toggleTopic(event);
        }
        // Arrow navigation
        if (event.key === 'ArrowRight') {
            event.preventDefault();
            const header = event.currentTarget;
            if (header.getAttribute('aria-expanded') === 'false') {
                this.toggleTopic(event);
            }
        }
        if (event.key === 'ArrowLeft') {
            event.preventDefault();
            const header = event.currentTarget;
            if (header.getAttribute('aria-expanded') === 'true') {
                this.toggleTopic(event);
            }
        }
    }

    loadState() {
        const stored = localStorage.getItem(this.storageKey);
        return stored ? JSON.parse(stored) : { modules: {}, topics: {} };
    }

    saveState() {
        localStorage.setItem(this.storageKey, JSON.stringify(this.state));
    }

    updateState(id, isExpanded, type) {
        const key = type === 'module' ? 'modules' : 'topics';
        this.state[key][id] = isExpanded;
        this.saveState();
    }

    restoreState() {
        // Restore module states
        Object.keys(this.state.modules).forEach(moduleId => {
            const header = document.querySelector(`.module-header[data-module-id="${moduleId}"]`);
            if (header) {
                const isExpanded = this.state.modules[moduleId];
                const contentId = header.getAttribute('aria-controls');
                const content = document.getElementById(contentId);
                const icon = header.querySelector('.module-icon');

                if (isExpanded) {
                    this.expandModule(header, content, icon, moduleId);
                } else {
                    this.collapseModule(header, content, icon, moduleId);
                }
            }
        });

        // Restore topic states
        Object.keys(this.state.topics).forEach(topicId => {
            const header = document.querySelector(`.topic-header[data-topic-id="${topicId}"]`);
            if (header) {
                const isExpanded = this.state.topics[topicId];
                const contentId = header.getAttribute('aria-controls');
                const content = document.getElementById(contentId);
                const icon = header.querySelector('.topic-icon');

                if (isExpanded) {
                    this.expandTopic(header, content, icon, topicId);
                } else {
                    this.collapseTopic(header, content, icon, topicId);
                }
            }
        });
    }

    expandCurrentPath() {
        // Find and expand the module and topic of current lesson
        const currentLessonLink = document.querySelector('a[data-lesson-id="' + currentLessonId + '"]');
        if (currentLessonLink) {
            // Find parent topic content
            let topicContent = currentLessonLink.closest('.topic-content');
            if (topicContent) {
                const topicId = topicContent.getAttribute('id');
                const topicHeader = document.querySelector('.topic-header[aria-controls="' + topicId + '"]');
                if (topicHeader && topicHeader.getAttribute('aria-expanded') === 'false') {
                    const icon = topicHeader.querySelector('.topic-icon');
                    this.expandTopic(topicHeader, topicContent, icon, topicHeader.getAttribute('data-topic-id'));
                }

                // Find parent module content
                let moduleContent = topicContent.closest('.module-content');
                if (moduleContent) {
                    const moduleId = moduleContent.getAttribute('id');
                    const moduleHeader = document.querySelector('.module-header[aria-controls="' + moduleId + '"]');
                    if (moduleHeader && moduleHeader.getAttribute('aria-expanded') === 'false') {
                        const icon = moduleHeader.querySelector('.module-icon');
                        this.expandModule(moduleHeader, moduleContent, icon, moduleHeader.getAttribute('data-module-id'));
                    }
                }
            }
        } else {
            // No current lesson - expand the first module and topic for better UX
            const firstModuleHeader = document.querySelector('.module-header');
            if (firstModuleHeader) {
                const firstModuleId = firstModuleHeader.getAttribute('data-module-id');
                const firstModuleContent = document.getElementById('module-content-' + firstModuleId);
                if (firstModuleContent && firstModuleHeader.getAttribute('aria-expanded') === 'false') {
                    const icon = firstModuleHeader.querySelector('.module-icon');
                    this.expandModule(firstModuleHeader, firstModuleContent, icon, firstModuleId);
                    
                    // Also expand first topic
                    const firstTopicHeader = firstModuleContent.querySelector('.topic-header');
                    if (firstTopicHeader) {
                        const firstTopicId = firstTopicHeader.getAttribute('data-topic-id');
                        const firstTopicContent = document.getElementById('topic-content-' + firstTopicId);
                        if (firstTopicContent) {
                            const topicIcon = firstTopicHeader.querySelector('.topic-icon');
                            this.expandTopic(firstTopicHeader, firstTopicContent, topicIcon, firstTopicId);
                        }
                    }
                }
            }
        }
    }
}

// Initialize collapsible sidebar
let currentCourseId = <?php echo $courseId; ?>;
let collapsibleSidebar;

console.log('Initializing collapsible sidebar for course:', currentCourseId);

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

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

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

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

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

let currentLessonId = <?php echo $currentLesson ? $currentLesson['id'] : 'null'; ?>;
let enrollmentId = <?php echo $enrollment['id']; ?>;
let totalLessons = <?php echo $course['total_lessons']; ?>;
let lessonStartTime = Date.now();
let isCompletingLesson = false;

// Mobile Sidebar Toggle Functionality
function initializeMobileSidebar() {
    const toggleButton = document.getElementById('mobile-menu-toggle');
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('sidebar-overlay');
    const closeButton = document.getElementById('sidebar-close');

    if (!toggleButton || !sidebar || !overlay) return;

    // Toggle sidebar open/close
    function toggleSidebar() {
        const isOpen = sidebar.classList.contains('mobile-open');
        if (isOpen) {
            closeSidebar();
        } else {
            openSidebar();
        }
    }

    function openSidebar() {
        sidebar.classList.add('mobile-open');
        overlay.classList.add('mobile-open');
        toggleButton.setAttribute('aria-expanded', 'true');
        // Prevent body scroll when sidebar is open
        document.body.style.overflow = 'hidden';
    }

    function closeSidebar() {
        sidebar.classList.remove('mobile-open');
        overlay.classList.remove('mobile-open');
        toggleButton.setAttribute('aria-expanded', 'false');
        // Restore body scroll
        document.body.style.overflow = '';
    }

    // Event listeners
    toggleButton.addEventListener('click', toggleSidebar);
    if (closeButton) {
        closeButton.addEventListener('click', closeSidebar);
    }
    overlay.addEventListener('click', closeSidebar);

    // Close on Escape key
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && sidebar.classList.contains('mobile-open')) {
            closeSidebar();
        }
    });
}

document.addEventListener('DOMContentLoaded', function() {
    try {
        // Initialize Lucide Icons if available, otherwise skip
        if (typeof lucide !== 'undefined') {
            lucide.createIcons();
        }

        // Initialize collapsible sidebar
        collapsibleSidebar = new CollapsibleSidebar();

        // Expand first module and topic by default for better UX
        setTimeout(function() {
            var firstModule = document.querySelector('.module-header');
            if (firstModule && firstModule.getAttribute('aria-expanded') === 'false') {
                firstModule.click();
            }
            setTimeout(function() {
                var firstTopic = document.querySelector('.topic-header');
                if (firstTopic && firstTopic.getAttribute('aria-expanded') === 'false') {
                    firstTopic.click();
                }
            }, 100);
        }, 300);

        // Initialize mobile sidebar toggle
        initializeMobileSidebar();

        initializeLearningInterface();
    } catch (e) {
        console.error('Initialization error:', e);
    }
});

function initializeLearningInterface() {
    // Track lesson start
    if (currentLessonId) {
        trackLessonStart(currentLessonId);
    }

    // Media tracking (video/audio)
    const mediaElement = document.getElementById('lesson-video') || document.getElementById('lesson-media');
    if (mediaElement) {
        mediaElement.addEventListener('play', () => trackLessonStart(currentLessonId));
        mediaElement.addEventListener('ended', () => {
            // Auto-mark as complete when media ends
            setTimeout(() => markLessonComplete(currentLessonId), 1000);
        });
        mediaElement.addEventListener('error', (e) => {
            console.error('Media error:', e);
            showToast('Unable to load video. Please check the video file or try refreshing the page.', 'error');
        });
    }

    // Auto-save notes
    const notesTextarea = document.getElementById('lesson-notes');
    if (notesTextarea) {
        let notesTimeout;
        notesTextarea.addEventListener('input', function() {
            clearTimeout(notesTimeout);
            notesTimeout = setTimeout(() => saveNotes(), 2000);
        });
    }
}

function navigateLesson(lessonId) {
    if (!lessonId) return;

    // Save current progress before navigating
    saveNotes();

    // Navigate to new lesson
    window.location.href = `learn.php?id=<?php echo $courseId; ?>&lesson=${lessonId}`;
}

function markLessonComplete(lessonId) {
    if (isCompletingLesson) {
        console.log('Already completing lesson, ignoring duplicate request');
        return;
    }

    if (!lessonId || !enrollmentId) {
        console.error('Invalid lessonId or enrollmentId:', lessonId, enrollmentId);
        showToast('Invalid lesson or enrollment data.', 'error');
        return;
    }

    isCompletingLesson = true;
    console.log('Marking lesson complete:', lessonId, 'enrollment:', enrollmentId);

    fetch('../api/lesson_progress.php', {
        method: 'POST',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            lesson_id: lessonId,
            enrollment_id: enrollmentId,
            action: 'complete',
            time_spent: Math.floor((Date.now() - lessonStartTime) / 1000)
        })
    })
    .then(async response => {
        console.log('Response status:', response.status);
        console.log('Response headers:', [...response.headers.entries()]);
        const text = await response.text();
        console.log('Raw response:', text);
        let data;
        try {
            data = JSON.parse(text);
        } catch (parseErr) {
            throw new Error('Invalid JSON: ' + text);
        }
        if (!response.ok) {
            throw new Error('HTTP ' + response.status + ': ' + (data.error || 'Unknown'));
        }
        return data;
    })
    .then(data => {
        console.log('Parsed response data:', data);
        if (data.success) {
            // Update lesson item in sidebar
            const lessonItem = document.querySelector(`[data-lesson-id="${lessonId}"]`);
            if (lessonItem) {
                const icon = lessonItem.querySelector('svg');
                if (icon) {
                    icon.outerHTML = `<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 flex-shrink-0 text-green-500" fill="currentColor" viewBox="0 0 20 20" aria-label="Completed">
                        <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" />
                    </svg>`;
                }
            }

            // Update mark complete button
            const markButton = document.getElementById('mark-complete');
            if (markButton) {
                markButton.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                Completed`;
                markButton.classList.remove('bg-green-600', 'hover:bg-green-700');
                markButton.classList.add('bg-gray-400', 'cursor-not-allowed');
                markButton.disabled = true;
            }

            // Update progress bar and text (use server-calculated percentage when available)
            const serverProgress = Number(data.progress_percentage);
            const serverTotalLessons = Number(data.total_lessons);
            const serverCompletedLessons = Number(data.completed_lessons);

            let newProgress;
            if (!Number.isNaN(serverProgress)) {
                newProgress = Math.min(100, Math.max(0, serverProgress));
            } else {
                const effectiveTotal = totalLessons || 1;
                const completedCount = document.querySelectorAll('.lesson-item svg[aria-label="Completed"]').length;
                newProgress = Math.round((completedCount / effectiveTotal) * 100);
            }

            // Update stored totalLessons if server returns it
            if (!Number.isNaN(serverTotalLessons) && serverTotalLessons > 0) {
                totalLessons = serverTotalLessons;
            }

            const progressText = document.getElementById('progress-text');
            const progressBar = document.getElementById('progress-bar');
            if (progressText) {
                progressText.textContent = `Progress: ${newProgress}%`;
            }
            if (progressBar) {
                progressBar.style.width = `${newProgress}%`;
            }

            // If course is now complete, show a completion message
            if (data.course_status === 'completed' || newProgress >= 100) {
                showToast('Congratulations! You have completed the course.', 'success');
            } else {
                showToast('Lesson marked as complete!', 'success');
            }
        } else {
            showToast('Error updating progress: ' + data.error, 'error');
        }
    })
    .catch(error => {
        console.error('Full fetch error in markLessonComplete:', error);
        console.error('lessonId:', lessonId, 'enrollmentId:', enrollmentId);
        showToast(error.message || 'An error occurred. Check console/logs/lesson_progress.log', 'error');
    })
    .finally(() => {
        isCompletingLesson = false;
    });
}

function trackLessonStart(lessonId) {
    lessonStartTime = Date.now();

    fetch('../api/lesson_progress.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            lesson_id: lessonId,
            enrollment_id: enrollmentId,
            action: 'start'
        })
    });
}

function saveNotes() {
    const notesTextarea = document.getElementById('lesson-notes');
    if (!notesTextarea) return;

    const notes = notesTextarea.value;

    fetch('../api/lesson_notes.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            lesson_id: currentLessonId,
            enrollment_id: enrollmentId,
            notes: notes
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast('Notes saved successfully!', 'success');
        }
    })
    .catch(error => {
        console.error('Error saving notes:', error);
    });
}


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

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

// Assignment form submission
document.getElementById('assignmentForm').addEventListener('submit', function(e) {
    e.preventDefault();

    const formData = new FormData(this);
    formData.append('lesson_id', currentLessonId);
    formData.append('enrollment_id', enrollmentId);

    fetch('../api/assignments.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            closeAssignmentModal();
            showToast('Assignment submitted successfully!', 'success');
            markLessonComplete(currentLessonId);
        } else {
            showToast('Error submitting assignment: ' + data.error, 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('An error occurred. Please try again.', 'error');
    });
});
</script>


</body>
</html>