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

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

// Get course lessons
$stmt = $db->prepare("
    SELECT cl.*,
           COALESCE(clp.status, 'not_started') as progress_status,
           clp.completed_at,
           clp.time_spent
    FROM course_lessons cl
    LEFT JOIN course_lesson_progress clp ON cl.id = clp.lesson_id AND clp.enrollment_id = ?
    WHERE cl.course_id = ?
    ORDER BY cl.sort_order
");
$stmt->execute([$enrollment['id'], $courseId]);
$lessons = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get current lesson (first incomplete or requested)
$currentLessonId = $_GET['lesson'] ?? null;
$currentLesson = 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 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>
    <!-- Load Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Font Awesome for icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        /* Custom Tailwind Configuration */
        :root {
            --primary: #007bff;
            --secondary: #6c757d;
            --success: #28a745;
            --danger: #dc3545;
            --info: #17a2b8;
        }
        .text-primary { color: var(--primary); }
        .bg-primary { background-color: var(--primary); }
        .bg-success { background-color: var(--success); }
        .bg-secondary { background-color: var(--secondary); }

        /* Ensure smooth scrolling and font */
        body { font-family: 'Inter', sans-serif; background-color: #f8f9fa; }

        /* Custom animations */
        .animate-fade-in {
            animation: fadeIn 0.5s ease-in-out;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        /* Video/Audio container responsive */
        .video-container iframe, .video-container video, .video-container audio {
            width: 100%;
            height: auto;
            min-height: 300px;
            border-radius: 8px;
        }

        /* Custom scrollbar for lessons list */
        .lessons-list::-webkit-scrollbar {
            width: 6px;
        }
        .lessons-list::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 3px;
        }
        .lessons-list::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 3px;
        }
        .lessons-list::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }
    </style>
</head>
<body class="min-h-screen flex flex-col bg-gray-50">

<!-- Header / Main Navigation -->
<header class="bg-white shadow-lg sticky top-0 z-10">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between items-center h-16">
            <!-- Logo -->
            <a href="../home.php" class="flex-shrink-0 flex items-center">
                <span class="text-2xl font-extrabold text-primary tracking-tight">Mutalex Academy</span>
            </a>

            <!-- Desktop Navigation Links -->
            <nav class="hidden md:block">
                <div class="flex space-x-2 lg:space-x-4 text-sm font-semibold">
                    <!-- Site Navigation -->
                    <a href="../home.php" class="text-gray-600 hover:text-primary p-2 rounded-lg transition duration-150">Home</a>
                    <a href="../category.php?cat=news" class="text-gray-600 hover:text-primary p-2 rounded-lg transition duration-150">News</a>
                    <a href="../category.php?cat=articles" class="text-gray-600 hover:text-primary p-2 rounded-lg transition duration-150">Articles</a>
                    <a href="../category.php?cat=journals" class="text-gray-600 hover:text-primary p-2 rounded-lg transition duration-150">Journals</a>
                    <a href="#" class="text-gray-600 hover:text-primary p-2 rounded-lg transition duration-150">Surveys</a>
                    <!-- Dashboard Link (Active State) -->
                    <a href="../student/dashboard.php" class="text-white bg-primary p-2 rounded-lg transition duration-150 shadow-md">My Dashboard</a>
                    <a href="../courses/catalog.php" class="text-gray-600 hover:text-primary p-2 rounded-lg transition duration-150">Courses</a>
                </div>
            </nav>

            <!-- Logout Button / Mobile Menu -->
            <div class="flex items-center space-x-4">
                <a href="../logout.php" class="text-red-500 hover:text-red-700 text-sm font-medium hidden sm:block transition duration-150">Logout</a>
                <!-- Mobile Menu Button (Hamburger) -->
                <button id="mobile-menu-button" class="md:hidden p-2 rounded-md text-gray-400 hover:text-gray-500 hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                    <svg class="h-6 w-6" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16m-7 6h7" /></svg>
                </button>
            </div>
        </div>
    </div>

    <!-- Mobile Menu (Hidden by default) -->
    <div id="mobile-menu" class="hidden md:hidden border-t border-gray-100">
        <div class="px-2 pt-2 pb-3 space-y-1 sm:px-3 text-sm">
            <a href="../home.php" class="block px-3 py-2 rounded-md font-medium text-gray-700 hover:bg-gray-50">Home</a>
            <a href="../category.php?cat=news" class="block px-3 py-2 rounded-md font-medium text-gray-700 hover:bg-gray-50">News & Articles</a>
            <a href="../student/dashboard.php" class="block px-3 py-2 rounded-md font-medium text-primary bg-indigo-50/50">My Dashboard</a>
            <a href="../courses/catalog.php" class="block px-3 py-2 rounded-md font-medium text-gray-700 hover:bg-gray-50">Courses</a>
            <a href="../logout.php" class="block px-3 py-2 rounded-md font-medium text-red-500 hover:bg-red-50">Logout</a>
        </div>
    </div>
