<?php
require_once '../../config/database.php';
require_once '../../config/auth.php';
require_once '../../config/rbac.php';
$lms_config = require '../../config/lms.php';
require_once '../../includes/functions.php';
require_once '../../includes/middleware.php';

// Check if user is instructor or admin
anyRoleMiddleware(['instructor', 'admin']);

$user = getUserContext();
$db = getDB();
$userId = $_SESSION['user_id'];

$courseId = $_GET['course_id'] ?? 0;
$lessonId = $_GET['lesson_id'] ?? 0;
$topicId = $_GET['topic_id'] ?? 0;

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

// Get course details
$stmt = $db->prepare("SELECT * FROM courses WHERE id = ?");
$stmt->execute([$courseId]);
$course = $stmt->fetch();

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

// Check if user can edit this course
if (!canEditCourse($course['instructor_id'])) {
    header('Location: ../dashboard.php');
    exit;
}

// Get lesson details if editing existing lesson
$lesson = null;
$versions = [];
$currentVersion = null;

if ($lessonId) {
    $stmt = $db->prepare("SELECT * FROM course_lessons WHERE id = ? AND course_id = ?");
    $stmt->execute([$lessonId, $courseId]);
    $lesson = $stmt->fetch();

    if (!$lesson) {
        header('Location: course_builder.php?id=' . $courseId);
        exit;
    }

    // Get lesson versions
    $stmt = $db->prepare("SELECT * FROM lesson_versions WHERE lesson_id = ? ORDER BY version_number DESC");
    $stmt->execute([$lessonId]);
    $versions = $stmt->fetchAll();

    // Get current published version
    $stmt = $db->prepare("SELECT * FROM lesson_versions WHERE lesson_id = ? AND is_published = 1 ORDER BY version_number DESC LIMIT 1");
    $stmt->execute([$lessonId]);
    $currentVersion = $stmt->fetch();
}

// Get course modules for organization
$stmt = $db->prepare("SELECT * FROM course_modules WHERE course_id = ? AND is_active = 1 ORDER BY sort_order");
$stmt->execute([$courseId]);
$modules = $stmt->fetchAll();

