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

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']) ? $_POST['module_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 = ?, 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, $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, 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, $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;
        }
    }
}

$pageTitle = ($lessonId ? 'Edit' : 'Create') . ' Lesson: ' . htmlspecialchars($course['title']);
?>
<!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">
    <style>
        /* Custom Tailwind Configuration and Base Styles */
        :root {
            --primary: #007bff; /* Blue */
            --secondary: #6c757d; /* Gray */
            --success: #28a745; /* Green */
            --danger: #dc3545; /* Red */
            --info: #17a2b8; /* Cyan */
        }
        .text-primary { color: var(--primary); }
        .bg-primary { background-color: var(--primary); }
        .bg-success { background-color: var(--success); }
        .bg-secondary { background-color: var(--secondary); }

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

        /* Custom Styles for Dashboard Layout */
        .admin-sidebar {
            transition: transform 0.3s ease-in-out;
            min-width: 250px;
        }
        @media (max-width: 1024px) {
            .admin-sidebar {
                position: fixed;
                top: 0;
                left: 0;
                transform: translateX(-100%);
                z-index: 50;
                height: 100%;
            }
            .admin-container.sidebar-open .admin-sidebar {
                transform: translateX(0);
            }
            .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: var(--success); }
        .toast-error { background-color: var(--danger); }

        /* 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="antialiased">

<!-- 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="admin-container flex min-h-screen">
    <!-- Sidebar -->
    <div id="admin-sidebar" class="admin-sidebar bg-gray-800 text-white shadow-xl lg:sticky lg:top-0 h-screen overflow-y-auto">
        <div class="p-6 border-b border-gray-700">
            <h2 class="text-2xl font-extrabold text-blue-400">Mutalex Academy</h2>
            <p class="text-sm font-light text-gray-400 mt-1">Instructor Panel</p>
        </div>

        <nav class="p-4">
            <ul class="space-y-2">
                <li><a href="../dashboard.php" class="flex items-center p-3 rounded-lg text-gray-300 hover:bg-gray-700 transition duration-150"><i class="fas fa-chart-line w-5 h-5 mr-3"></i>Dashboard</a></li>
                <li><a href="index.php" class="flex items-center p-3 rounded-lg bg-gray-700 text-blue-300 font-semibold hover:bg-gray-700 transition duration-150"><i class="fas fa-graduation-cap w-5 h-5 mr-3"></i>My Courses</a></li>
                <li><a href="new.php" class="flex items-center p-3 rounded-lg text-gray-300 hover:bg-gray-700 transition duration-150"><i class="fas fa-plus-circle w-5 h-5 mr-3"></i>Create Course</a></li>
                <li><a href="/lms/instructor/questions/index.php" class="flex items-center p-3 rounded-lg text-gray-300 hover:bg-gray-700 transition duration-150"><i class="fas fa-question-circle w-5 h-5 mr-3"></i>Question Bank</a></li>
                <li><a href="/lms/instructor/exams/index.php" class="flex items-center p-3 rounded-lg text-gray-300 hover:bg-gray-700 transition duration-150"><i class="fas fa-clipboard-check w-5 h-5 mr-3"></i>Exams & Quizzes</a></li>
                <li><a href="../resources.php" class="flex items-center p-3 rounded-lg text-gray-300 hover:bg-gray-700 transition duration-150"><i class="fas fa-book-open w-5 h-5 mr-3"></i>Resources</a></li>
                <li><a href="../students.php" class="flex items-center p-3 rounded-lg text-gray-300 hover:bg-gray-700 transition duration-150"><i class="fas fa-users w-5 h-5 mr-3"></i>Students</a></li>
                <li><a href="../assignments.php" class="flex items-center p-3 rounded-lg text-gray-300 hover:bg-gray-700 transition duration-150"><i class="fas fa-file-alt w-5 h-5 mr-3"></i>Assignments</a></li>
                <li><a href="/lms/instructor/grading/index.php" class="flex items-center p-3 rounded-lg text-gray-300 hover:bg-gray-700 transition duration-150"><i class="fas fa-trophy w-5 h-5 mr-3"></i>Grades</a></li>
                <li class="pt-4 border-t border-gray-700 mt-4">
                    <a href="../../logout.php" class="flex items-center p-3 rounded-lg text-red-400 hover:bg-gray-700 transition duration-150">
                        <i class="fas fa-sign-out-alt w-5 h-5 mr-3"></i>Logout
                    </a>
                </li>
            </ul>
        </nav>
    </div>

    <!-- Main Content -->
    <div class="admin-content flex-1 p-4 sm:p-6 lg:p-8">
        <!-- Header (Mobile Menu Button and Page Title) -->
        <div class="admin-header flex justify-between items-center pb-6 border-b border-gray-200 mb-6">
            <div class="flex items-center">
                <!-- Hamburger Menu for Mobile -->
                <button id="sidebar-toggle" class="lg:hidden p-2 mr-4 text-gray-600 hover:text-gray-900 rounded-lg focus:outline-none">
                    <i class="fas fa-bars text-xl"></i>
                </button>
                <div>
                    <h1 class="text-3xl font-bold text-gray-800"><?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>

            <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="edit.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>
?>

        <!-- 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 *</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="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>

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

                            <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() {
    // Update hidden content input
    document.getElementById('contentInput').value = document.getElementById('lessonContent').innerHTML;
    document.getElementById('lessonForm').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() {
    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');
    }
});

// Sidebar Toggle Logic
document.getElementById('sidebar-toggle').addEventListener('click', () => {
    document.querySelector('.admin-container').classList.toggle('sidebar-open');
});

// Close sidebar when clicking the overlay on mobile
document.getElementById('sidebar-overlay').addEventListener('click', () => {
    document.querySelector('.admin-container').classList.remove('sidebar-open');
});

// Ensure sidebar is always visible on large screens
window.addEventListener('resize', () => {
    if (window.innerWidth >= 1024) {
        document.querySelector('.admin-container').classList.remove('sidebar-open');
    }
});

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

</body>
</html>