</header>

<!-- Course Header -->
<section class="bg-white border-b border-gray-200 py-6">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-6">
            <!-- Course Info -->
            <div class="flex-1">
                <h1 class="text-3xl font-bold text-gray-900 mb-3"><?php echo htmlspecialchars($course['title']); ?></h1>
                <div class="flex items-center gap-4">
                    <div class="flex-1">
                        <div class="w-full bg-gray-200 rounded-full h-3 mb-2">
                            <div class="bg-blue-600 h-3 rounded-full transition-all duration-500" style="width: <?php echo $progressPercentage; ?>%"></div>
                        </div>
                        <p class="text-sm text-gray-600"><?php echo $progressPercentage; ?>% Complete</p>
                    </div>
                </div>
            </div>

            <!-- Course Actions -->
            <div class="flex gap-3">
                <a href="detail.php?id=<?php echo $courseId; ?>" class="flex items-center gap-2 bg-white border border-blue-600 text-blue-600 px-4 py-2 rounded-lg font-semibold hover:bg-blue-50 transition duration-200">
                    <i data-lucide="info" class="w-4 h-4"></i>
                    Course Info
                </a>
                <a href="../student/dashboard.php" class="flex items-center gap-2 bg-gray-600 text-white px-4 py-2 rounded-lg font-semibold hover:bg-gray-700 transition duration-200">
                    <i data-lucide="layout-dashboard" class="w-4 h-4"></i>
                    Dashboard
                </a>
            </div>
        </div>
    </div>
</section>