// Get course topics with module information
$stmt = $db->prepare("
    SELECT ct.*, cm.title as module_title 
    FROM course_topics ct
    LEFT JOIN course_modules cm ON ct.module_id = cm.id
    WHERE ct.module_id IN (SELECT id FROM course_modules WHERE course_id = ?)
    ORDER BY cm.sort_order, ct.sort_order
");
$stmt->execute([$courseId]);
$topics = $stmt->fetchAll();

// Get course resources for embedding
$stmt = $db->prepare("SELECT id, title, resource_type, file_path, external_url FROM course_resources WHERE course_id = ? AND is_active = 1 ORDER BY title");
$stmt->execute([$courseId]);
$resources = $stmt->fetchAll();

$message = '';
$error = '';
$videoPath = '';

// Handle AJAX video upload before any other processing
if (isset($_FILES['video_file']) && $_FILES['video_file']['error'] === UPLOAD_ERR_OK && isset($_POST['action']) && $_POST['action'] === 'upload_video') {
    $videoTypes = ['mp4', 'webm', 'ogg', 'mov', 'avi', 'wmv'];
    $maxVideoSize = 500 * 1024 * 1024;
    $uploadError = '';
    $uploadMessage = '';
    $uploadedPath = '';
    
    if ($_FILES['video_file']['size'] > $maxVideoSize) {
        $uploadError = 'Video file is too large. Maximum size is 500MB.';
    } else {
        $fileExtension = strtolower(pathinfo($_FILES['video_file']['name'], PATHINFO_EXTENSION));
        if (!in_array($fileExtension, $videoTypes)) {
            $uploadError = 'Invalid video file type. Allowed: ' . implode(', ', $videoTypes);
        } else {
            $uploadDir = '../../uploads/videos/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
            
            $fileName = time() . '_' . basename($_FILES['video_file']['name']);
            $targetPath = $uploadDir . $fileName;
            
            if (move_uploaded_file($_FILES['video_file']['tmp_name'], $targetPath)) {
                $uploadedPath = 'uploads/videos/' . $fileName;
                $uploadMessage = 'Video uploaded successfully.';
            } else {
                $uploadError = 'Failed to upload video. PHP error code: ' . $_FILES['video_file']['error'];
            }
        }
    }
    
    header('Content-Type: application/json');
    
    if (!empty($uploadError)) {
        echo json_encode(['success' => false, 'message' => $uploadError]);
    } elseif (!empty($uploadMessage)) {
        echo json_encode(['success' => true, 'message' => $uploadMessage, 'video_path' => $uploadedPath]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Unknown error']);
    }
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' || isset($_FILES['video_file'])) {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'save_lesson':
                $title = trim($_POST['title']);
                $description = trim($_POST['description']);
                $moduleId = !empty($_POST['module_id']) ? $_POST['module_id'] : null;
                $topicId = !empty($_POST['topic_id']) ? $_POST['topic_id'] : null;
                $content = $_POST['content'];
                $lessonType = $_POST['lesson_type'];
                $videoUrl = trim($_POST['video_url']);
                $attachmentUrl = trim($_POST['attachment_url']);
                $attachmentName = trim($_POST['attachment_name']);
                $sortOrder = intval($_POST['sort_order']);
                $isPreview = isset($_POST['is_preview']);
                $estimatedTime = intval($_POST['estimated_time']);
                $learningObjectives = array_filter(array_map('trim', $_POST['learning_objectives'] ?? []));
                $prerequisites = array_filter(array_map('intval', $_POST['prerequisites'] ?? []));

                if (empty($title) || empty($content)) {
                    $error = 'Title and content are required.';
                } else {
                    try {
                        $db->beginTransaction();

                        if ($lessonId) {
                            // Update existing lesson
                            $stmt = $db->prepare("UPDATE course_lessons SET title = ?, description = ?, module_id = ?, topic_id = ?, content = ?, lesson_type = ?, video_url = ?, attachment_url = ?, attachment_name = ?, sort_order = ?, is_preview = ?, estimated_time = ?, learning_objectives = ?, prerequisites = ?, updated_at = NOW() WHERE id = ?");
                            $stmt->execute([
                                $title, $description, $moduleId, $topicId, $content, $lessonType, $videoUrl,
                                $attachmentUrl, $attachmentName, $sortOrder, $isPreview, $estimatedTime,
                                json_encode($learningObjectives), json_encode($prerequisites), $lessonId
                            ]);

                            $message = 'Lesson updated successfully.';
                        } else {
                            // Create new lesson
                            $slug = createSlug($title);
                            $originalSlug = $slug;
                            $counter = 1;
                            while (true) {
                                $stmt = $db->prepare("SELECT id FROM course_lessons WHERE course_id = ? AND slug = ?");
                                $stmt->execute([$courseId, $slug]);
                                if (!$stmt->fetch()) break;
                                $slug = $originalSlug . '-' . $counter;
                                $counter++;
                            }

                            $stmt = $db->prepare("INSERT INTO course_lessons (course_id, module_id, topic_id, title, slug, description, content, lesson_type, video_url, attachment_url, attachment_name, sort_order, is_preview, estimated_time, learning_objectives, prerequisites, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");
                            $stmt->execute([
                                $courseId, $moduleId, $topicId, $title, $slug, $description, $content, $lessonType, $videoUrl,
                                $attachmentUrl, $attachmentName, $sortOrder, $isPreview, $estimatedTime,
                                json_encode($learningObjectives), json_encode($prerequisites)
                            ]);

                            $lessonId = $db->lastInsertId();
                            $message = 'Lesson created successfully.';
                        }

                        $db->commit();

                        // Refresh lesson data
                        $stmt = $db->prepare("SELECT * FROM course_lessons WHERE id = ?");
                        $stmt->execute([$lessonId]);
                        $lesson = $stmt->fetch();

                    } catch (PDOException $e) {
                        $db->rollBack();
                        $error = 'Error saving lesson: ' . $e->getMessage();
                    }
                }
                break;

            case 'save_version':
                $versionTitle = trim($_POST['version_title']);
                $versionDescription = trim($_POST['version_description']);
                $changesDescription = trim($_POST['changes_description']);
                $isPublished = isset($_POST['is_published']);

                if (empty($versionTitle)) {
                    $error = 'Version title is required.';
                } elseif (!$lessonId) {
                    $error = 'Cannot save version for unsaved lesson.';
                } else {
                    try {
                        // Get next version number
                        $stmt = $db->prepare("SELECT MAX(version_number) as max_version FROM lesson_versions WHERE lesson_id = ?");
                        $stmt->execute([$lessonId]);
                        $result = $stmt->fetch();
                        $nextVersion = ($result['max_version'] ?? 0) + 1;

                        // If publishing, unpublish previous versions
                        if ($isPublished) {
                            $stmt = $db->prepare("UPDATE lesson_versions SET is_published = 0 WHERE lesson_id = ?");
                            $stmt->execute([$lessonId]);
                        }

                        $stmt = $db->prepare("INSERT INTO lesson_versions (lesson_id, version_number, title, description, content, video_url, attachment_url, attachment_name, changes_description, is_published, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
                        $stmt->execute([
                            $lessonId, $nextVersion, $versionTitle, $versionDescription,
                            $lesson['content'], $lesson['video_url'], $lesson['attachment_url'],
                            $lesson['attachment_name'], $changesDescription, $isPublished, $userId
                        ]);

                        $message = 'Version saved successfully.';

                        // Refresh versions
                        $stmt = $db->prepare("SELECT * FROM lesson_versions WHERE lesson_id = ? ORDER BY version_number DESC");
                        $stmt->execute([$lessonId]);
                        $versions = $stmt->fetchAll();

                    } catch (PDOException $e) {
                        $error = 'Error saving version: ' . $e->getMessage();
                    }
                }
                break;

            case 'restore_version':
                $versionId = $_POST['version_id'];

                try {
                    $stmt = $db->prepare("SELECT * FROM lesson_versions WHERE id = ? AND lesson_id = ?");
                    $stmt->execute([$versionId, $lessonId]);
                    $version = $stmt->fetch();

                    if ($version) {
                        $stmt = $db->prepare("UPDATE course_lessons SET title = ?, description = ?, content = ?, video_url = ?, attachment_url = ?, attachment_name = ?, updated_at = NOW() WHERE id = ?");
                        $stmt->execute([
                            $version['title'], $version['description'], $version['content'],
                            $version['video_url'], $version['attachment_url'], $version['attachment_name'],
                            $lessonId
                        ]);

                        $message = 'Version restored successfully.';

                        // Refresh lesson data
                        $stmt = $db->prepare("SELECT * FROM course_lessons WHERE id = ?");
                        $stmt->execute([$lessonId]);
                        $lesson = $stmt->fetch();
                    } else {
                        $error = 'Version not found.';
                    }

                } catch (PDOException $e) {
                    $error = 'Error restoring version: ' . $e->getMessage();
                }
                break;

            case 'preview_lesson':
                // Preview is handled via JavaScript
                break;

            case 'upload_video':
                $videoTypes = ['mp4', 'webm', 'ogg', 'mov', 'avi', 'wmv'];
                $maxVideoSize = 500 * 1024 * 1024; // 500MB
                
                if (!isset($_FILES['video_file']) || $_FILES['video_file']['error'] !== UPLOAD_ERR_OK) {
                    $error = 'No video file uploaded.';
                } elseif ($_FILES['video_file']['size'] > $maxVideoSize) {
                    $error = 'Video file is too large. Maximum size is 500MB.';
                } else {
                    $fileExtension = strtolower(pathinfo($_FILES['video_file']['name'], PATHINFO_EXTENSION));
                    if (!in_array($fileExtension, $videoTypes)) {
                        $error = 'Invalid video file type. Allowed: ' . implode(', ', $videoTypes);
                    } else {
                        $uploadDir = '../../uploads/videos/';
                        if (!is_dir($uploadDir)) {
                            mkdir($uploadDir, 0755, true);
                        }
                        $newFilename = 'video_' . time() . '_' . bin2hex(random_bytes(8)) . '.' . $fileExtension;
                        $targetPath = $uploadDir . $newFilename;
                        
                        if (move_uploaded_file($_FILES['video_file']['tmp_name'], $targetPath)) {
                            $videoPath = 'uploads/videos/' . $newFilename;
                            $message = 'Video uploaded successfully.';
                        } else {
                            $error = 'Failed to upload video.';
                        }
                    }
                }
                break;
        }
    }
}

$page_title = ($lessonId ? 'Edit' : 'Create') . ' Lesson: ' . htmlspecialchars($course['title']);
$active_link = 'courses';
?>
<!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 -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Set up Tailwind configuration for Inter font and a professional color palette -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'primary-blue': '#1E3A8A', // Deep Indigo/Navy
                        'background-light': '#F8FAFC', // Slate 50
                        'text-dark': '#1F2937', // Gray 800
                        'accent-subtle': '#E5E7EB', // Gray 200
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </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>
        /* Ensuring full page height and scrolling */
        html, body {
            height: 100%;
        }
        /* Custom scrollbar for a cleaner look */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        ::-webkit-scrollbar-thumb {
            background-color: #D1D5DB; /* Gray 300 */
            border-radius: 4px;
        }
        ::-webkit-scrollbar-track {
            background-color: transparent;
        }

        /* Custom Styles for Dashboard Layout */
        .admin-sidebar {
            transition: transform 0.3s ease-in-out;
            min-width: 250px;
            /* Using min-h-screen utility class */
        }
        @media (max-width: 1024px) {
            .admin-sidebar {
                position: fixed;
                top: 0;
                left: 0; /* Always positioned at 0, use transform to hide */
                transform: translateX(-100%); /* Hidden by default on mobile */
                z-index: 50;
                height: 100%;
            }
            .admin-container.sidebar-open .admin-sidebar {
                transform: translateX(0); /* Show on mobile */
            }
            .admin-container.sidebar-open .sidebar-overlay {
                display: block;
            }
        }

        /* Sidebar Overlay for Mobile */
        .sidebar-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 40;
            display: none;
            transition: opacity 0.3s ease;
        }

        /* Toast Notification Styles */
        #toast-container {
            position: fixed;
            top: 1.5rem;
            right: 1.5rem;
            z-index: 100;
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
            max-width: 350px;
        }

        .toast {
            padding: 1rem 1.5rem;
            border-radius: 0.5rem;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            color: white;
            opacity: 0;
            transform: translateX(100%);
            transition: opacity 0.3s ease-out, transform 0.3s ease-out;
        }

        .toast.show {
            opacity: 1;
            transform: translateX(0);
        }

        .toast-success { background-color: #10b981; }
        .toast-error { background-color: #ef4444; }

        /* Rating Stars */
        .rating .fas.fa-star {
            color: #ddd; /* Unfilled */
        }
        .rating .fas.fa-star.filled {
            color: #ffc107; /* Filled (Yellow/Gold) */
        }

        /* Editor Styles */
        #editor-toolbar {
            border: 1px solid #d1d5db;
            border-bottom: none;
            padding: 5px;
            background-color: #f9fafb;
        }

        .content-editor {
            border: 1px solid #d1d5db;
            border-radius: 0 0 0.375rem 0.375rem;
            min-height: 400px;
            overflow-y: auto;
        }

        .content-editor:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 1px #3b82f6;
        }

        .version-item {
            border-left: 3px solid #3b82f6;
        }

        .version-item:hover {
            background-color: #f9fafb;
        }

        .resource-list {
            max-height: 300px;
            overflow-y: auto;
        }

        /* Tab Styles */
        .tab-button {
            padding: 0.5rem 1rem;
            border-bottom: 2px solid transparent;
            cursor: pointer;
            transition: all 0.2s;
        }
        .tab-button.active {
            border-bottom-color: #3b82f6;
            color: #3b82f6;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
    </style>
</head>
<body class="bg-background-light font-sans text-text-dark min-h-screen">

<!-- Toast Notification Container -->
<div id="toast-container"></div>

<!-- Sidebar Overlay (for closing sidebar on mobile tap outside) -->
<div id="sidebar-overlay" class="sidebar-overlay lg:hidden"></div>

<div class="flex">
    <?php include '../includes/sidebar.php'; ?>

    <!-- Top Bar (Mobile/Desktop Header) -->
    <header class="bg-white shadow-sm fixed top-0 left-0 right-0 z-10 border-b border-accent-subtle">
        <div class="px-4 sm:px-6 lg:px-8 py-4 flex justify-between items-center">
            <div class="flex items-center space-x-3">
                <img src="../../assets/images/logo_1757657555.jpg" alt="Instructor Panel Logo" class="h-10 w-10">
                <div>
                    <h1 class="text-xl font-bold text-primary-blue"><?php echo htmlspecialchars($lms_config['lms']['site_name']); ?></h1>
                    <p class="text-sm text-gray-600"><?php echo htmlspecialchars($page_title); ?></p>
                </div>
            </div>

            <div class="flex items-center space-x-4">
                <span class="text-sm font-medium hidden sm:inline"><?php echo htmlspecialchars($user['username']); ?></span>
                <img class="h-10 w-10 rounded-full border-2 border-primary-blue object-cover" src="https://placehold.co/100x100/1E3A8A/ffffff?text=<?php echo substr(htmlspecialchars($user['username'] ?? 'I'), 0, 1); ?>" alt="User Avatar">
                <!-- Mobile Menu Button (Hamburger) -->
                <button class="lg:hidden p-2 rounded-lg text-text-dark hover:bg-accent-subtle ml-4" id="mobileMenuButton">
                    <span class="text-xl">☰</span>
                </button>
            </div>
        </div>
    </header>

    <!-- Main Content Area -->
    <main class="flex-1 overflow-y-auto pt-16">

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

        <!-- Page Header -->
        <div class="bg-white shadow-sm">
            <div class="px-4 sm:px-6 lg:px-8 py-6">
                <div class="flex justify-between items-center">
                    <div>
                        <h1 class="text-3xl font-bold text-gray-900"><?php echo $lessonId ? 'Edit' : 'Create'; ?> Lesson</h1>
                        <p class="text-sm text-gray-600 mt-1">Course: <?php echo htmlspecialchars($course['title']); ?></p>
                    </div>
                    <div class="flex items-center space-x-4">
                        <button class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg shadow hover:bg-gray-300 transition duration-150" onclick="previewLesson()">
                            <i class="fas fa-eye mr-2"></i>Preview
                        </button>
                        <a href="course_builder.php?id=<?php echo $courseId; ?>" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg shadow hover:bg-gray-300 transition duration-150">
                            <i class="fas fa-arrow-left mr-2"></i>Back to Course
                        </a>
                        <button class="px-4 py-2 bg-blue-600 text-white rounded-lg shadow hover:bg-blue-700 transition duration-150" onclick="saveLesson()">
                            <i class="fas fa-save mr-2"></i>Save Lesson
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Page Content -->
        <div class="px-4 sm:px-6 lg:px-8 py-8 admin-content">

            <!-- Alerts -->
            <?php if ($message): ?>
                <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-6" role="alert">
                    <?php echo htmlspecialchars($message); ?>
                </div>
            <?php endif; ?>

            <?php if ($error): ?>
                <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6" role="alert">
                    <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>

            <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- Editor Panel -->
            <div class="lg:col-span-2">
                <div class="bg-white rounded-xl shadow-lg">
                    <div class="border-b border-gray-200">
                        <div class="flex">
                            <button class="tab-button active px-6 py-3 text-sm font-medium" onclick="switchTab('content')">Content</button>
                            <button class="tab-button px-6 py-3 text-sm font-medium" onclick="switchTab('media')">Media</button>
                            <button class="tab-button px-6 py-3 text-sm font-medium" onclick="switchTab('resources')">Resources</button>
                            <button class="tab-button px-6 py-3 text-sm font-medium" onclick="switchTab('versions')">Versions</button>
                        </div>
                    </div>
                    <div class="p-6">
                        <form id="lessonForm" method="POST">
                            <input type="hidden" name="action" value="save_lesson">
                            <input type="hidden" name="course_id" value="<?php echo $courseId; ?>">

                            <!-- Content Tab -->
                            <div id="content-tab" class="tab-content active">
                                <div class="mb-4">
                                    <label for="lessonTitle" class="block text-sm font-medium text-gray-700 mb-2">Lesson Title <span class="text-red-500">*</span></label>
                                    <input type="text" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition" id="lessonTitle" name="title" value="<?php echo htmlspecialchars($lesson['title'] ?? ''); ?>" placeholder="Enter lesson title" required>
                                    <p class="text-xs text-gray-500 mt-1">Required field</p>
                                </div>

                                <div class="mb-4">
                                    <label for="lessonDescription" class="block text-sm font-medium text-gray-700 mb-2">Description</label>
                                    <textarea class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" id="lessonDescription" name="description" rows="3"><?php echo htmlspecialchars($lesson['description'] ?? ''); ?></textarea>
                                </div>

                                <div class="mb-4">
                                    <label for="lessonContent" class="block text-sm font-medium text-gray-700 mb-2">Content <span class="text-red-500">*</span></label>
                                    <div id="editor-toolbar" class="flex flex-wrap items-center gap-1 p-2 bg-gray-50 border border-gray-300 rounded-t-lg">
                                        <button type="button" class="px-2 py-1 text-sm bg-white border border-gray-300 rounded hover:bg-gray-100" onclick="formatText('bold')"><i class="fas fa-bold"></i></button>
                                        <button type="button" class="px-2 py-1 text-sm bg-white border border-gray-300 rounded hover:bg-gray-100" onclick="formatText('italic')"><i class="fas fa-italic"></i></button>
                                        <button type="button" class="px-2 py-1 text-sm bg-white border border-gray-300 rounded hover:bg-gray-100" onclick="formatText('underline')"><i class="fas fa-underline"></i></button>
                                        <span class="mx-2 text-gray-400">|</span>
                                        <button type="button" class="px-2 py-1 text-sm bg-white border border-gray-300 rounded hover:bg-gray-100" onclick="formatBlock('h1')">H1</button>
                                        <button type="button" class="px-2 py-1 text-sm bg-white border border-gray-300 rounded hover:bg-gray-100" onclick="formatBlock('h2')">H2</button>
                                        <button type="button" class="px-2 py-1 text-sm bg-white border border-gray-300 rounded hover:bg-gray-100" onclick="formatBlock('h3')">H3</button>
                                        <span class="mx-2 text-gray-400">|</span>
                                        <button type="button" class="px-2 py-1 text-sm bg-white border border-gray-300 rounded hover:bg-gray-100" onclick="insertLink()"><i class="fas fa-link"></i></button>
                                        <button type="button" class="px-2 py-1 text-sm bg-white border border-gray-300 rounded hover:bg-gray-100" onclick="insertImage()"><i class="fas fa-image"></i></button>
                                        <button type="button" class="px-2 py-1 text-sm bg-white border border-gray-300 rounded hover:bg-gray-100" onclick="insertVideo()"><i class="fas fa-video"></i></button>
                                        <span class="mx-2 text-gray-400">|</span>
                                        <button type="button" class="px-2 py-1 text-sm bg-white border border-gray-300 rounded hover:bg-gray-100" onclick="insertResource()"><i class="fas fa-paperclip"></i></button>
                                    </div>
                                    <div id="lessonContent" class="content-editor w-full px-3 py-2 border border-gray-300 rounded-b-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent min-h-96" contenteditable="true"><?php echo $lesson['content'] ?? ''; ?></div>
                                    <input type="hidden" name="content" id="contentInput">
                                    <p class="text-xs text-gray-500 mt-1">Required field - Add text, images, videos, or links to create your lesson content</p>
                                </div>
                            </div>

                            <!-- Media Tab -->
                            <div id="media-tab" class="tab-content">
                                <div class="mb-4">
                                    <label for="lessonType" class="block text-sm font-medium text-gray-700 mb-2">Lesson Type</label>
                                    <select class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" id="lessonType" name="lesson_type">
                                        <option value="text" <?php echo ($lesson['lesson_type'] ?? 'text') === 'text' ? 'selected' : ''; ?>>Text</option>
                                        <option value="video" <?php echo ($lesson['lesson_type'] ?? '') === 'video' ? 'selected' : ''; ?>>Video</option>
                                        <option value="quiz" <?php echo ($lesson['lesson_type'] ?? '') === 'quiz' ? 'selected' : ''; ?>>Quiz</option>
                                        <option value="assignment" <?php echo ($lesson['lesson_type'] ?? '') === 'assignment' ? 'selected' : ''; ?>>Assignment</option>
                                        <option value="resource" <?php echo ($lesson['lesson_type'] ?? '') === 'resource' ? 'selected' : ''; ?>>Resource</option>
                                    </select>
                                </div>

                                <div id="videoSection" class="hidden">
                                    <div class="mb-4">
                                        <label class="block text-sm font-medium text-gray-700 mb-2">Video Source</label>
                                        <div class="flex gap-2 mb-3">
                                            <button type="button" class="px-3 py-1 text-sm bg-gray-200 rounded" onclick="switchVideoSource('url')" id="btnVideoUrl">URL</button>
                                            <button type="button" class="px-3 py-1 text-sm bg-white border border-gray-300 rounded" onclick="switchVideoSource('upload')" id="btnVideoUpload">Upload</button>
                                        </div>
                                    </div>
                                    
                                    <div id="videoUrlSection">
                                        <div class="mb-4">
                                            <label for="videoUrl" class="block text-sm font-medium text-gray-700 mb-2">Video URL</label>
                                            <input type="url" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" id="videoUrl" name="video_url" value="<?php echo htmlspecialchars($lesson['video_url'] ?? ''); ?>" placeholder="https://www.youtube.com/watch?v=... or https://vimeo.com/...">
                                            <p class="text-sm text-gray-500 mt-1">Supports YouTube, Vimeo, and direct video URLs</p>
                                        </div>
                                    </div>
                                    
                                    <div id="videoUploadSection" class="hidden">
                                        <div class="mb-4">
                                            <label for="videoFile" class="block text-sm font-medium text-gray-700 mb-2">Upload Video</label>
                                            <div class="border-2 border-dashed border-gray-300 rounded-lg p-4 text-center">
                                                <input type="file" id="videoFile" name="video_file" accept="video/*" class="hidden" onchange="handleVideoSelect(this)">
                                                <label for="videoFile" class="cursor-pointer">
                                                    <i class="fas fa-cloud-upload-alt text-3xl text-gray-400 mb-2"></i>
                                                    <p class="text-sm text-gray-600">Click to select video file</p>
                                                    <p class="text-xs text-gray-500 mt-1">MP4, WebM, OGG, MOV (max 500MB)</p>
                                                </label>
                                            </div>
                                            <div id="videoUploadProgress" class="hidden mt-3">
                                                <div class="w-full bg-gray-200 rounded-full h-2">
                                                    <div id="videoProgressBar" class="bg-blue-600 h-2 rounded-full" style="width: 0%"></div>
                                                </div>
                                                <p id="videoUploadStatus" class="text-sm text-gray-600 mt-1">Uploading...</p>
                                            </div>
                                            <div id="videoPreview" class="hidden mt-3">
                                                <video id="uploadedVideoPlayer" class="w-full rounded" controls></video>
                                                <input type="hidden" id="uploadedVideoPath" name="video_url">
                                                <button type="button" class="text-red-500 text-sm mt-2" onclick="removeUploadedVideo()">Remove Video</button>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div id="resourceSection" class="hidden">
                                    <div class="mb-4">
                                        <label for="attachmentUrl" class="block text-sm font-medium text-gray-700 mb-2">Attachment URL</label>
                                        <input type="url" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" id="attachmentUrl" name="attachment_url" value="<?php echo htmlspecialchars($lesson['attachment_url'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-4">
                                        <label for="attachmentName" class="block text-sm font-medium text-gray-700 mb-2">Attachment Name</label>
                                        <input type="text" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" id="attachmentName" name="attachment_name" value="<?php echo htmlspecialchars($lesson['attachment_name'] ?? ''); ?>">
                                    </div>
                                </div>
                            </div>

                            <!-- Resources Tab -->
                            <div id="resources-tab" class="tab-content">
                                <div class="mb-4">
                                    <button type="button" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition duration-150" onclick="openResourceModal()">
                                        <i class="fas fa-plus mr-2"></i>Add Resource
                                    </button>
                                </div>
                                <div id="lessonResources" class="resource-list">
                                    <!-- Resources will be loaded here -->
                                </div>
                            </div>

                            <!-- Versions Tab -->
                            <div id="versions-tab" class="tab-content">
                                <div class="flex justify-between items-center mb-4">
                                    <h3 class="text-lg font-semibold text-gray-800">Version History</h3>
                                    <button type="button" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition duration-150" onclick="saveVersion()">
                                        <i class="fas fa-save mr-2"></i>Save Version
                                    </button>
                                </div>

                                <div class="version-list space-y-3">
                                    <?php if (empty($versions)): ?>
                                        <p class="text-gray-500">No versions saved yet.</p>
                                    <?php else: ?>
                                        <?php foreach ($versions as $version): ?>
                                            <div class="version-item bg-white border border-gray-200 rounded-lg p-4">
                                                <div class="flex justify-between items-center">
                                                    <div>
                                                        <strong class="text-blue-600">v<?php echo $version['version_number']; ?></strong>
                                                        <span class="text-gray-700 ml-2"><?php echo htmlspecialchars($version['title']); ?></span>
                                                        <?php if ($version['is_published']): ?>
                                                            <span class="ml-2 px-2 py-1 bg-green-100 text-green-800 text-xs rounded-full">Published</span>
                                                        <?php endif; ?>
                                                    </div>
                                                    <div class="flex items-center space-x-2">
                                                        <small class="text-gray-500"><?php echo date('M j, Y H:i', strtotime($version['created_at'])); ?></small>
                                                        <button type="button" class="px-2 py-1 bg-gray-200 text-gray-700 rounded hover:bg-gray-300" onclick="restoreVersion(<?php echo $version['id']; ?>)">
                                                            <i class="fas fa-undo"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                                <?php if ($version['changes_description']): ?>
                                                    <div class="text-gray-600 text-sm mt-2"><?php echo htmlspecialchars($version['changes_description']); ?></div>
                                                <?php endif; ?>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Common Fields -->
                            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mt-6 pt-6 border-t border-gray-200">
                                <div>
                                    <label for="moduleId" class="block text-sm font-medium text-gray-700 mb-2">Module</label>
                                    <select class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" id="moduleId" name="module_id">
                                        <option value="">No module</option>
                                        <?php foreach ($modules as $module): ?>
                                            <option value="<?php echo $module['id']; ?>" <?php echo ($lesson['module_id'] ?? null) == $module['id'] ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($module['title']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div>
                                    <label for="topicId" class="block text-sm font-medium text-gray-700 mb-2">Topic</label>
                                    <select class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" id="topicId" name="topic_id">
                                        <option value="">No topic</option>
                                        <?php foreach ($topics as $topic): ?>
                                            <option value="<?php echo $topic['id']; ?>" <?php echo ($lesson['topic_id'] ?? $topicId) == $topic['id'] ? 'selected' : ''; ?> data-module="<?php echo $topic['module_id']; ?>">
                                                <?php echo htmlspecialchars($topic['module_title'] . ' > ' . $topic['title']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div>
                                    <label for="sortOrder" class="block text-sm font-medium text-gray-700 mb-2">Sort Order</label>
                                    <input type="number" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" id="sortOrder" name="sort_order" value="<?php echo $lesson['sort_order'] ?? 1; ?>" min="1">
                                </div>
                            </div>

                            <div class="mt-6">
                                <label for="estimatedTime" class="block text-sm font-medium text-gray-700 mb-2">Estimated Time (min)</label>
                                <input type="number" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" id="estimatedTime" name="estimated_time" value="<?php echo $lesson['estimated_time'] ?? 30; ?>" min="1">
                            </div>

                            <div class="mt-6">
                                <label class="block text-sm font-medium text-gray-700 mb-2">Learning Objectives</label>
                                <div id="objectivesContainer" class="space-y-2">
                                    <?php
                                    $objectives = json_decode($lesson['learning_objectives'] ?? '[]', true);
                                    if (empty($objectives)) $objectives = [''];
                                    foreach ($objectives as $objective):
                                    ?>
                                        <div class="flex">
                                            <input type="text" class="flex-1 px-3 py-2 border border-gray-300 rounded-l-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" name="learning_objectives[]" value="<?php echo htmlspecialchars($objective); ?>" placeholder="Enter learning objective">
                                            <button type="button" class="px-3 py-2 bg-red-500 text-white rounded-r-lg hover:bg-red-600" onclick="removeObjective(this)">
                                                <i class="fas fa-times"></i>
                                            </button>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                                <button type="button" class="mt-2 px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition duration-150" onclick="addObjective()">
                                    <i class="fas fa-plus mr-2"></i>Add Objective
                                </button>
                            </div>

                            <div class="mt-6">
                                <label class="flex items-center">
                                    <input type="checkbox" class="mr-2" id="isPreview" name="is_preview" <?php echo ($lesson['is_preview'] ?? 0) ? 'checked' : ''; ?>>
                                    <span class="text-sm text-gray-700">Allow preview (visible to non-enrolled students)</span>
                                </label>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Sidebar -->
            <div class="lg:col-span-1 space-y-6">
                <div class="bg-white rounded-xl shadow-lg p-6">
                    <h3 class="text-lg font-semibold text-gray-800 mb-4">Lesson Status</h3>
                    <div class="space-y-3">
                        <button class="w-full px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition duration-150" onclick="publishLesson()">
                            <i class="fas fa-globe mr-2"></i>Publish
                        </button>
                        <button class="w-full px-4 py-2 bg-yellow-500 text-white rounded-lg hover:bg-yellow-600 transition duration-150" onclick="unpublishLesson()">
                            <i class="fas fa-eye-slash mr-2"></i>Unpublish
                        </button>
                        <button class="w-full px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition duration-150" onclick="previewLesson()">
                            <i class="fas fa-eye mr-2"></i>Preview
                        </button>
                    </div>
                </div>

                <div class="bg-white rounded-xl shadow-lg p-6">
                    <h3 class="text-lg font-semibold text-gray-800 mb-4">Course Structure</h3>
                    <div id="courseStructure">
                        <!-- Course structure will be loaded here -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Resource Modal -->
<div id="resourceModal" class="fixed inset-0 bg-gray-900 bg-opacity-50 hidden items-center justify-center z-50">
    <div class="bg-white rounded-lg shadow-2xl max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
        <div class="flex justify-between items-center p-6 border-b border-gray-200">
            <h3 class="text-xl font-bold text-gray-800">Add Resource</h3>
            <button onclick="closeResourceModal()" class="text-gray-400 hover:text-gray-600">
                <i class="fas fa-times text-xl"></i>
            </button>
        </div>
        <div class="p-6">
            <div class="mb-4">
                <label for="resourceSelect" class="block text-sm font-medium text-gray-700 mb-2">Select Resource</label>
                <select class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" id="resourceSelect">
                    <option value="">Choose a resource...</option>
                    <?php foreach ($resources as $resource): ?>
                        <option value="<?php echo $resource['id']; ?>" data-type="<?php echo $resource['resource_type']; ?>" data-url="<?php echo htmlspecialchars($resource['file_path'] ?? $resource['external_url']); ?>">
                            <?php echo htmlspecialchars($resource['title']); ?> (<?php echo ucfirst($resource['resource_type']); ?>)
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="mb-4">
                <label for="resourceDisplayText" class="block text-sm font-medium text-gray-700 mb-2">Display Text</label>
                <input type="text" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" id="resourceDisplayText" placeholder="Text to display for the link">
            </div>
        </div>
        <div class="flex justify-end space-x-3 p-6 border-t border-gray-200">
            <button onclick="closeResourceModal()" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition duration-150">Cancel</button>
            <button onclick="insertSelectedResource()" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition duration-150">Insert Resource</button>
        </div>
    </div>
</div>

<!-- Version Modal -->
<div id="versionModal" class="fixed inset-0 bg-gray-900 bg-opacity-50 hidden items-center justify-center z-50">
    <div class="bg-white rounded-lg shadow-2xl max-w-lg w-full mx-4">
        <div class="flex justify-between items-center p-6 border-b border-gray-200">
            <h3 class="text-xl font-bold text-gray-800">Save Version</h3>
            <button onclick="closeVersionModal()" class="text-gray-400 hover:text-gray-600">
                <i class="fas fa-times text-xl"></i>
            </button>
        </div>
        <form method="POST">
            <div class="p-6">
                <input type="hidden" name="action" value="save_version">
                <div class="mb-4">
                    <label for="versionTitle" class="block text-sm font-medium text-gray-700 mb-2">Version Title *</label>
                    <input type="text" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" id="versionTitle" name="version_title" required>
                </div>
                <div class="mb-4">
                    <label for="versionDescription" class="block text-sm font-medium text-gray-700 mb-2">Description</label>
                    <textarea class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" id="versionDescription" name="version_description" rows="2"></textarea>
                </div>
                <div class="mb-4">
                    <label for="changesDescription" class="block text-sm font-medium text-gray-700 mb-2">Changes Made</label>
                    <textarea class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" id="changesDescription" name="changes_description" rows="3" placeholder="Describe what changes were made in this version"></textarea>
                </div>
                <div class="mb-4">
                    <label class="flex items-center">
                        <input type="checkbox" class="mr-2" id="isPublished" name="is_published">
                        <span class="text-sm text-gray-700">Publish this version</span>
                    </label>
                </div>
            </div>
            <div class="flex justify-end space-x-3 p-6 border-t border-gray-200">
                <button type="button" onclick="closeVersionModal()" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition duration-150">Cancel</button>
                <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition duration-150">Save Version</button>
            </div>
        </form>
    </div>
</div>

<script>
// Tab switching
function switchTab(tabName) {
    // Hide all tabs
    const tabs = document.querySelectorAll('.tab-content');
    tabs.forEach(tab => tab.classList.remove('active'));

    // Remove active class from all buttons
    const buttons = document.querySelectorAll('.tab-button');
    buttons.forEach(button => button.classList.remove('active'));

    // Show selected tab
    document.getElementById(tabName + '-tab').classList.add('active');

    // Add active class to clicked button
    event.target.classList.add('active');
}

// Editor functions
function formatText(command) {
    document.execCommand(command, false, null);
    document.getElementById('lessonContent').focus();
}

function formatBlock(tag) {
    document.execCommand('formatBlock', false, tag);
    document.getElementById('lessonContent').focus();
}

function insertLink() {
    const url = prompt('Enter URL:');
    if (url) {
        document.execCommand('createLink', false, url);
    }
    document.getElementById('lessonContent').focus();
}

function insertImage() {
    const url = prompt('Enter image URL:');
    if (url) {
        document.execCommand('insertImage', false, url);
    }
    document.getElementById('lessonContent').focus();
}

function insertVideo() {
    const url = prompt('Enter video URL:');
    if (url) {
        const videoHtml = `<div class="video-container"><iframe src="${url}" allowfullscreen></iframe></div>`;
        document.execCommand('insertHTML', false, videoHtml);
    }
    document.getElementById('lessonContent').focus();
}

function insertResource() {
    openResourceModal();
}

function openResourceModal() {
    document.getElementById('resourceModal').classList.remove('hidden');
    document.getElementById('resourceModal').classList.add('flex');
}

function closeResourceModal() {
    document.getElementById('resourceModal').classList.add('hidden');
    document.getElementById('resourceModal').classList.remove('flex');
}

function insertSelectedResource() {
    const select = document.getElementById('resourceSelect');
    const displayText = document.getElementById('resourceDisplayText').value || select.options[select.selectedIndex].text;

    if (select.value) {
        const option = select.options[select.selectedIndex];
        const resourceType = option.getAttribute('data-type');
        const url = option.getAttribute('data-url');

        let html = '';
        if (resourceType === 'link') {
            html = `<a href="${url}" target="_blank">${displayText}</a>`;
        } else {
            html = `<a href="../${url}" target="_blank">${displayText}</a>`;
        }

        document.execCommand('insertHTML', false, html);
        closeResourceModal();
    }
    document.getElementById('lessonContent').focus();
}

// Lesson management
function saveLesson() {
    // Get form values
    const title = document.getElementById('lessonTitle').value.trim();
    const contentDiv = document.getElementById('lessonContent');
    const content = contentDiv.innerHTML.trim();

    // Validate title
    if (!title) {
        showAlert('Please enter a lesson title.', 'error');
        document.getElementById('lessonTitle').focus();
        document.getElementById('lessonTitle').classList.add('border-red-500');
        return false;
    }

    // Validate content
    if (!content || content === '<br>' || content === '<br/>') {
        showAlert('Please enter lesson content.', 'error');
        contentDiv.focus();
        contentDiv.classList.add('border-red-500');
        return false;
    }

    // Remove error classes if validation passes
    document.getElementById('lessonTitle').classList.remove('border-red-500');
    contentDiv.classList.remove('border-red-500');

    // Update hidden content input
    document.getElementById('contentInput').value = content;
    document.getElementById('lessonForm').submit();
}

// Alert function
function showAlert(message, type) {
    const alertDiv = document.createElement('div');
    const bgColor = type === 'error' ? 'bg-red-100' : 'bg-green-100';
    const borderColor = type === 'error' ? 'border-red-400' : 'border-green-400';
    const textColor = type === 'error' ? 'text-red-700' : 'text-green-700';
    
    alertDiv.className = `${bgColor} border ${borderColor} ${textColor} px-4 py-3 rounded mb-6`;
    alertDiv.setAttribute('role', 'alert');
    alertDiv.textContent = message;
    
    const container = document.querySelector('.admin-content');
    const firstAlert = container.querySelector('[role="alert"]');
    
    if (firstAlert) {
        firstAlert.parentNode.insertBefore(alertDiv, firstAlert);
    } else {
        container.insertBefore(alertDiv, container.firstChild);
    }
    
    // Auto remove after 5 seconds
    setTimeout(() => alertDiv.remove(), 5000);
}

function previewLesson() {
    // Update hidden content input
    document.getElementById('contentInput').value = document.getElementById('lessonContent').innerHTML;

    const form = document.getElementById('lessonForm');
    const originalAction = form.getAttribute('action');
    const originalTarget = form.getAttribute('target');

    form.setAttribute('action', 'lesson_preview.php');
    form.setAttribute('target', '_blank');
    form.setAttribute('method', 'POST');

    // Temporarily change action to preview
    const actionInput = form.querySelector('input[name="action"]');
    actionInput.value = 'preview_lesson';

    form.submit();

    // Restore original form attributes
    form.setAttribute('action', originalAction);
    form.setAttribute('target', originalTarget);
    actionInput.value = 'save_lesson';
}

function publishLesson() {
    if (confirm('Are you sure you want to publish this lesson?')) {
        // Implementation for publishing
        alert('Publish functionality will be implemented.');
    }
}

function unpublishLesson() {
    if (confirm('Are you sure you want to unpublish this lesson?')) {
        // Implementation for unpublishing
        alert('Unpublish functionality will be implemented.');
    }
}

function saveVersion() {
    document.getElementById('versionModal').classList.remove('hidden');
    document.getElementById('versionModal').classList.add('flex');
}

function closeVersionModal() {
    document.getElementById('versionModal').classList.add('hidden');
    document.getElementById('versionModal').classList.remove('flex');
}

function restoreVersion(versionId) {
    if (confirm('Are you sure you want to restore this version? Current changes will be lost.')) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = `
            <input type="hidden" name="action" value="restore_version">
            <input type="hidden" name="version_id" value="${versionId}">
        `;
        document.body.appendChild(form);
        form.submit();
    }
}

// Objectives management
function addObjective() {
    const container = document.getElementById('objectivesContainer');
    const div = document.createElement('div');
    div.className = 'flex';
    div.innerHTML = `
        <input type="text" class="flex-1 px-3 py-2 border border-gray-300 rounded-l-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" name="learning_objectives[]" placeholder="Enter learning objective">
        <button type="button" class="px-3 py-2 bg-red-500 text-white rounded-r-lg hover:bg-red-600" onclick="removeObjective(this)">
            <i class="fas fa-times"></i>
        </button>
    `;
    container.appendChild(div);
}

function removeObjective(button) {
    button.closest('.flex').remove();
}

// Lesson type handling
document.getElementById('lessonType').addEventListener('change', function() {
    const videoSection = document.getElementById('videoSection');
    const resourceSection = document.getElementById('resourceSection');

    if (this.value === 'video') {
        videoSection.classList.remove('hidden');
        resourceSection.classList.add('hidden');
    } else if (this.value === 'resource') {
        resourceSection.classList.remove('hidden');
        videoSection.classList.add('hidden');
    } else {
        videoSection.classList.add('hidden');
        resourceSection.classList.add('hidden');
    }
});

// Mobile Menu Functionality
const mobileMenuButton = document.getElementById('mobileMenuButton');
const closeMobileMenu = document.getElementById('closeMobileMenu');
const mobileMenu = document.getElementById('mobileMenu');

if (mobileMenuButton && closeMobileMenu && mobileMenu) {
    mobileMenuButton.addEventListener('click', () => {
        mobileMenu.classList.remove('-translate-x-full');
    });

    closeMobileMenu.addEventListener('click', () => {
        mobileMenu.classList.add('-translate-x-full');
    });

    // Close menu when a link is clicked
    mobileMenu.querySelectorAll('a').forEach(link => {
        link.addEventListener('click', () => {
            mobileMenu.classList.add('-translate-x-full');
        });
    });
}

// Initialize lesson type display
document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('lessonType').dispatchEvent(new Event('change'));
});

// Video source switching
function switchVideoSource(source) {
    const urlSection = document.getElementById('videoUrlSection');
    const uploadSection = document.getElementById('videoUploadSection');
    const btnUrl = document.getElementById('btnVideoUrl');
    const btnUpload = document.getElementById('btnVideoUpload');
    
    if (source === 'url') {
        urlSection.classList.remove('hidden');
        uploadSection.classList.add('hidden');
        btnUrl.classList.remove('bg-white');
        btnUrl.classList.add('bg-gray-200');
        btnUpload.classList.remove('bg-gray-200');
        btnUpload.classList.add('bg-white');
    } else {
        urlSection.classList.add('hidden');
        uploadSection.classList.remove('hidden');
        btnUrl.classList.remove('bg-gray-200');
        btnUrl.classList.add('bg-white');
        btnUpload.classList.remove('bg-white');
        btnUpload.classList.add('bg-gray-200');
    }
}

// Handle video file selection
function handleVideoSelect(input) {
    if (input.files && input.files[0]) {
        const file = input.files[0];
        const maxSize = 500 * 1024 * 1024; // 500MB
        
        if (file.size > maxSize) {
            alert('File is too large. Maximum size is 500MB.');
            input.value = '';
            return;
        }
        
        const validTypes = ['video/mp4', 'video/webm', 'video/ogg', 'video/quicktime', 'video/x-msvideo', 'video/x-ms-wmv'];
        const extension = file.name.split('.').pop().toLowerCase();
        const allowedExtensions = ['mp4', 'webm', 'ogg', 'mov', 'avi', 'wmv'];
        
        if (!allowedExtensions.includes(extension)) {
            alert('Invalid file type. Allowed: ' + allowedExtensions.join(', '));
            input.value = '';
            return;
        }
        
        // Show preview and upload
        const videoPreview = document.getElementById('videoPreview');
        const progressDiv = document.getElementById('videoUploadProgress');
        const player = document.getElementById('uploadedVideoPlayer');
        
        const reader = new FileReader();
        reader.onload = function(e) {
            player.src = e.target.result;
            videoPreview.classList.remove('hidden');
        };
        reader.readAsDataURL(file);
        
        // Upload via AJAX
        uploadVideoFile(file);
    }
}

// Upload video file via AJAX
function uploadVideoFile(file) {
    const progressDiv = document.getElementById('videoUploadProgress');
    const progressBar = document.getElementById('videoProgressBar');
    const statusText = document.getElementById('videoUploadStatus');
    const videoPreview = document.getElementById('videoPreview');
    const videoPathInput = document.getElementById('uploadedVideoPath');
    
    progressDiv.classList.remove('hidden');
    videoPreview.classList.add('hidden');
    progressBar.style.width = '0%';
    statusText.textContent = 'Uploading...';
    
    const formData = new FormData();
    formData.append('action', 'upload_video');
    formData.append('course_id', '<?php echo $courseId; ?>');
    formData.append('video_file', file);
    
    const xhr = new XMLHttpRequest();
    
    xhr.upload.addEventListener('progress', function(e) {
        if (e.lengthComputable) {
            const percent = Math.round((e.loaded / e.total) * 100);
            progressBar.style.width = percent + '%';
            statusText.textContent = 'Uploading... ' + percent + '%';
        }
    });
    
    xhr.addEventListener('load', function() {
        progressDiv.classList.add('hidden');
        console.log('XHR Response:', xhr.responseText);
        
        if (xhr.status !== 200) {
            alert('Upload failed. Server returned status: ' + xhr.status);
            return;
        }
        
        try {
            const response = JSON.parse(xhr.responseText);
            
            if (response.success) {
                videoPathInput.value = response.video_path;
                statusText.textContent = 'Upload complete!';
                videoPreview.classList.remove('hidden');
            } else {
                alert('Upload failed: ' + (response.message || 'Unknown error'));
            }
        } catch (e) {
            alert('Upload failed. Please try again. Response: ' + xhr.responseText.substring(0, 200));
        }
    });
    
    xhr.addEventListener('error', function() {
        progressDiv.classList.add('hidden');
        alert('Upload failed. Please try again. Check console for details.');
    });
    
    xhr.open('POST', 'video_upload.php');
    xhr.send(formData);
}

// Remove uploaded video
function removeUploadedVideo() {
    const videoPreview = document.getElementById('videoPreview');
    const videoFile = document.getElementById('videoFile');
    const videoPathInput = document.getElementById('uploadedVideoPath');
    const player = document.getElementById('uploadedVideoPlayer');
    
    videoPreview.classList.add('hidden');
    videoFile.value = '';
    videoPathInput.value = '';
    player.src = '';
}
</script>

</main>
</div>

</body>
</html>