<?php
require_once '../../config/database.php';
require_once '../../config/auth.php';
require_once '../../config/rbac.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;

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: edit.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 for organization
$stmt = $db->prepare("SELECT t.*, m.title as module_title FROM course_topics t JOIN course_modules m ON t.module_id = m.id WHERE m.course_id = ? AND m.is_active = 1 ORDER BY m.sort_order, t.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();

// Get lesson resources if editing existing lesson
$lessonResources = [];
if ($lessonId) {
    $stmt = $db->prepare("SELECT resource_id FROM lesson_resources WHERE lesson_id = ?");
    $stmt->execute([$lessonId]);
    $lessonResources = array_column($stmt->fetchAll(), 'resource_id');
}

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

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

                // Validate required fields
                if (empty($title)) {
                    $error = 'Lesson title is required.';
                } else {
                    try {
                        $db->beginTransaction();

                        // Sanitize and validate media URLs
                        if ($videoUrl && !filter_var($videoUrl, FILTER_VALIDATE_URL)) {
                            $videoUrl = null;
                        }
                        if ($attachmentUrl && !filter_var($attachmentUrl, FILTER_VALIDATE_URL)) {
                            $attachmentUrl = null;
                        }

                        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 = ? AND course_id = ?
                            ");
                            $stmt->execute([
                                $title, $description, $moduleId, $topicId, $content, $lessonType, $videoUrl,
                                $attachmentUrl, $attachmentName, $sortOrder, $isPreview, $estimatedTime,
                                json_encode($learningObjectives), json_encode($prerequisites), $lessonId, $courseId
                            ]);

                            $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.';
                        }

                        // Handle resource associations if the lesson_resources table exists
                        if ($lessonId && isset($_POST['resources'])) {
                            // Clear existing resource associations
                            $stmt = $db->prepare("DELETE FROM lesson_resources WHERE lesson_id = ?");
                            $stmt->execute([$lessonId]);

                            // Add new resource associations
                            $resourceIds = array_filter(array_map('intval', $_POST['resources'] ?? []));
                            if (!empty($resourceIds)) {
                                $stmt = $db->prepare("INSERT INTO lesson_resources (lesson_id, resource_id, created_at) VALUES (?, ?, NOW())");
                                foreach ($resourceIds as $resourceId) {
                                    $stmt->execute([$lessonId, $resourceId]);
                                }
                            }
                        }

                        $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();
                        error_log('Lesson save error: ' . $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']) ? 1 : 0;

                if (empty($versionTitle)) {
                    $error = 'Version title is required.';
                } elseif (!$lessonId) {
                    $error = 'Cannot save version for unsaved lesson.';
                } else {
                    try {
                        $db->beginTransaction();

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

                        // Save the current lesson state as a new version
                        $stmt = $db->prepare("
                            INSERT INTO lesson_versions 
                            (lesson_id, version_number, title, description, content, video_url, attachment_url, 
                             attachment_name, lesson_type, 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'], 
                            $lesson['lesson_type'],
                            $changesDescription, 
                            $isPublished, 
                            $userId
                        ]);

                        // Update lesson's updated_at timestamp
                        $stmt = $db->prepare("UPDATE course_lessons SET updated_at = NOW() WHERE id = ?");
                        $stmt->execute([$lessonId]);

                        $db->commit();

                        $message = 'Version ' . $nextVersion . ' 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) {
                        $db->rollBack();
                        $error = 'Error saving version: ' . $e->getMessage();
                        error_log('Version save error: ' . $e->getMessage());
                    }
                }
                break;

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

                try {
                    $db->beginTransaction();

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

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

                        $db->commit();

                        $message = 'Version ' . $version['version_number'] . ' 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) {
                    $db->rollBack();
                    $error = 'Error restoring version: ' . $e->getMessage();
                    error_log('Version restore error: ' . $e->getMessage());
                }
                break;

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

$pageTitle = ($lessonId ? 'Edit' : 'Create') . ' Lesson: ' . htmlspecialchars($course['title']);
$page_title = $pageTitle;
$active_link = 'courses';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Content-Security-Policy" content="frame-src https://www.youtube.com https://youtube.com https://vimeo.com https://player.vimeo.com;">
    <title><?php echo htmlspecialchars($pageTitle); ?></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">
    <!-- 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>
    <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">Instructor Panel</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">
?>

        <!-- 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="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; ?>">

                            <!-- Common Fields (Always Visible) -->
                            <div class="mb-6 pb-6 border-b border-gray-200">
                                <div class="mb-4">
                                    <label for="lessonTitle" class="block text-sm font-medium text-gray-700 mb-2">Lesson 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="lessonTitle" name="title" value="<?php echo htmlspecialchars($lesson['title'] ?? ''); ?>" required>
                                </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="grid grid-cols-1 md:grid-cols-3 gap-4">
                                    <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" required>
                                            <?php foreach ($topics as $topic): ?>
                                                <option value="<?php echo $topic['id']; ?>" <?php echo ($lesson['topic_id'] ?? null) == $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-4">
                                    <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>
                            </div>

                            <!-- Tabbed Content -->
                            <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>

                            <!-- Content Tab -->
                            <div id="content-tab" class="tab-content active p-6">

                                <div class="mb-4">
                                    <label for="lessonContent" class="block text-sm font-medium text-gray-700 mb-2">Content *</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" contenteditable="true"><?php echo $lesson['content'] ?? ''; ?></div>
                                    <input type="hidden" name="content" id="contentInput">
                                </div>

                                <div class="mt-6 flex justify-end">
                                    <button type="submit" class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition duration-150">
                                        <i class="fas fa-save mr-2"></i><?php echo $lessonId ? 'Update' : 'Save'; ?> Lesson
                                    </button>
                                </div>
                            </div>

                            <!-- Media Tab -->
                            <div id="media-tab" class="tab-content p-6">
                                <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 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 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 class="mt-6 flex justify-end">
                                    <button type="submit" class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition duration-150">
                                        <i class="fas fa-save mr-2"></i><?php echo $lessonId ? 'Update' : 'Save'; ?> Lesson
                                    </button>
                                </div>
                            </div>

                            <!-- Resources Tab -->
                            <div id="resources-tab" class="tab-content p-6">
                                <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 class="mb-4">
                                    <h4 class="text-md font-semibold text-gray-800 mb-2">Associate Resources with Lesson</h4>
                                    <p class="text-sm text-gray-600 mb-4">Select resources to associate with this lesson. These will be saved separately from content-embedded resources.</p>
                                    <div class="resource-list space-y-2">
                                        <?php foreach ($resources as $resource): ?>
                                            <label class="flex items-center space-x-3 p-3 bg-gray-50 rounded-lg hover:bg-gray-100">
                                                <input type="checkbox" name="resources[]" value="<?php echo $resource['id']; ?>" <?php echo in_array($resource['id'], $lessonResources) ? 'checked' : ''; ?> class="form-checkbox h-5 w-5 text-blue-600">
                                                <div class="flex-1">
                                                    <div class="font-medium text-gray-900"><?php echo htmlspecialchars($resource['title']); ?></div>
                                                    <div class="text-sm text-gray-500"><?php echo ucfirst($resource['resource_type']); ?></div>
                                                </div>
                                            </label>
                                        <?php endforeach; ?>
                                    </div>
                                </div>

                                <div class="mt-6 flex justify-end">
                                    <button type="submit" class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition duration-150">
                                        <i class="fas fa-save mr-2"></i><?php echo $lessonId ? 'Update' : 'Save'; ?> Lesson
                                    </button>
                                </div>
                            </div>

                            <!-- Versions Tab -->
                            <div id="versions-tab" class="tab-content p-6">
                                <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>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Sidebar -->
            <div class="lg:col-span-1 space-y-6">
            </div>
        </div>
    </main>
</div>

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

<!-- 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>
    // --- UI/Utility Functions ---

    // --- UI/Utility Functions ---

    // Function to show a dismissible toast notification
    function showToast(message, type = 'success') {
        const container = document.getElementById('toast-container');
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`; // Note: 'show' added below
        toast.innerHTML = `<i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-triangle'} mr-2"></i>${message}`;
        container.appendChild(toast);

        // Force repaint to start transition
        setTimeout(() => toast.classList.add('show'), 10);

        // Auto-dismiss after 4 seconds
        setTimeout(() => {
            toast.classList.remove('show');
            // Remove from DOM after transition finishes
            setTimeout(() => toast.remove(), 300);
        }, 4000);
    }

    // Function to handle the custom confirmation modal (replacing window.confirm)
    function showConfirmationModal(action, reviewId) {
        const modal = document.getElementById('confirmation-modal');
        const title = document.getElementById('modal-title');
        const message = document.getElementById('modal-message');
        const confirmButton = document.getElementById('modal-confirm');
        const cancelButton = document.getElementById('modal-cancel');

        const isApprove = action === 'approve';
        const actionText = isApprove ? 'Approve' : 'Reject';

        // Placeholder function to simulate the PHP action
        const performAction = () => {
            // In a real application, this would be an AJAX call:
            // fetch('api/review_action.php', { method: 'POST', body: JSON.stringify({ action: action, review_id: reviewId }) })
            // .then(response => response.json()).then(data => { ... })
            fetch('../../api/reviews.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: action,
                    review_id: reviewId
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast(`Review ${actionText.toLowerCase()}d successfully.`, 'success');
                    modal.classList.add('hidden');
                    modal.classList.remove('flex');
                    // Reload or remove the review item from the UI
                    location.reload();
                } else {
                    showToast('Error: ' + data.error, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('An error occurred. Please try again.', 'error');
            });
        };

        // Set modal content
        title.textContent = `Confirm ${actionText}`;
        message.textContent = `Are you sure you want to ${actionText.toLowerCase()} this review? This action cannot be undone. (Review ID: ${reviewId})`;
        confirmButton.textContent = actionText;
        confirmButton.className = `px-4 py-2 text-white rounded-md transition ${isApprove ? 'bg-green-500 hover:bg-green-600' : 'bg-red-500 hover:bg-red-600'}`;

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

        // Set listeners
        confirmButton.onclick = performAction;
        cancelButton.onclick = () => {
            modal.classList.add('hidden');
            modal.classList.remove('flex');
        };

        // Allow clicking the overlay to close
        document.getElementById('sidebar-overlay').onclick = () => {
            modal.classList.add('hidden');
            modal.classList.remove('flex');
        };
    }

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

    // 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');
            const resourceId = select.value;

            let html = '';
            if (resourceType === 'link' || resourceType === 'external') {
                html = `<a href="${url}" target="_blank" class="resource-link" data-resource-id="${resourceId}">${displayText}</a>`;
            } else if (resourceType === 'file') {
                html = `<a href="../../${url}" target="_blank" class="resource-link" data-resource-id="${resourceId}">${displayText}</a>`;
            } else if (resourceType === 'video') {
                html = `<iframe src="${url}" width="560" height="315" allowfullscreen class="resource-video" data-resource-id="${resourceId}"></iframe>`;
            } else if (resourceType === 'image') {
                html = `<img src="${url}" alt="${displayText}" class="resource-image max-w-md" data-resource-id="${resourceId}">`;
            } else {
                html = `<a href="${url}" target="_blank" class="resource-link" data-resource-id="${resourceId}">${displayText}</a>`;
            }

            document.execCommand('insertHTML', false, html);
            
            // Clear modal inputs
            document.getElementById('resourceDisplayText').value = '';
            select.value = '';
            
            closeResourceModal();
            document.getElementById('lessonContent').focus();
        } else {
            alert('Please select a resource.');
        }
    }

    // Lesson management
    function saveLesson() {
        // Validate required fields
        const title = document.getElementById('lessonTitle').value.trim();
        const content = document.getElementById('lessonContent').innerText.trim();
        
        if (!title) {
            alert('Please enter a lesson title.');
            document.getElementById('lessonTitle').focus();
            return;
        }

        // Update hidden content input with editor content
        document.getElementById('contentInput').value = document.getElementById('lessonContent').innerHTML;

        // Collect selected resources
        const resourceInputs = document.querySelectorAll('input[name="resources[]"]:checked');
        const resourceData = Array.from(resourceInputs).map(input => input.value);
        
        // Create hidden resource inputs if there are any
        const form = document.getElementById('lessonForm');
        const existingResourceInputs = form.querySelectorAll('input[name="resources[]"]');
        existingResourceInputs.forEach(input => input.remove());
        
        resourceData.forEach(resourceId => {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'resources[]';
            input.value = resourceId;
            form.appendChild(input);
        });

        // Ensure action is set to save_lesson
        document.querySelector('input[name="action"]').value = 'save_lesson';
        
        // Submit the form
        form.submit();
    }

    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() {
        // Validate that lesson is saved first
        const lessonId = new URLSearchParams(window.location.search).get('lesson_id');
        
        if (!lessonId) {
            alert('Please save the lesson first before creating a version.');
            return;
        }

        // Update content input before opening modal
        document.getElementById('contentInput').value = document.getElementById('lessonContent').innerHTML;

        // Clear and show version modal
        document.getElementById('versionTitle').value = '';
        document.getElementById('versionDescription').value = '';
        document.getElementById('changesDescription').value = '';
        document.getElementById('isPublished').checked = false;

        document.getElementById('versionModal').classList.remove('hidden');
        document.getElementById('versionModal').classList.add('flex');

        // Focus on title input
        setTimeout(() => {
            document.getElementById('versionTitle').focus();
        }, 100);
    }

    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 resourceSection = document.getElementById('resourceSection');

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

    // Module and topic handling
    document.getElementById('moduleId').addEventListener('change', function() {
        const selectedModuleId = this.value;
        const topicSelect = document.getElementById('topicId');
        const topicOptions = topicSelect.querySelectorAll('option');

        // Clear current selection
        topicSelect.value = '';

        // Show/hide topic options based on selected module
        topicOptions.forEach(option => {
            if (option.value === '') {
                // Always show "No topic" option
                option.style.display = 'block';
            } else {
                const optionModuleId = option.getAttribute('data-module');
                if (optionModuleId === selectedModuleId) {
                    option.style.display = 'block';
                } else {
                    option.style.display = 'none';
                }
            }
        });
    });

    // Unsaved Changes Warning System
    let hasUnsavedChanges = false;

    // Function to mark form as dirty when inputs change
    function setupUnsavedChangesTracking() {
        const form = document.getElementById('lessonForm');
        const inputs = form.querySelectorAll('input, textarea, select');

        inputs.forEach(input => {
            input.addEventListener('change', () => {
                hasUnsavedChanges = true;
            });
            input.addEventListener('keydown', () => {
                hasUnsavedChanges = true;
            });
        });

        // Clear flag after successful submission
        form.addEventListener('submit', () => {
            hasUnsavedChanges = false;
        });
    }

    // Warn user before leaving page with unsaved changes
    window.addEventListener('beforeunload', (e) => {
        if (hasUnsavedChanges) {
            e.preventDefault();
            e.returnValue = 'You have unsaved changes. Are you sure you want to leave?';
            return 'You have unsaved changes. Are you sure you want to leave?';
        }
    });

    // Initialize lesson type display and module/topic selection
    document.addEventListener('DOMContentLoaded', function() {
        document.getElementById('lessonType').dispatchEvent(new Event('change'));
        document.getElementById('moduleId').dispatchEvent(new Event('change'));
        setupUnsavedChangesTracking();

        // Update hidden content input on form submit
        document.getElementById('lessonForm').addEventListener('submit', function() {
            document.getElementById('contentInput').value = document.getElementById('lessonContent').innerHTML;
        });
    });
</script>

</body>
</html>