<!-- Main Learning Interface -->
<main class="flex-grow max-w-screen-2xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <div class="grid grid-cols-1 lg:grid-cols-12 gap-8">

        <!-- Left Sidebar - Course Content -->
        <div class="lg:col-span-2">
            <div class="bg-white rounded-xl shadow-lg sticky top-24">
                <div class="p-6 border-b border-gray-200">
                    <div class="flex items-center justify-between">
                        <h3 class="text-lg font-semibold text-gray-900">Course Content</h3>
                        <span class="text-sm text-gray-500 bg-gray-100 px-2 py-1 rounded-full"><?php echo count($lessons); ?> lessons</span>
                    </div>
                </div>

                <div class="lessons-list max-h-96 overflow-y-auto">
                    <?php foreach ($lessons as $index => $lesson): ?>
                        <div class="lesson-item <?php echo $currentLesson && $currentLesson['id'] == $lesson['id'] ? 'active bg-blue-50 border-l-4 border-blue-500' : 'hover:bg-gray-50'; ?> p-4 border-b border-gray-100 cursor-pointer transition duration-200"
                             data-lesson-id="<?php echo $lesson['id']; ?>"
                             onclick="navigateLesson(<?php echo $lesson['id']; ?>)">
                            <div class="flex items-start gap-3">
                                <div class="flex-shrink-0 mt-1">
                                    <?php if ($lesson['progress_status'] === 'completed'): ?>
                                        <i data-lucide="check-circle" class="w-5 h-5 text-green-500"></i>
                                    <?php elseif ($lesson['progress_status'] === 'in_progress'): ?>
                                        <i data-lucide="play-circle" class="w-5 h-5 text-blue-500"></i>
                                    <?php else: ?>
                                        <i data-lucide="circle" class="w-5 h-5 text-gray-400"></i>
                                    <?php endif; ?>
                                </div>
                                <div class="flex-1 min-w-0">
                                    <h4 class="text-sm font-medium text-gray-900 leading-tight mb-1"><?php echo htmlspecialchars($lesson['title']); ?></h4>
                                    <div class="flex items-center gap-3 text-xs text-gray-500">
                                        <span class="flex items-center gap-1">
                                            <i data-lucide="<?php
                                                echo $lesson['lesson_type'] === 'video' ? 'play' :
                                                     ($lesson['lesson_type'] === 'quiz' ? 'help-circle' :
                                                     ($lesson['lesson_type'] === 'assignment' ? 'edit' : 'file-text'));
                                            ?>" class="w-3 h-3"></i>
                                            <?php echo ucfirst($lesson['lesson_type']); ?>
                                        </span>
                                        <?php if ($lesson['estimated_time']): ?>
                                            <span><?php echo $lesson['estimated_time']; ?> min</span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>

        <!-- Main Content Area -->
        <div class="lg:col-span-8">
            <div class="bg-white rounded-xl shadow-lg min-h-[600px]">
                <?php if ($currentLesson): ?>
                    <!-- Lesson Header with Navigation -->
                    <div class="p-6 border-b border-gray-200">
                        <div class="flex justify-between items-center">
                            <?php
                            $currentIndex = array_search($currentLesson['id'], array_column($lessons, 'id'));
                            $prevLesson = $currentIndex !== false && $currentIndex > 0 ? $lessons[$currentIndex - 1] : null;
                            $nextLesson = $currentIndex !== false && $currentIndex < count($lessons) - 1 ? $lessons[$currentIndex + 1] : null;
                            ?>

                            <div class="flex gap-3">
                                <?php if ($prevLesson): ?>
                                    <button onclick="navigateLesson(<?php echo $prevLesson['id']; ?>)" class="flex items-center gap-2 bg-gray-100 text-gray-700 px-4 py-2 rounded-lg font-medium hover:bg-gray-200 transition duration-200">
                                        <i data-lucide="chevron-left" class="w-4 h-4"></i>
                                        Previous
                                    </button>
                                <?php endif; ?>
                            </div>

                            <div class="flex gap-3">
                                <?php if ($nextLesson): ?>
                                    <button onclick="navigateLesson(<?php echo $nextLesson['id']; ?>)" class="flex items-center gap-2 bg-blue-600 text-white px-4 py-2 rounded-lg font-medium hover:bg-blue-700 transition duration-200">
                                        Next
                                        <i data-lucide="chevron-right" class="w-4 h-4"></i>
                                    </button>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Lesson Body -->
                    <div class="p-8">
                        <div class="mb-6">
                            <h2 class="text-2xl font-bold text-gray-900 mb-3"><?php echo htmlspecialchars($currentLesson['title']); ?></h2>
                            <?php if ($currentLesson['description']): ?>
                                <p class="text-gray-600 leading-relaxed"><?php echo htmlspecialchars($currentLesson['description']); ?></p>
                            <?php endif; ?>
                        </div>

                        <!-- Lesson Content Area -->
                        <div class="lesson-content-area mb-8">
                            <?php if ($currentLesson['lesson_type'] === 'video' && $currentLesson['video_url']): ?>
                                <!-- Video/Audio Content -->
                                <div class="video-container mb-6">
                                    <?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):
                                            // External video (YouTube, Vimeo)
                                            if ($isYouTube) {
                                                // Convert YouTube URL to embed URL
                                                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) {
                                                // Convert Vimeo URL to embed URL
                                                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); ?>" allowfullscreen class="w-full aspect-video rounded-lg shadow-md"></iframe>
                                        <?php else: ?>
                                            <!-- Direct video/audio URL -->
                                            <?php
                                            $fileExtension = strtolower(pathinfo(parse_url($videoUrl, PHP_URL_PATH), PATHINFO_EXTENSION));
                                            $audioExtensions = ['mp3', 'wav', 'ogg', 'aac', 'm4a', 'flac'];
                                            $isAudio = in_array($fileExtension, $audioExtensions);
                                            $mimeType = $isAudio ? 'audio/' . $fileExtension : 'video/' . $fileExtension;
                                            if ($fileExtension === 'mp3') $mimeType = 'audio/mpeg';
                                            if ($fileExtension === 'm4a') $mimeType = 'audio/mp4';
                                            ?>
                                            <?php if ($isAudio): ?>
                                                <audio id="lesson-media" controls preload="metadata" class="w-full rounded-lg shadow-md">
                                                    <source src="<?php echo htmlspecialchars($videoUrl); ?>" type="<?php echo $mimeType; ?>">
                                                    Your browser does not support the audio element.
                                                </audio>
                                            <?php else: ?>
                                                <video id="lesson-media" controls preload="metadata" class="w-full rounded-lg shadow-md">
                                                    <source src="<?php echo htmlspecialchars($videoUrl); ?>" type="<?php echo $mimeType; ?>">
                                                    Your browser does not support the video tag.
                                                </video>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <!-- Local video file -->
                                        <video id="lesson-video" controls preload="metadata" class="w-full rounded-lg shadow-md">
                                            <source src="/<?php echo htmlspecialchars($videoUrl); ?>" type="video/mp4">
                                            Your browser does not support the video tag.
                                        </video>
                                    <?php endif; ?>
                                </div>

                            <?php elseif ($currentLesson['lesson_type'] === 'text'): ?>
                                <!-- Text Content -->
                                <div class="text-content prose prose-lg max-w-none">
                                    <?php echo $currentLesson['content']; ?>
                                </div>

                            <?php elseif ($currentLesson['lesson_type'] === 'quiz'): ?>
                                <!-- Quiz Content -->
                                <div class="text-center py-12">
                                    <div class="bg-blue-50 border border-blue-200 rounded-lg p-6 mb-6">
                                        <i data-lucide="help-circle" class="w-12 h-12 text-blue-500 mx-auto mb-4"></i>
                                        <h3 class="text-lg font-semibold text-blue-900 mb-2">Quiz Time!</h3>
                                        <p class="text-blue-700">This lesson contains a quiz. Complete the quiz to mark this lesson as finished.</p>
                                    </div>
                                    <a href="../student/exams/take.php?id=<?php echo $currentLesson['id']; ?>" class="inline-flex items-center gap-2 bg-blue-600 text-white px-6 py-3 rounded-lg font-semibold hover:bg-blue-700 transition duration-200">
                                        <i data-lucide="play" class="w-5 h-5"></i>
                                        Start Quiz
                                    </a>
                                </div>

                            <?php elseif ($currentLesson['lesson_type'] === 'assignment'): ?>
                                <!-- Assignment Content -->
                                <div class="text-center py-12">
                                    <div class="bg-amber-50 border border-amber-200 rounded-lg p-6 mb-6">
                                        <i data-lucide="edit" class="w-12 h-12 text-amber-500 mx-auto mb-4"></i>
                                        <h3 class="text-lg font-semibold text-amber-900 mb-2">Assignment Required</h3>
                                        <p class="text-amber-700">This lesson contains an assignment. Submit your work to complete this lesson.</p>
                                    </div>
                                    <button onclick="showAssignmentModal()" class="inline-flex items-center gap-2 bg-amber-600 text-white px-6 py-3 rounded-lg font-semibold hover:bg-amber-700 transition duration-200">
                                        <i data-lucide="upload" class="w-5 h-5"></i>
                                        Submit Assignment
                                    </button>
                                </div>

                            <?php else: ?>
                                <!-- Resource Content -->
                                <div class="text-center py-12">
                                    <div class="bg-green-50 border border-green-200 rounded-lg p-6 mb-6">
                                        <i data-lucide="file-text" class="w-12 h-12 text-green-500 mx-auto mb-4"></i>
                                        <h3 class="text-lg font-semibold text-green-900 mb-2">Downloadable Resources</h3>
                                        <p class="text-green-700">This lesson contains downloadable resources for your reference.</p>
                                    </div>
                                    <?php if ($currentLesson['attachment_url']): ?>
                                        <a href="<?php echo htmlspecialchars($currentLesson['attachment_url']); ?>" download class="inline-flex items-center gap-2 bg-green-600 text-white px-6 py-3 rounded-lg font-semibold hover:bg-green-700 transition duration-200">
                                            <i data-lucide="download" class="w-5 h-5"></i>
                                            Download Resource
                                        </a>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>
                        </div>

                        <!-- Lesson Footer Actions -->
                        <div class="border-t border-gray-200 pt-6">
                            <div class="flex justify-between items-center">
                                <button id="mark-complete" onclick="markLessonComplete(<?php echo $currentLesson['id']; ?>)" class="flex items-center gap-2 <?php echo $currentLesson['progress_status'] === 'completed' ? 'bg-gray-100 text-gray-600' : 'bg-green-600 text-white hover:bg-green-700'; ?> px-6 py-3 rounded-lg font-semibold transition duration-200" <?php echo $currentLesson['progress_status'] === 'completed' ? 'disabled' : ''; ?>>
                                    <i data-lucide="check" class="w-5 h-5"></i>
                                    <?php echo $currentLesson['progress_status'] === 'completed' ? 'Completed' : 'Mark as Complete'; ?>
                                </button>

                                <button onclick="toggleNotes()" class="flex items-center gap-2 bg-gray-100 text-gray-700 px-6 py-3 rounded-lg font-semibold hover:bg-gray-200 transition duration-200">
                                    <i data-lucide="sticky-note" class="w-5 h-5"></i>
                                    Notes
                                </button>
                            </div>
                        </div>
                    </div>
                <?php else: ?>
                    <!-- Empty State -->
                    <div class="flex items-center justify-center min-h-[600px]">
                        <div class="text-center">
                            <i data-lucide="book-open" class="w-16 h-16 text-gray-300 mx-auto mb-4"></i>
                            <h3 class="text-xl font-semibold text-gray-900 mb-2">No lessons available</h3>
                            <p class="text-gray-600">This course doesn't have any lessons yet.</p>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Right Sidebar - Notes & Progress -->
        <div class="lg:col-span-2 space-y-6">
            <!-- Notes Section -->
            <div class="bg-white rounded-xl shadow-lg">
                <div class="p-6 border-b border-gray-200">
                    <h4 class="text-lg font-semibold text-gray-900 flex items-center gap-2">
                        <i data-lucide="sticky-note" class="w-5 h-5 text-blue-500"></i>
                        My Notes
                    </h4>
                </div>
                <div id="notes-content" class="p-6 hidden">
                    <textarea id="lesson-notes" rows="8" 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="Add your notes here..."><?php
                        // Load existing notes if any
                        echo htmlspecialchars($currentLesson['notes'] ?? '');
                    ?></textarea>
                    <div class="mt-4">
                        <button onclick="saveNotes()" class="w-full bg-blue-600 text-white py-2 px-4 rounded-lg font-medium hover:bg-blue-700 transition duration-200">
                            Save Notes
                        </button>
                    </div>
                </div>
            </div>

            <!-- Course Progress -->
            <div class="bg-white rounded-xl shadow-lg">
                <div class="p-6 border-b border-gray-200">
                    <h4 class="text-lg font-semibold text-gray-900 flex items-center gap-2">
                        <i data-lucide="bar-chart-3" class="w-5 h-5 text-green-500"></i>
                        Course Progress
                    </h4>
                </div>
                <div class="p-6">
                    <!-- Progress Stats -->
                    <div class="grid grid-cols-2 gap-4 mb-6">
                        <div class="text-center">
                            <div class="text-2xl font-bold text-blue-600"><?php echo $completedLessons; ?>/<?php echo count($lessons); ?></div>
                            <div class="text-sm text-gray-500">Lessons Completed</div>
                        </div>
                        <div class="text-center">
                            <div class="text-2xl font-bold text-green-600"><?php echo round($totalTimeSpent / 60, 1); ?>h</div>
                            <div class="text-sm text-gray-500">Time Spent</div>
                        </div>
                    </div>

                    <!-- Lesson Status Breakdown -->
                    <div>
                        <h5 class="text-sm font-semibold text-gray-900 mb-3">Lesson Status</h5>
                        <div class="space-y-2">
                            <div class="flex items-center justify-between">
                                <div class="flex items-center gap-2">
                                    <div class="w-3 h-3 bg-green-500 rounded-full"></div>
                                    <span class="text-sm text-gray-600">Completed</span>
                                </div>
                                <span class="text-sm font-medium text-gray-900"><?php echo $completedLessons; ?></span>
                            </div>
                            <div class="flex items-center justify-between">
                                <div class="flex items-center gap-2">
                                    <div class="w-3 h-3 bg-blue-500 rounded-full"></div>
                                    <span class="text-sm text-gray-600">In Progress</span>
                                </div>
                                <span class="text-sm font-medium text-gray-900"><?php echo count(array_filter($lessons, fn($l) => $l['progress_status'] === 'in_progress')); ?></span>
                            </div>
                            <div class="flex items-center justify-between">
                                <div class="flex items-center gap-2">
                                    <div class="w-3 h-3 bg-gray-400 rounded-full"></div>
                                    <span class="text-sm text-gray-600">Not Started</span>
                                </div>
                                <span class="text-sm font-medium text-gray-900"><?php echo count(array_filter($lessons, fn($l) => $l['progress_status'] === 'not_started')); ?></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

<!-- 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>
// 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 lessonStartTime = Date.now();

document.addEventListener('DOMContentLoaded', function() {
    // Initialize Lucide Icons
    lucide.createIcons();

    // Mobile Menu Toggle
    const mobileMenuButton = document.getElementById('mobile-menu-button');
    const mobileMenu = document.getElementById('mobile-menu');

    if (mobileMenuButton && mobileMenu) {
        mobileMenuButton.addEventListener('click', () => {
            mobileMenu.classList.toggle('hidden');
        });
    }

    initializeLearningInterface();
});

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

    // 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) {
    // Save current progress before navigating
    saveNotes();

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

function markLessonComplete(lessonId) {
    fetch('../api/lesson_progress.php', {
        method: 'POST',
        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(response => response.json())
    .then(data => {
        if (data.success) {
            // Update UI
            const lessonItem = document.querySelector(`[data-lesson-id="${lessonId}"]`);
            if (lessonItem) {
                lessonItem.classList.remove('in-progress', 'not-started');
                lessonItem.classList.add('completed');
                const icon = lessonItem.querySelector('.lesson-icon i');
                if (icon) {
                    icon.className = 'fas fa-check-circle text-success';
                }
            }

            // Update mark complete button
            const markButton = document.getElementById('mark-complete');
            if (markButton) {
                markButton.innerHTML = '<i class="fas fa-check me-1"></i>Completed';
                markButton.classList.remove('btn-success');
                markButton.classList.add('btn-secondary');
                markButton.disabled = true;
            }

            // Show success message
            showToast('Lesson marked as complete!', 'success');
        } else {
            showToast('Error updating progress: ' + data.error, 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('An error occurred. Please try again.', 'error');
    });
}

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 notes = document.getElementById('lesson-notes').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 toggleNotes() {
    const notesContent = document.getElementById('notes-content');
    const isVisible = notesContent.style.display !== 'none';

    notesContent.style.display = isVisible ? 'none' : 'block';
}

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

    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>

<!-- Footer -->
<footer class="bg-gray-800 mt-12 pt-12 pb-8 text-white">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="grid grid-cols-2 md:grid-cols-4 gap-10 border-b border-gray-700 pb-10">
            <!-- Mutalex Academy & Mission -->
            <div class="col-span-2 md:col-span-1">
                <a href="../home.php" class="flex-shrink-0 flex items-center mb-3">
                    <span class="text-xl font-extrabold text-primary tracking-tight">Mutalex Academy</span>
                </a>
                <p class="text-sm text-gray-400 mt-2">
                    Your source for professional courses, news, articles, and journals. Invest in your knowledge today.
                </p>
                <div class="flex space-x-4 mt-4">
                    <a href="#" class="text-gray-400 hover:text-primary transition duration-150"><i data-lucide="linkedin" class="w-5 h-5"></i></a>
                    <a href="#" class="text-gray-400 hover:text-primary transition duration-150"><i data-lucide="twitter" class="w-5 h-5"></i></a>
                    <a href="#" class="text-gray-400 hover:text-primary transition duration-150"><i data-lucide="facebook" class="w-5 h-5"></i></a>
                </div>
            </div>

            <!-- Quick Links -->
            <div>
                <h4 class="text-base font-semibold text-white mb-4">Quick Links</h4>
                <ul class="space-y-3 text-sm">
                    <li><a href="../home.php" class="text-gray-400 hover:text-primary transition duration-150">Home</a></li>
                    <li><a href="../courses/catalog.php" class="text-gray-400 hover:text-primary transition duration-150">Courses</a></li>
                    <li><a href="../student/dashboard.php" class="text-gray-400 hover:text-primary transition duration-150">My Dashboard</a></li>
                    <li><a href="../student/reports.php" class="text-gray-400 hover:text-primary transition duration-150">My Reports</a></li>
                </ul>
            </div>

            <!-- Resources -->
            <div>
                <h4 class="text-base font-semibold text-white mb-4">Resources</h4>
                <ul class="space-y-3 text-sm">
                    <li><a href="../category.php?cat=news" class="text-gray-400 hover:text-primary transition duration-150">News</a></li>
                    <li><a href="../category.php?cat=articles" class="text-gray-400 hover:text-primary transition duration-150">Articles</a></li>
                    <li><a href="../category.php?cat=journals" class="text-gray-400 hover:text-primary transition duration-150">Journals</a></li>
                    <li><a href="#" class="text-gray-400 hover:text-primary transition duration-150">Surveys</a></li>
                </ul>
            </div>

            <!-- Legal & Contact -->
            <div>
                <h4 class="text-base font-semibold text-white mb-4">Legal</h4>
                <ul class="space-y-3 text-sm">
                    <li><a href="#" class="text-gray-400 hover:text-primary transition duration-150">Privacy Policy</a></li>
                    <li><a href="#" class="text-gray-400 hover:text-primary transition duration-150">Terms of Service</a></li>
                    <li><a href="#" class="text-gray-400 hover:text-primary transition duration-150">Help & Support</a></li>
                </ul>
            </div>
        </div>

        <!-- Copyright -->
        <div class="mt-8 text-center text-sm text-gray-500">
            &copy; 2025 Mutalex Academy. All rights reserved.
        </div>
    </div>
</footer>

</body>
</html>