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

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

$user = getUserContext();
$db = getDB();

$courseId = $_GET['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 categories for dropdown
$stmt = $db->query("SELECT * FROM course_categories WHERE is_active = 1 ORDER BY name");
$categories = $stmt->fetchAll();

// Get course curriculum (modules, topics, lessons)
$stmt = $db->prepare("
    SELECT
        cm.id as module_id, cm.title as module_title, cm.description as module_description, cm.sort_order as module_sort_order,
        ct.id as topic_id, ct.title as topic_title, ct.description as topic_description, ct.sort_order as topic_sort_order,
        cl.id as lesson_id, cl.title as lesson_title, cl.description as lesson_description, cl.content as lesson_content,
        cl.lesson_type, cl.sort_order as lesson_sort_order, cl.is_preview, cl.estimated_time
    FROM course_modules cm
    LEFT JOIN course_topics ct ON cm.id = ct.module_id
    LEFT JOIN course_lessons cl ON ct.id = cl.topic_id
    WHERE cm.course_id = ?
    ORDER BY cm.sort_order ASC, ct.sort_order ASC, cl.sort_order ASC
");
$stmt->execute([$courseId]);
$rawCurriculum = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Organize into hierarchical structure
$curriculum = [];
foreach ($rawCurriculum as $row) {
    $moduleId = $row['module_id'];
    $topicId = $row['topic_id'];
    $lessonId = $row['lesson_id'];

    if (!isset($curriculum[$moduleId])) {
        $curriculum[$moduleId] = [
            'id' => $moduleId,
            'title' => $row['module_title'],
            'description' => $row['module_description'],
            'sort_order' => $row['module_sort_order'],
            'topics' => []
        ];
    }

    if ($topicId && !isset($curriculum[$moduleId]['topics'][$topicId])) {
        $curriculum[$moduleId]['topics'][$topicId] = [
            'id' => $topicId,
            'title' => $row['topic_title'],
            'description' => $row['topic_description'],
            'sort_order' => $row['topic_sort_order'],
            'lessons' => []
        ];
    }

    if ($lessonId) {
        $curriculum[$moduleId]['topics'][$topicId]['lessons'][] = [
            'id' => $lessonId,
            'title' => $row['lesson_title'],
            'description' => $row['lesson_description'],
            'content' => $row['lesson_content'],
            'type' => $row['lesson_type'],
            'sort_order' => $row['lesson_sort_order'],
            'is_preview' => $row['is_preview'],
            'duration' => $row['estimated_time'] . 'm',
            'status' => 'draft',
            'is_free' => false // Default, can be extended
        ];
    }
}

// Convert associative array to indexed array
$curriculum = array_values($curriculum);
foreach ($curriculum as &$module) {
    $module['topics'] = array_values($module['topics']);
}
unset($module);


// Get enrollment stats
$stmt = $db->prepare("SELECT COUNT(*) as total_enrollments, COUNT(CASE WHEN status = 'completed' THEN 1 END) as completed_count FROM course_enrollments WHERE course_id = ?");
$stmt->execute([$courseId]);
$enrollmentStats = $stmt->fetch();

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'update_course':
                $title = trim($_POST['title']);
                $slug = trim($_POST['slug']);
                $description = trim($_POST['description']);
                $shortDescription = trim($_POST['short_description']);
                $categoryId = !empty($_POST['category_id']) ? $_POST['category_id'] : null;
                $level = $_POST['level'];
                $language = trim($_POST['language']);
                $durationHours = intval($_POST['duration_hours']);
                $price = floatval($_POST['price']);
                $currency = trim($_POST['currency']);
                $maxStudents = !empty($_POST['max_students']) ? intval($_POST['max_students']) : null;
                $prerequisites = trim($_POST['prerequisites']);
                $learningObjectives = array_filter(array_map('trim', $_POST['learning_objectives'] ?? []));
                $tags = array_filter(array_map('trim', $_POST['tags'] ?? []));
                $isFree = isset($_POST['is_free']);
                $isFeatured = isset($_POST['is_featured']);
                $status = $_POST['status'];

                if (empty($title) || empty($description)) {
                    $error = 'Title and description are required.';
                } else {
                    try {
                        // Handle file uploads
                        $thumbnail = $course['thumbnail'];
                        $bannerImage = $course['banner_image'];

                        if (isset($_FILES['thumbnail']) && $_FILES['thumbnail']['error'] === UPLOAD_ERR_OK) {
                            $uploadDir = '../../uploads/course-thumbnails/';
                            if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

                            $fileName = time() . '_' . basename($_FILES['thumbnail']['name']);
                            $targetPath = $uploadDir . $fileName;

                            if (move_uploaded_file($_FILES['thumbnail']['tmp_name'], $targetPath)) {
                                $thumbnail = 'uploads/course-thumbnails/' . $fileName;
                            }
                        }

                        if (isset($_FILES['banner_image']) && $_FILES['banner_image']['error'] === UPLOAD_ERR_OK) {
                            $uploadDir = '../../uploads/course-banners/';
                            if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

                            $fileName = time() . '_' . basename($_FILES['banner_image']['name']);
                            $targetPath = $uploadDir . $fileName;

                            if (move_uploaded_file($_FILES['banner_image']['tmp_name'], $targetPath)) {
                                $bannerImage = 'uploads/course-banners/' . $fileName;
                            }
                        }

                        // Update course
                        $stmt = $db->prepare("UPDATE courses SET title = ?, slug = ?, description = ?, short_description = ?, category_id = ?, thumbnail = ?, banner_image = ?, price = ?, currency = ?, level = ?, duration_hours = ?, language = ?, max_students = ?, prerequisites = ?, learning_objectives = ?, tags = ?, status = ?, is_featured = ?, is_free = ?, updated_at = NOW() WHERE id = ?");

                        $stmt->execute([
                            $title, $slug, $description, $shortDescription, $categoryId, $thumbnail, $bannerImage,
                            $price, $currency, $level, $durationHours, $language, $maxStudents, $prerequisites,
                            json_encode($learningObjectives), json_encode($tags), $status, $isFeatured, $isFree, $courseId
                        ]);

                        $message = 'Course updated successfully.';

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

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

            case 'add_lesson':
                $title = trim($_POST['lesson_title']);
                $description = trim($_POST['lesson_description']);
                $content = trim($_POST['lesson_content']);
                $lessonType = $_POST['lesson_type'];
                $topicId = intval($_POST['topic_id'] ?? 0);
                $sortOrder = intval($_POST['sort_order']);
                $isPreview = isset($_POST['is_preview']);
                $estimatedTime = intval($_POST['estimated_time']);

                if (empty($title) || !$topicId) {
                    $error = 'Lesson title and topic are required.';
                } else {
                    try {
                        // Generate unique slug for lesson
                        $baseSlug = createSlug($title);
                        $slug = $courseId . '-' . $baseSlug . '-' . time();
                        $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, topic_id, title, slug, description, content, lesson_type, sort_order, is_preview, estimated_time, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");
                        $stmt->execute([$courseId, $topicId, $title, $slug, $description, $content, $lessonType, $sortOrder, $isPreview, $estimatedTime]);

                        $message = 'Lesson added successfully.';

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

            case 'delete_lesson':
                $lessonId = $_POST['lesson_id'];

                try {
                    $stmt = $db->prepare("DELETE FROM course_lessons WHERE id = ? AND course_id = ?");
                    $stmt->execute([$lessonId, $courseId]);

                    $message = 'Lesson deleted successfully.';

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

            case 'add_module':
                $title = trim($_POST['module_title']);
                $description = trim($_POST['module_description']);
                $sortOrder = intval($_POST['module_sort_order'] ?? 1);

                if (empty($title)) {
                    $error = 'Module title is required.';
                } else {
                    try {
                        $baseSlug = createSlug($title);
                        $slug = $courseId . '-' . $baseSlug . '-' . time();
                        $originalSlug = $slug;
                        $counter = 1;
                        while (true) {
                            $stmt = $db->prepare("SELECT id FROM course_modules WHERE slug = ?");
                            $stmt->execute([$slug]);
                            if (!$stmt->fetch()) break;
                            $slug = $originalSlug . '-' . $counter;
                            $counter++;
                        }

                        $stmt = $db->prepare("INSERT INTO course_modules (course_id, title, slug, description, sort_order, created_at, updated_at) VALUES (?, ?, ?, ?, ?, NOW(), NOW())");
                        $stmt->execute([$courseId, $title, $slug, $description, $sortOrder]);

                        $message = 'Module added successfully.';

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

            case 'add_topic':
                $moduleId = intval($_POST['module_id']);
                $title = trim($_POST['topic_title']);
                $description = trim($_POST['topic_description']);
                $sortOrder = intval($_POST['topic_sort_order'] ?? 1);

                if (empty($title) || !$moduleId) {
                    $error = 'Topic title and module are required.';
                } else {
                    try {
                        // Generate unique slug for topic
                        $baseSlug = createSlug($title);
                        $slug = $moduleId . '-' . $baseSlug . '-' . time();
                        $originalSlug = $slug;
                        $counter = 1;
                        while (true) {
                            $stmt = $db->prepare("SELECT id FROM course_topics WHERE module_id = ? AND slug = ?");
                            $stmt->execute([$moduleId, $slug]);
                            if (!$stmt->fetch()) break;
                            $slug = $originalSlug . '-' . $counter;
                            $counter++;
                        }

                        $stmt = $db->prepare("INSERT INTO course_topics (module_id, title, slug, description, sort_order, created_at, updated_at) VALUES (?, ?, ?, ?, ?, NOW(), NOW())");
                        $stmt->execute([$moduleId, $title, $slug, $description, $sortOrder]);

                        $message = 'Topic added successfully.';

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

            case 'update_module':
                $moduleId = intval($_POST['module_id']);
                $title = trim($_POST['module_title']);
                $description = trim($_POST['module_description']);
                $sortOrder = intval($_POST['module_sort_order'] ?? 1);

                if (empty($title)) {
                    $error = 'Module title is required.';
                } else {
                    try {
                        $stmt = $db->prepare("UPDATE course_modules SET title = ?, description = ?, sort_order = ?, updated_at = NOW() WHERE id = ? AND course_id = ?");
                        $stmt->execute([$title, $description, $sortOrder, $moduleId, $courseId]);

                        $message = 'Module updated successfully.';

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

            case 'delete_module':
                $moduleId = intval($_POST['module_id']);

                try {
                    // Delete all lessons in topics within this module
                    $stmt = $db->prepare("
                        DELETE FROM course_lessons 
                        WHERE topic_id IN (
                            SELECT id FROM course_topics WHERE module_id = ?
                        )
                    ");
                    $stmt->execute([$moduleId]);

                    // Delete all topics in this module
                    $stmt = $db->prepare("DELETE FROM course_topics WHERE module_id = ?");
                    $stmt->execute([$moduleId]);

                    // Delete the module itself
                    $stmt = $db->prepare("DELETE FROM course_modules WHERE id = ? AND course_id = ?");
                    $stmt->execute([$moduleId, $courseId]);

                    $message = 'Module and all its contents deleted successfully.';

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

            case 'update_topic':
                $topicId = intval($_POST['topic_id']);
                $title = trim($_POST['topic_title']);
                $description = trim($_POST['topic_description']);
                $sortOrder = intval($_POST['topic_sort_order'] ?? 1);

                if (empty($title)) {
                    $error = 'Topic title is required.';
                } else {
                    try {
                        $stmt = $db->prepare("UPDATE course_topics SET title = ?, description = ?, sort_order = ?, updated_at = NOW() WHERE id = ?");
                        $stmt->execute([$title, $description, $sortOrder, $topicId]);

                        $message = 'Topic updated successfully.';

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

            case 'delete_topic':
                $topicId = intval($_POST['topic_id']);

                try {
                    // Delete all lessons in this topic
                    $stmt = $db->prepare("DELETE FROM course_lessons WHERE topic_id = ?");
                    $stmt->execute([$topicId]);

                    // Delete the topic itself
                    $stmt = $db->prepare("DELETE FROM course_topics WHERE id = ?");
                    $stmt->execute([$topicId]);

                    $message = 'Topic and all its lessons deleted successfully.';

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

            case 'update_lesson':
                $lessonId = intval($_POST['lesson_id']);
                $title = trim($_POST['lesson_title']);
                $description = trim($_POST['lesson_description']);
                $content = trim($_POST['lesson_content']);
                $lessonType = $_POST['lesson_type'];
                $sortOrder = intval($_POST['sort_order']);
                $isPreview = isset($_POST['is_preview']);
                $estimatedTime = intval($_POST['estimated_time']);

                if (empty($title)) {
                    $error = 'Lesson title is required.';
                } else {
                    try {
                        $stmt = $db->prepare("UPDATE course_lessons SET title = ?, description = ?, content = ?, lesson_type = ?, sort_order = ?, is_preview = ?, estimated_time = ?, updated_at = NOW() WHERE id = ? AND course_id = ?");
                        $stmt->execute([$title, $description, $content, $lessonType, $sortOrder, $isPreview, $estimatedTime, $lessonId, $courseId]);

                        $message = 'Lesson updated successfully.';

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

// Function to refresh curriculum data
function refreshCurriculum($db, $courseId) {
    global $curriculum;

    $stmt = $db->prepare("
        SELECT
            cm.id as module_id, cm.title as module_title, cm.description as module_description, cm.sort_order as module_sort_order,
            ct.id as topic_id, ct.title as topic_title, ct.description as topic_description, ct.sort_order as topic_sort_order,
            cl.id as lesson_id, cl.title as lesson_title, cl.description as lesson_description, cl.content as lesson_content,
            cl.lesson_type, cl.sort_order as lesson_sort_order, cl.is_preview, cl.estimated_time
        FROM course_modules cm
        LEFT JOIN course_topics ct ON cm.id = ct.module_id
        LEFT JOIN course_lessons cl ON ct.id = cl.topic_id
        WHERE cm.course_id = ?
        ORDER BY cm.sort_order ASC, ct.sort_order ASC, cl.sort_order ASC
    ");
    $stmt->execute([$courseId]);
    $rawCurriculum = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Organize into hierarchical structure
    $curriculum = [];
    foreach ($rawCurriculum as $row) {
        $moduleId = $row['module_id'];
        $topicId = $row['topic_id'];
        $lessonId = $row['lesson_id'];

        if (!isset($curriculum[$moduleId])) {
            $curriculum[$moduleId] = [
                'id' => $moduleId,
                'title' => $row['module_title'],
                'description' => $row['module_description'],
                'sort_order' => $row['module_sort_order'],
                'topics' => []
            ];
        }

        if ($topicId && !isset($curriculum[$moduleId]['topics'][$topicId])) {
            $curriculum[$moduleId]['topics'][$topicId] = [
                'id' => $topicId,
                'title' => $row['topic_title'],
                'description' => $row['topic_description'],
                'sort_order' => $row['topic_sort_order'],
                'lessons' => []
            ];
        }

        if ($lessonId) {
            $curriculum[$moduleId]['topics'][$topicId]['lessons'][] = [
                'id' => $lessonId,
                'title' => $row['lesson_title'],
                'description' => $row['lesson_description'],
                'content' => $row['lesson_content'],
                'type' => $row['lesson_type'],
                'sort_order' => $row['lesson_sort_order'],
                'is_preview' => $row['is_preview'],
                'duration' => $row['estimated_time'] . 'm',
                'status' => 'draft',
                'is_free' => false
            ];
        }
    }

    // Convert associative array to indexed array
    $curriculum = array_values($curriculum);
    foreach ($curriculum as &$module) {
        $module['topics'] = array_values($module['topics']);
    }
    unset($module);
}

// Refresh curriculum after POST operations
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    refreshCurriculum($db, $courseId);
}

$page_title = 'Course Builder - ' . $lms_config['lms']['site_name'];
$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($page_title); ?></title>
    <!-- Load Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Set up Tailwind configuration for Inter font and a professional color palette -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'primary-blue': '#1E3A8A', // Deep Indigo/Navy
                        'background-light': '#F8FAFC', // Slate 50
                        'text-dark': '#1F2937', // Gray 800
                        'accent-subtle': '#E5E7EB', // Gray 200
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <!-- Font Awesome for icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        /* Ensuring full page height and scrolling */
        html, body {
            height: 100%;
        }
        /* Custom scrollbar for a cleaner look */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        ::-webkit-scrollbar-thumb {
            background-color: #D1D5DB; /* Gray 300 */
            border-radius: 4px;
        }
        ::-webkit-scrollbar-track {
            background-color: transparent;
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        <!-- Page Header -->
        <div class="p-4 sm:p-6 lg:p-8 pb-0">
            <div class="flex justify-between items-center mb-6">
                <div>
                    <h1 class="text-3xl font-bold text-gray-800">Edit Course</h1>
                    <p class="text-sm text-gray-600 mt-1"><?php echo htmlspecialchars($course['title']); ?></p>
                </div>

                <div class="flex items-center space-x-4">
                    <a href="../dashboard.php" 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 Dashboard
                    </a>
                    <a href="../../courses/course.php?id=<?php echo $course['id']; ?>" class="px-4 py-2 bg-blue-600 text-white rounded-lg shadow hover:bg-blue-700 transition duration-150" target="_blank">
                        <i class="fas fa-eye mr-2"></i>Preview Course
                    </a>
                </div>
            </div>
        </div>

        <!-- Course Stats -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <div class="bg-white p-6 rounded-xl shadow-lg border border-gray-100 text-center">
                <h3 class="text-3xl font-bold text-blue-600"><?php echo $enrollmentStats['total_enrollments']; ?></h3>
                <p class="text-gray-500 mt-2">Total Enrollments</p>
            </div>
            <div class="bg-white p-6 rounded-xl shadow-lg border border-gray-100 text-center">
                <h3 class="text-3xl font-bold text-green-600"><?php echo $enrollmentStats['completed_count']; ?></h3>
                <p class="text-gray-500 mt-2">Completions</p>
            </div>
            <div class="bg-white p-6 rounded-xl shadow-lg border border-gray-100 text-center">
                <h3 class="text-3xl font-bold text-cyan-600"><?php
                    $totalLessons = 0;
                    foreach ($curriculum as $module) {
                        foreach ($module['topics'] as $topic) {
                            $totalLessons += count($topic['lessons']);
                        }
                    }
                    echo $totalLessons;
                ?></h3>
                <p class="text-gray-500 mt-2">Lessons</p>
            </div>
            <div class="bg-white p-6 rounded-xl shadow-lg border border-gray-100 text-center">
                <h3 class="text-3xl font-bold text-yellow-600"><?php echo $course['status'] === 'published' ? 'Published' : 'Draft'; ?></h3>
                <p class="text-gray-500 mt-2">Status</p>
            </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 $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; ?>

        <!-- Tabs -->
        <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('basic')">Basic Info</button>
                    <button class="tab-button px-6 py-3 text-sm font-medium" onclick="switchTab('curriculum')">Curriculum</button>
                </div>
            </div>
            <div class="p-6">
                <!-- Basic Info Tab -->
                <div id="basic-tab" class="tab-content active">
                    <form method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="action" value="update_course">

                        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
                            <div class="lg:col-span-2 space-y-4">
                                <div>
                                    <label for="title" class="block text-sm font-medium text-gray-700 mb-2">Course 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="title" name="title" value="<?php echo htmlspecialchars($course['title']); ?>" required>
                                </div>

                                <div>
                                    <label for="slug" class="block text-sm font-medium text-gray-700 mb-2">URL Slug</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="slug" name="slug" value="<?php echo htmlspecialchars($course['slug']); ?>">
                                </div>

                                <div>
                                    <label for="shortDescription" class="block text-sm font-medium text-gray-700 mb-2">Short 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="shortDescription" name="short_description" rows="3"><?php echo htmlspecialchars($course['short_description'] ?? ''); ?></textarea>
                                </div>

                                <div>
                                    <label for="description" class="block text-sm font-medium text-gray-700 mb-2">Full 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="description" name="description" rows="8" required><?php echo htmlspecialchars($course['description']); ?></textarea>
                                </div>
                            </div>

                            <div class="space-y-4">
                            <div>
                                <label for="category" class="block text-sm font-medium text-gray-700 mb-2">Category</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="category" name="category_id">
                                    <option value="">Select Category</option>
                                    <?php foreach ($categories as $category): ?>
                                        <option value="<?php echo $category['id']; ?>" <?php echo $course['category_id'] == $category['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($category['name']); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div>
                                <label for="level" class="block text-sm font-medium text-gray-700 mb-2">Difficulty Level</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="level" name="level" required>
                                    <option value="beginner" <?php echo $course['level'] === 'beginner' ? 'selected' : ''; ?>>Beginner</option>
                                    <option value="intermediate" <?php echo $course['level'] === 'intermediate' ? 'selected' : ''; ?>>Intermediate</option>
                                    <option value="advanced" <?php echo $course['level'] === 'advanced' ? 'selected' : ''; ?>>Advanced</option>
                                </select>
                            </div>

                            <div>
                                <label for="language" class="block text-sm font-medium text-gray-700 mb-2">Language</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="language" name="language" value="<?php echo htmlspecialchars($course['language'] ?? 'English'); ?>">
                            </div>

                            <div>
                                <label for="duration_hours" class="block text-sm font-medium text-gray-700 mb-2">Duration (hours)</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="duration_hours" name="duration_hours" min="0" step="0.5" value="<?php echo htmlspecialchars($course['duration_hours'] ?? 0); ?>">
                            </div>

                            <div>
                                <label for="price" class="block text-sm font-medium text-gray-700 mb-2">Price</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="price" name="price" min="0" step="0.01" value="<?php echo htmlspecialchars($course['price'] ?? 0); ?>">
                            </div>

                            <div>
                                <label for="currency" class="block text-sm font-medium text-gray-700 mb-2">Currency</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="currency" name="currency">
                                    <option value="USD" <?php echo ($course['currency'] ?? 'USD') === 'USD' ? 'selected' : ''; ?>>USD</option>
                                    <option value="EUR" <?php echo ($course['currency'] ?? '') === 'EUR' ? 'selected' : ''; ?>>EUR</option>
                                    <option value="GBP" <?php echo ($course['currency'] ?? '') === 'GBP' ? 'selected' : ''; ?>>GBP</option>
                                    <option value="ZAR" <?php echo ($course['currency'] ?? '') === 'ZAR' ? 'selected' : ''; ?>>ZAR</option>
                                </select>
                            </div>

                            <div>
                                <label for="max_students" class="block text-sm font-medium text-gray-700 mb-2">Max Students (optional)</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="max_students" name="max_students" min="1" value="<?php echo htmlspecialchars($course['max_students'] ?? ''); ?>">
                            </div>

                            <div>
                                <label for="prerequisites" class="block text-sm font-medium text-gray-700 mb-2">Prerequisites</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="prerequisites" name="prerequisites" rows="3"><?php echo htmlspecialchars($course['prerequisites'] ?? ''); ?></textarea>
                            </div>

                            <div>
                                <label for="status" class="block text-sm font-medium text-gray-700 mb-2">Status</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="status" name="status" required>
                                    <option value="draft" <?php echo $course['status'] === 'draft' ? 'selected' : ''; ?>>Draft</option>
                                    <option value="published" <?php echo $course['status'] === 'published' ? 'selected' : ''; ?>>Published</option>
                                    <option value="archived" <?php echo $course['status'] === 'archived' ? 'selected' : ''; ?>>Archived</option>
                                </select>
                            </div>

                            <div class="space-y-3">
                                <label class="flex items-center">
                                    <input type="checkbox" class="mr-2" id="isFree" name="is_free" <?php echo $course['is_free'] ? 'checked' : ''; ?>>
                                    <span class="text-sm text-gray-700">Free Course</span>
                                </label>

                                <label class="flex items-center">
                                    <input type="checkbox" class="mr-2" id="isFeatured" name="is_featured" <?php echo $course['is_featured'] ? 'checked' : ''; ?>>
                                    <span class="text-sm text-gray-700">Featured Course</span>
                                </label>
                            </div>
                        </div>
                        </div>

                        <div class="flex justify-end mt-6">
                            <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>Update Course
                            </button>
                        </div>
                    </form>
                </div>

                <!-- Curriculum Tab -->
                <div id="curriculum-tab" class="tab-content">
                    <div class="flex justify-between items-center mb-6">
                        <div>
                            <h3 class="text-xl font-semibold text-gray-800">Curriculum Builder</h3>
                            <p class="text-gray-500 text-sm">Design the path for your students.</p>
                        </div>
                        <div class="flex space-x-3">
                            <button onclick="openAddModuleModal()" class="flex items-center gap-2 px-4 py-2.5 bg-white border border-gray-200 hover:border-indigo-200 rounded-xl text-sm font-bold text-gray-700 shadow-sm transition-all">
                                <i class="fas fa-layer-group text-gray-400"></i>
                                Add Module
                            </button>
                            <a href="lesson_editor.php?course_id=<?php echo $courseId; ?>" class="flex items-center gap-2 px-4 py-2.5 bg-indigo-600 hover:bg-indigo-700 rounded-xl text-sm font-bold text-white shadow-md shadow-indigo-100 transition-all">
                                <i class="fas fa-plus"></i>
                                Add Lesson
                            </a>
                        </div>
                    </div>

                    <?php if (empty($curriculum)): ?>
                        <div class="text-center py-12">
                            <i class="fas fa-book-open text-6xl text-gray-400 mb-4"></i>
                            <h4 class="text-xl font-semibold text-gray-800 mb-2">No curriculum yet</h4>
                            <p class="text-gray-500">Start building your course curriculum by adding modules and lessons.</p>
                        </div>
                    <?php else: ?>
                        <div class="space-y-6">
                            <?php foreach ($curriculum as $module): ?>
                                <div class="bg-white rounded-2xl border border-gray-200 shadow-sm overflow-hidden transition-all hover:border-indigo-200">
                                    <!-- Module Header -->
                                    <div class="px-6 py-4 bg-gray-50/50 border-b border-gray-100 flex items-center justify-between">
                                        <div class="flex items-center gap-3">
                                            <div class="bg-white p-1.5 rounded-lg border border-gray-200 text-gray-500">
                                                <i class="fas fa-grip-vertical w-4 h-4"></i>
                                            </div>
                                            <h3 class="font-bold text-gray-800"><?php echo htmlspecialchars($module['title']); ?></h3>
                                        </div>
                                        <div class="flex items-center gap-2">
                                            <button onclick="openAddTopicModal(<?php echo $module['id']; ?>)" class="flex items-center gap-1.5 px-3 py-1.5 bg-white border border-gray-200 rounded-lg text-xs font-black uppercase text-gray-500 hover:text-indigo-600 hover:border-indigo-200 transition-all">
                                                <i class="fas fa-plus w-3 h-3"></i> Add Topic
                                            </button>
                                            <button onclick="editModule(<?php echo $module['id']; ?>)" class="p-2 text-gray-400 hover:text-indigo-600 hover:bg-white rounded-lg transition-all">
                                                <i class="fas fa-edit w-4 h-4"></i>
                                            </button>
                                            <button onclick="deleteModule(<?php echo $module['id']; ?>)" class="p-2 text-gray-400 hover:text-red-500 hover:bg-white rounded-lg transition-all">
                                                <i class="fas fa-trash w-4 h-4"></i>
                                            </button>
                                        </div>
                                    </div>

                                    <!-- Topics List -->
                                    <div class="p-2 space-y-2">
                                        <?php if (empty($module['topics'])): ?>
                                            <div class="p-8 text-center border-2 border-dashed border-gray-100 rounded-xl">
                                                <p class="text-xs font-bold text-gray-300 uppercase tracking-widest">No topics in this module</p>
                                            </div>
                                        <?php else: ?>
                                            <?php foreach ($module['topics'] as $topic): ?>
                                                <div class="bg-white rounded-xl">
                                                    <div class="flex items-center justify-between px-4 py-3 hover:bg-gray-50 rounded-xl transition-colors group/topic">
                                                        <div class="flex items-center gap-3">
                                                            <i class="fas fa-chevron-down w-4 h-4 text-gray-300"></i>
                                                            <h4 class="font-bold text-gray-700 text-sm tracking-tight"><?php echo htmlspecialchars($topic['title']); ?></h4>
                                                        </div>
                                                        <div class="flex items-center gap-1 opacity-0 group-hover/topic:opacity-100 transition-opacity">
                                                            <a href="lesson_editor.php?course_id=<?php echo $courseId; ?>&topic_id=<?php echo $topic['id']; ?>" class="p-1.5 text-gray-400 hover:text-indigo-600 rounded-lg transition-colors">
                                                                <i class="fas fa-plus w-3.5 h-3.5"></i>
                                                            </a>
                                                            <button onclick="editTopic(<?php echo $topic['id']; ?>)" class="p-1.5 text-gray-400 hover:text-indigo-600 rounded-lg">
                                                                <i class="fas fa-edit w-3.5 h-3.5"></i>
                                                            </button>
                                                            <button onclick="deleteTopic(<?php echo $topic['id']; ?>)" class="p-1.5 text-gray-400 hover:text-red-500 rounded-lg">
                                                                <i class="fas fa-trash w-3.5 h-3.5"></i>
                                                            </button>
                                                        </div>
                                                    </div>

                                                    <!-- Lessons inside Topic -->
                                                    <div class="mt-1 space-y-1 ml-4 border-l-2 border-gray-50 pl-2 pb-2">
                                                        <?php foreach ($topic['lessons'] as $lesson): ?>
                                                            <div class="group/lesson flex items-center justify-between p-3 rounded-xl hover:bg-white hover:shadow-md hover:shadow-gray-100 transition-all">
                                                                <div class="flex items-center gap-4">
                                                                    <div class="p-2 rounded-lg <?php
                                                                        $bgColor = 'bg-gray-50 text-gray-600';
                                                                        $icon = 'fas fa-file-text';
                                                                        switch ($lesson['type']) {
                                                                            case 'video': $bgColor = 'bg-indigo-50 text-indigo-600'; $icon = 'fas fa-video'; break;
                                                                            case 'text': $bgColor = 'bg-orange-50 text-orange-600'; $icon = 'fas fa-file-alt'; break;
                                                                            case 'quiz': $bgColor = 'bg-purple-50 text-purple-600'; $icon = 'fas fa-question-circle'; break;
                                                                            case 'assignment': $bgColor = 'bg-emerald-50 text-emerald-600'; $icon = 'fas fa-tasks'; break;
                                                                            case 'resource': $bgColor = 'bg-blue-50 text-blue-600'; $icon = 'fas fa-download'; break;
                                                                        }
                                                                        echo $bgColor;
                                                                    ?>">
                                                                        <i class="<?php echo $icon; ?> w-4 h-4"></i>
                                                                    </div>
                                                                    <div>
                                                                        <div class="flex items-center gap-3 mb-0.5">
                                                                            <h5 class="font-bold text-gray-800 text-sm"><?php echo htmlspecialchars($lesson['title']); ?></h5>
                                                                            <span class="px-2 py-0.5 rounded-md text-xs font-bold uppercase tracking-wider <?php
                                                                                echo $lesson['status'] === 'published' ? 'bg-emerald-50 text-emerald-600 border border-emerald-100' : 'bg-amber-50 text-amber-600 border border-amber-100';
                                                                            ?>">
                                                                                <?php echo $lesson['status']; ?>
                                                                            </span>
                                                                        </div>
                                                                        <div class="flex items-center gap-2 text-xs font-bold text-gray-400 uppercase">
                                                                            <i class="fas fa-clock w-3 h-3"></i> <?php echo $lesson['duration']; ?>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                                <div class="flex items-center gap-1 opacity-0 group-hover/lesson:opacity-100 transition-opacity">
                                                                    <a href="lesson_editor.php?course_id=<?php echo $courseId; ?>&lesson_id=<?php echo $lesson['id']; ?>" class="p-2 text-gray-400 hover:text-indigo-600 rounded-lg transition-all">
                                                                        <i class="fas fa-edit w-4 h-4"></i>
                                                                    </a>
                                                                    <button onclick="deleteLesson(<?php echo $lesson['id']; ?>)" class="p-2 text-gray-400 hover:text-red-500 rounded-lg transition-all">
                                                                        <i class="fas fa-trash w-4 h-4"></i>
                                                                    </button>
                                                                </div>
                                                            </div>
                                                        <?php endforeach; ?>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>

        </div>
    </main>
</div>

<!-- Add Lesson Modal -->
<div id="addLessonModal" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-gray-900/60 backdrop-blur-sm hidden">
    <div class="bg-white w-full max-w-xl rounded-3xl shadow-2xl overflow-hidden animate-in fade-in zoom-in duration-200">
        <div class="px-8 py-6 border-b border-gray-100 flex items-center justify-between">
            <div>
                <h3 class="font-black text-gray-900 text-xl tracking-tight">Create Lesson</h3>
                <p class="text-gray-500 text-xs font-medium">Define your lesson parameters</p>
            </div>
            <button onclick="closeAddLessonModal()" class="text-gray-400 hover:text-gray-600">
                <i class="fas fa-times w-6 h-6"></i>
            </button>
        </div>

        <form method="POST">
            <div class="p-8 space-y-6 max-h-[70vh] overflow-y-auto">
                <input type="hidden" name="action" value="add_lesson">
                <input type="hidden" name="topic_id" id="lessonTopicId">

                <div class="grid grid-cols-2 gap-4">
                    <div class="space-y-2">
                        <label class="text-xs font-black text-gray-400 uppercase tracking-widest">Target Module</label>
                        <select name="module_id" id="lessonModuleSelect" class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-sm font-bold focus:ring-2 focus:ring-indigo-500 outline-none appearance-none" onchange="updateTopicsForLesson()">
                            <option value="">Choose Module...</option>
                            <?php foreach ($curriculum as $module): ?>
                                <option value="<?php echo $module['id']; ?>"><?php echo htmlspecialchars($module['title']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="space-y-2">
                        <label class="text-xs font-black text-gray-400 uppercase tracking-widest">Target Topic</label>
                        <select name="topic_id" id="lessonTopicSelect" class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-sm font-bold focus:ring-2 focus:ring-indigo-500 outline-none appearance-none disabled:opacity-50" disabled>
                            <option value="">Choose Module First</option>
                        </select>
                    </div>
                </div>

                <div id="lessonFormSection" class="space-y-6 transition-all opacity-30 pointer-events-none">
                    <div class="space-y-2">
                        <label class="text-xs font-black text-gray-400 uppercase tracking-widest">Lesson Title</label>
                        <input type="text" name="lesson_title" placeholder="Lesson Name" class="w-full bg-white border border-gray-200 rounded-xl px-4 py-3 text-sm font-bold outline-none" required>
                    </div>

                    <div class="space-y-2">
                        <label class="text-xs font-black text-gray-400 uppercase tracking-widest">Content Type</label>
                        <select name="lesson_type" class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-sm font-bold outline-none">
                            <option value="video">Video Lesson</option>
                            <option value="text">Text / Article</option>
                            <option value="quiz">Interactive Quiz</option>
                            <option value="assignment">Assignment / Project</option>
                            <option value="resource">Downloadable Resource</option>
                        </select>
                    </div>

                    <div class="space-y-2">
                        <label class="text-xs font-black text-gray-400 uppercase tracking-widest">Description</label>
                        <textarea name="lesson_description" rows="3" placeholder="Brief description..." class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-sm font-bold outline-none"></textarea>
                    </div>

                    <div class="grid grid-cols-2 gap-4">
                        <div class="space-y-2">
                            <label class="text-xs font-black text-gray-400 uppercase tracking-widest">Estimated Time (min)</label>
                            <input type="number" name="estimated_time" min="1" value="30" class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-sm font-bold outline-none">
                        </div>
                        <div class="space-y-2">
                            <label class="text-xs font-black text-gray-400 uppercase tracking-widest">Sort Order</label>
                            <input type="number" name="sort_order" min="1" value="1" class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-sm font-bold outline-none">
                        </div>
                    </div>

                    <div class="space-y-2">
                        <label class="text-xs font-black text-gray-400 uppercase tracking-widest">Content</label>
                        <textarea name="lesson_content" rows="4" placeholder="Lesson content..." class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-sm font-bold outline-none"></textarea>
                    </div>

                    <div class="flex items-center space-x-2">
                        <input type="checkbox" id="isPreview" name="is_preview" class="rounded">
                        <label for="isPreview" class="text-sm text-gray-700">Allow preview (visible to non-enrolled students)</label>
                    </div>
                </div>
            </div>

            <div class="px-8 py-6 bg-gray-50 border-t border-gray-100 flex gap-3">
                <button type="button" onclick="closeAddLessonModal()" class="flex-1 py-3 text-sm font-bold text-gray-500">Discard</button>
                <button type="submit" id="createLessonBtn" class="flex-1 py-3 text-sm font-bold text-white bg-indigo-600 rounded-xl disabled:bg-gray-200" disabled>Create Lesson</button>
            </div>
        </form>
    </div>
</div>

<!-- Edit Lesson Modal -->
<div id="editLessonModal" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-gray-900/60 backdrop-blur-sm hidden">
    <div class="bg-white w-full max-w-xl rounded-3xl shadow-2xl overflow-hidden animate-in fade-in zoom-in duration-200">
        <div class="px-8 py-6 border-b border-gray-100 flex items-center justify-between">
            <div>
                <h3 class="font-black text-gray-900 text-xl tracking-tight">Edit Lesson</h3>
                <p class="text-gray-500 text-xs font-medium">Update your lesson parameters</p>
            </div>
            <button onclick="closeEditLessonModal()" class="text-gray-400 hover:text-gray-600">
                <i class="fas fa-times w-6 h-6"></i>
            </button>
        </div>

        <form method="POST">
            <div class="p-8 space-y-6 max-h-[70vh] overflow-y-auto">
                <input type="hidden" name="action" value="update_lesson">
                <input type="hidden" name="lesson_id" id="editLessonId">

                <div class="space-y-2">
                    <label class="text-xs font-black text-gray-400 uppercase tracking-widest">Lesson Title</label>
                    <input type="text" name="lesson_title" id="editLessonTitle" placeholder="Lesson Name" class="w-full bg-white border border-gray-200 rounded-xl px-4 py-3 text-sm font-bold outline-none" required>
                </div>

                <div class="space-y-2">
                    <label class="text-xs font-black text-gray-400 uppercase tracking-widest">Content Type</label>
                    <select name="lesson_type" id="editLessonType" class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-sm font-bold outline-none">
                        <option value="video">Video Lesson</option>
                        <option value="text">Text / Article</option>
                        <option value="quiz">Interactive Quiz</option>
                        <option value="assignment">Assignment / Project</option>
                        <option value="resource">Downloadable Resource</option>
                    </select>
                </div>

                <div class="space-y-2">
                    <label class="text-xs font-black text-gray-400 uppercase tracking-widest">Description</label>
                    <textarea name="lesson_description" id="editLessonDescription" rows="3" placeholder="Brief description..." class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-sm font-bold outline-none"></textarea>
                </div>

                <div class="grid grid-cols-2 gap-4">
                    <div class="space-y-2">
                        <label class="text-xs font-black text-gray-400 uppercase tracking-widest">Estimated Time (min)</label>
                        <input type="number" name="estimated_time" id="editLessonTime" min="1" value="30" class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-sm font-bold outline-none">
                    </div>
                    <div class="space-y-2">
                        <label class="text-xs font-black text-gray-400 uppercase tracking-widest">Sort Order</label>
                        <input type="number" name="sort_order" id="editLessonSortOrder" min="1" value="1" class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-sm font-bold outline-none">
                    </div>
                </div>

                <div class="space-y-2">
                    <label class="text-xs font-black text-gray-400 uppercase tracking-widest">Content</label>
                    <textarea name="lesson_content" id="editLessonContent" rows="4" placeholder="Lesson content..." class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-sm font-bold outline-none"></textarea>
                </div>

                <div class="flex items-center space-x-2">
                    <input type="checkbox" id="editIsPreview" name="is_preview" class="rounded">
                    <label for="editIsPreview" class="text-sm text-gray-700">Allow preview (visible to non-enrolled students)</label>
                </div>
            </div>

            <div class="px-8 py-6 bg-gray-50 border-t border-gray-100 flex gap-3">
                <button type="button" onclick="closeEditLessonModal()" class="flex-1 py-3 text-sm font-bold text-gray-500">Discard</button>
                <button type="submit" class="flex-1 py-3 text-sm font-bold text-white bg-indigo-600 rounded-xl">Update Lesson</button>
            </div>
        </form>
    </div>
</div>

<!-- Delete Lesson Modal -->
<div id="deleteLessonModal" 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-md 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">Delete Lesson</h3>
            <button onclick="closeDeleteLessonModal()" 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="delete_lesson">
                <input type="hidden" name="lesson_id" id="deleteLessonId">
                <p class="text-gray-700 mb-4">Are you sure you want to delete the lesson "<span id="deleteLessonTitle" class="font-semibold"></span>"?</p>
                <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                    <div class="flex">
                        <i class="fas fa-exclamation-triangle text-yellow-400"></i>
                        <div class="ml-3">
                            <h4 class="text-sm font-medium text-yellow-800">Warning</h4>
                            <p class="text-sm text-yellow-700 mt-1">This action cannot be undone. Student progress for this lesson will also be removed.</p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="flex justify-end space-x-3 p-6 border-t border-gray-200">
                <button type="button" onclick="closeDeleteLessonModal()" 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-red-600 text-white rounded-lg hover:bg-red-700 transition duration-150">Delete Lesson</button>
            </div>
        </form>
    </div>
</div>

<!-- Add Module Modal -->
<div id="addModuleModal" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-gray-900/60 backdrop-blur-sm hidden">
    <div class="bg-white w-full max-w-md rounded-3xl shadow-2xl animate-in zoom-in duration-200 overflow-hidden">
        <div class="px-8 py-6 border-b border-gray-100 flex items-center justify-between">
            <h3 class="font-black text-gray-900 text-xl tracking-tight">New Module</h3>
            <button onclick="closeAddModuleModal()" class="text-gray-400 hover:text-gray-600">
                <i class="fas fa-times w-6 h-6"></i>
            </button>
        </div>
        <form method="POST">
            <div class="p-8 space-y-4">
                <input type="hidden" name="action" value="add_module">
                <div class="space-y-2">
                    <label class="text-xs font-black text-gray-400 uppercase tracking-widest">Module Title</label>
                    <input type="text" name="module_title" placeholder="e.g. Introduction to Frameworks" class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-sm font-bold focus:ring-2 focus:ring-indigo-500 outline-none" required>
                </div>
                <div class="space-y-2">
                    <label class="text-xs font-black text-gray-400 uppercase tracking-widest">Description (Optional)</label>
                    <textarea name="module_description" rows="3" placeholder="Brief description of this module..." class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-sm font-bold focus:ring-2 focus:ring-indigo-500 outline-none"></textarea>
                </div>
                <div class="space-y-2">
                    <label class="text-xs font-black text-gray-400 uppercase tracking-widest">Sort Order</label>
                    <input type="number" name="module_sort_order" min="1" value="1" class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-sm font-bold focus:ring-2 focus:ring-indigo-500 outline-none">
                </div>
            </div>
            <div class="px-8 py-6 bg-gray-50 border-t border-gray-100 flex gap-3">
                <button type="button" onclick="closeAddModuleModal()" class="flex-1 py-3 text-sm font-bold text-gray-500">Cancel</button>
                <button type="submit" class="flex-1 py-3 text-sm font-bold text-white bg-indigo-600 rounded-xl shadow-lg shadow-indigo-100">Create Module</button>
            </div>
        </form>
    </div>
</div>

<!-- Edit Module Modal -->
<div id="editModuleModal" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-gray-900/60 backdrop-blur-sm hidden">
    <div class="bg-white w-full max-w-md rounded-3xl shadow-2xl animate-in zoom-in duration-200 overflow-hidden">
        <div class="px-8 py-6 border-b border-gray-100 flex items-center justify-between">
            <h3 class="font-black text-gray-900 text-xl tracking-tight">Edit Module</h3>
            <button onclick="closeEditModuleModal()" class="text-gray-400 hover:text-gray-600">
                <i class="fas fa-times w-6 h-6"></i>
            </button>
        </div>
        <form method="POST">
            <div class="p-8 space-y-4">
                <input type="hidden" name="action" value="update_module">
                <input type="hidden" name="module_id" id="editModuleId">
                <div class="space-y-2">
                    <label class="text-xs font-black text-gray-400 uppercase tracking-widest">Module Title</label>
                    <input type="text" name="module_title" id="editModuleTitle" placeholder="e.g. Introduction to Frameworks" class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-sm font-bold focus:ring-2 focus:ring-indigo-500 outline-none" required>
                </div>
                <div class="space-y-2">
                    <label class="text-xs font-black text-gray-400 uppercase tracking-widest">Description (Optional)</label>
                    <textarea name="module_description" id="editModuleDescription" rows="3" placeholder="Brief description of this module..." class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-sm font-bold focus:ring-2 focus:ring-indigo-500 outline-none"></textarea>
                </div>
                <div class="space-y-2">
                    <label class="text-xs font-black text-gray-400 uppercase tracking-widest">Sort Order</label>
                    <input type="number" name="module_sort_order" id="editModuleSortOrder" min="1" value="1" class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-sm font-bold focus:ring-2 focus:ring-indigo-500 outline-none">
                </div>
            </div>
            <div class="px-8 py-6 bg-gray-50 border-t border-gray-100 flex gap-3">
                <button type="button" onclick="closeEditModuleModal()" class="flex-1 py-3 text-sm font-bold text-gray-500">Cancel</button>
                <button type="submit" class="flex-1 py-3 text-sm font-bold text-white bg-indigo-600 rounded-xl shadow-lg shadow-indigo-100">Update Module</button>
            </div>
        </form>
    </div>
</div>

<!-- Delete Module Modal -->
<div id="deleteModuleModal" 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-md 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">Delete Module</h3>
            <button onclick="closeDeleteModuleModal()" 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="delete_module">
                <input type="hidden" name="module_id" id="deleteModuleId">
                <p class="text-gray-700 mb-4">Are you sure you want to delete the module "<span id="deleteModuleTitle" class="font-semibold"></span>"?</p>
                <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                    <div class="flex">
                        <i class="fas fa-exclamation-triangle text-yellow-400"></i>
                        <div class="ml-3">
                            <h4 class="text-sm font-medium text-yellow-800">Warning</h4>
                            <p class="text-sm text-yellow-700 mt-1">This action cannot be undone. All topics and lessons within this module will also be deleted.</p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="flex justify-end space-x-3 p-6 border-t border-gray-200">
                <button type="button" onclick="closeDeleteModuleModal()" 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-red-600 text-white rounded-lg hover:bg-red-700 transition duration-150">Delete Module</button>
            </div>
        </form>
    </div>
</div>

<!-- Add Topic Modal -->
<div id="addTopicModal" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-gray-900/60 backdrop-blur-sm hidden">
    <div class="bg-white w-full max-w-md rounded-3xl shadow-2xl animate-in zoom-in duration-200 overflow-hidden">
        <div class="px-8 py-6 border-b border-gray-100 flex items-center justify-between">
            <h3 class="font-black text-gray-900 text-xl tracking-tight">Add Topic</h3>
            <button onclick="closeAddTopicModal()" class="text-gray-400 hover:text-gray-600">
                <i class="fas fa-times w-6 h-6"></i>
            </button>
        </div>
        <form method="POST">
            <div class="p-8 space-y-4">
                <input type="hidden" name="action" value="add_topic">
                <input type="hidden" name="module_id" id="topicModuleId">
                <div class="space-y-2">
                    <label class="text-xs font-black text-gray-400 uppercase tracking-widest">Topic Title</label>
                    <input type="text" name="topic_title" placeholder="e.g. Setting up Git" class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-sm font-bold focus:ring-2 focus:ring-indigo-500 outline-none" required>
                </div>
                <div class="space-y-2">
                    <label class="text-xs font-black text-gray-400 uppercase tracking-widest">Description (Optional)</label>
                    <textarea name="topic_description" rows="3" placeholder="Brief description of this topic..." class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-sm font-bold focus:ring-2 focus:ring-indigo-500 outline-none"></textarea>
                </div>
                <div class="space-y-2">
                    <label class="text-xs font-black text-gray-400 uppercase tracking-widest">Sort Order</label>
                    <input type="number" name="topic_sort_order" min="1" value="1" class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-sm font-bold focus:ring-2 focus:ring-indigo-500 outline-none">
                </div>
            </div>
            <div class="px-8 py-6 bg-gray-50 border-t border-gray-100 flex gap-3">
                <button type="button" onclick="closeAddTopicModal()" class="flex-1 py-3 text-sm font-bold text-gray-500">Cancel</button>
                <button type="submit" class="flex-1 py-3 text-sm font-bold text-white bg-indigo-600 rounded-xl shadow-lg shadow-indigo-100">Add Topic</button>
            </div>
        </form>
    </div>
</div>

<!-- Edit Topic Modal -->
<div id="editTopicModal" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-gray-900/60 backdrop-blur-sm hidden">
    <div class="bg-white w-full max-w-md rounded-3xl shadow-2xl animate-in zoom-in duration-200 overflow-hidden">
        <div class="px-8 py-6 border-b border-gray-100 flex items-center justify-between">
            <h3 class="font-black text-gray-900 text-xl tracking-tight">Edit Topic</h3>
            <button onclick="closeEditTopicModal()" class="text-gray-400 hover:text-gray-600">
                <i class="fas fa-times w-6 h-6"></i>
            </button>
        </div>
        <form method="POST">
            <div class="p-8 space-y-4">
                <input type="hidden" name="action" value="update_topic">
                <input type="hidden" name="topic_id" id="editTopicId">
                <div class="space-y-2">
                    <label class="text-xs font-black text-gray-400 uppercase tracking-widest">Topic Title</label>
                    <input type="text" name="topic_title" id="editTopicTitle" placeholder="e.g. Setting up Git" class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-sm font-bold focus:ring-2 focus:ring-indigo-500 outline-none" required>
                </div>
                <div class="space-y-2">
                    <label class="text-xs font-black text-gray-400 uppercase tracking-widest">Description (Optional)</label>
                    <textarea name="topic_description" id="editTopicDescription" rows="3" placeholder="Brief description of this topic..." class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-sm font-bold focus:ring-2 focus:ring-indigo-500 outline-none"></textarea>
                </div>
                <div class="space-y-2">
                    <label class="text-xs font-black text-gray-400 uppercase tracking-widest">Sort Order</label>
                    <input type="number" name="topic_sort_order" id="editTopicSortOrder" min="1" value="1" class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-sm font-bold focus:ring-2 focus:ring-indigo-500 outline-none">
                </div>
            </div>
            <div class="px-8 py-6 bg-gray-50 border-t border-gray-100 flex gap-3">
                <button type="button" onclick="closeEditTopicModal()" class="flex-1 py-3 text-sm font-bold text-gray-500">Cancel</button>
                <button type="submit" class="flex-1 py-3 text-sm font-bold text-white bg-indigo-600 rounded-xl shadow-lg shadow-indigo-100">Update Topic</button>
            </div>
        </form>
    </div>
</div>

<!-- Delete Topic Modal -->
<div id="deleteTopicModal" 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-md 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">Delete Topic</h3>
            <button onclick="closeDeleteTopicModal()" 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="delete_topic">
                <input type="hidden" name="topic_id" id="deleteTopicId">
                <p class="text-gray-700 mb-4">Are you sure you want to delete the topic "<span id="deleteTopicTitle" class="font-semibold"></span>"?</p>
                <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                    <div class="flex">
                        <i class="fas fa-exclamation-triangle text-yellow-400"></i>
                        <div class="ml-3">
                            <h4 class="text-sm font-medium text-yellow-800">Warning</h4>
                            <p class="text-sm text-yellow-700 mt-1">This action cannot be undone. All lessons within this topic will also be deleted.</p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="flex justify-end space-x-3 p-6 border-t border-gray-200">
                <button type="button" onclick="closeDeleteTopicModal()" 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-red-600 text-white rounded-lg hover:bg-red-700 transition duration-150">Delete Topic</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');

    // Load data for specific tabs

}
 // Modal functions for Modules
 function openAddModuleModal() {
     document.getElementById('addModuleModal').classList.remove('hidden');
 }
 
 function closeAddModuleModal() {
     document.getElementById('addModuleModal').classList.add('hidden');
 }
 
 function editModule(moduleId) {
     const curriculum = <?php echo json_encode($curriculum); ?>;
     const module = curriculum.find(m => m.id == moduleId);
     if (module) {
         document.getElementById('editModuleId').value = module.id;
         document.getElementById('editModuleTitle').value = module.title;
         document.getElementById('editModuleDescription').value = module.description || '';
         document.getElementById('editModuleSortOrder').value = module.sort_order;
         document.getElementById('editModuleModal').classList.remove('hidden');
     }
 }
 
 function closeEditModuleModal() {
     document.getElementById('editModuleModal').classList.add('hidden');
 }
 
 function deleteModule(moduleId) {
     const curriculum = <?php echo json_encode($curriculum); ?>;
     const module = curriculum.find(m => m.id == moduleId);
     if (module) {
         document.getElementById('deleteModuleId').value = module.id;
         document.getElementById('deleteModuleTitle').textContent = module.title;
         document.getElementById('deleteModuleModal').classList.remove('hidden');
     }
 }
 
 function closeDeleteModuleModal() {
     document.getElementById('deleteModuleModal').classList.add('hidden');
 }

// Modal functions for Topics
function openAddTopicModal(moduleId) {
    document.getElementById('topicModuleId').value = moduleId;
    document.getElementById('addTopicModal').classList.remove('hidden');
}

function closeAddTopicModal() {
    document.getElementById('addTopicModal').classList.add('hidden');
}

function editTopic(topicId) {
    const curriculum = <?php echo json_encode($curriculum); ?>;
    let topic = null;
    for (const module of curriculum) {
        topic = module.topics.find(t => t.id == topicId);
        if (topic) break;
    }
    if (topic) {
        document.getElementById('editTopicId').value = topic.id;
        document.getElementById('editTopicTitle').value = topic.title;
        document.getElementById('editTopicDescription').value = topic.description || '';
        document.getElementById('editTopicSortOrder').value = topic.sort_order;
        document.getElementById('editTopicModal').classList.remove('hidden');
    }
}

function closeEditTopicModal() {
    document.getElementById('editTopicModal').classList.add('hidden');
}

function deleteTopic(topicId) {
    const curriculum = <?php echo json_encode($curriculum); ?>;
    let topic = null;
    for (const module of curriculum) {
        topic = module.topics.find(t => t.id == topicId);
        if (topic) break;
    }
    if (topic) {
        document.getElementById('deleteTopicId').value = topic.id;
        document.getElementById('deleteTopicTitle').textContent = topic.title;
        document.getElementById('deleteTopicModal').classList.remove('hidden');
    }
}

function closeDeleteTopicModal() {
    document.getElementById('deleteTopicModal').classList.add('hidden');
}

// Modal functions for Lessons
function openAddLessonModal(topicId = null) {
    if (topicId) {
        document.getElementById('lessonTopicId').value = topicId;
        // Pre-select the module and topic if provided
        // This would require additional logic to find the module for the topic
    }
    document.getElementById('addLessonModal').classList.remove('hidden');
}

function closeAddLessonModal() {
    document.getElementById('addLessonModal').classList.add('hidden');
    // Reset form
    document.getElementById('lessonModuleSelect').value = '';
    document.getElementById('lessonTopicSelect').value = '';
    document.getElementById('lessonFormSection').classList.add('opacity-30', 'pointer-events-none');
    document.getElementById('lessonTopicSelect').disabled = true;
    document.getElementById('createLessonBtn').disabled = true;
}

function editLesson(lessonId) {
    const curriculum = <?php echo json_encode($curriculum); ?>;
    let lesson = null;
    for (const module of curriculum) {
        for (const topic of module.topics) {
            lesson = topic.lessons.find(l => l.id == lessonId);
            if (lesson) break;
        }
        if (lesson) break;
    }
    if (lesson) {
        document.getElementById('editLessonId').value = lesson.id;
        document.getElementById('editLessonTitle').value = lesson.title;
        document.getElementById('editLessonType').value = lesson.type;
        document.getElementById('editLessonDescription').value = lesson.description || '';
        document.getElementById('editLessonTime').value = lesson.duration.replace('m', '');
        document.getElementById('editLessonSortOrder').value = lesson.sort_order;
        document.getElementById('editLessonContent').value = lesson.content || '';
        document.getElementById('editIsPreview').checked = lesson.is_preview;
        document.getElementById('editLessonModal').classList.remove('hidden');
    }
}

function closeEditLessonModal() {
    document.getElementById('editLessonModal').classList.add('hidden');
}

function deleteLesson(lessonId) {
    const curriculum = <?php echo json_encode($curriculum); ?>;
    let lesson = null;
    for (const module of curriculum) {
        for (const topic of module.topics) {
            lesson = topic.lessons.find(l => l.id == lessonId);
            if (lesson) break;
        }
        if (lesson) break;
    }
    if (lesson) {
        document.getElementById('deleteLessonId').value = lesson.id;
        document.getElementById('deleteLessonTitle').textContent = lesson.title;
        document.getElementById('deleteLessonModal').classList.remove('hidden');
    }
}

function closeDeleteLessonModal() {
    document.getElementById('deleteLessonModal').classList.add('hidden');
}

function updateTopicsForLesson() {
    const moduleId = document.getElementById('lessonModuleSelect').value;
    const topicSelect = document.getElementById('lessonTopicSelect');

    if (!moduleId) {
        topicSelect.innerHTML = '<option value="">Choose Module First</option>';
        topicSelect.disabled = true;
        document.getElementById('lessonFormSection').classList.add('opacity-30', 'pointer-events-none');
        document.getElementById('createLessonBtn').disabled = true;
        return;
    }

    // Find topics for the selected module
    const curriculum = <?php echo json_encode($curriculum); ?>;
    const module = curriculum.find(m => m.id == moduleId);

    if (module && module.topics.length > 0) {
        topicSelect.innerHTML = '<option value="">Select Topic...</option>';
        module.topics.forEach(topic => {
            const option = document.createElement('option');
            option.value = topic.id;
            option.textContent = topic.title;
            topicSelect.appendChild(option);
        });
        topicSelect.disabled = false;
        document.getElementById('lessonFormSection').classList.remove('opacity-30', 'pointer-events-none');
        document.getElementById('createLessonBtn').disabled = false;
    } else {
        topicSelect.innerHTML = '<option value="">No topics available</option>';
        topicSelect.disabled = true;
        document.getElementById('lessonFormSection').classList.add('opacity-30', 'pointer-events-none');
        document.getElementById('createLessonBtn').disabled = true;
    }
}

// Update topic selection when topic is changed
document.getElementById('lessonTopicSelect').addEventListener('change', function() {
    const topicId = this.value;
    document.getElementById('lessonTopicId').value = topicId;
});

// Unsaved Changes Warning System
let hasUnsavedChanges = false;

// Track changes in modal forms
const modalForms = [
    'addLessonModal',
    'addModuleModal',
    'addTopicModal',
    'editLessonModal',
    'editModuleModal',
    'editTopicModal'
];

// Function to mark form as dirty when inputs change
function setupUnsavedChangesTracking() {
    modalForms.forEach(modalId => {
        const modal = document.getElementById(modalId);
        if (!modal) return;

        const form = modal.querySelector('form');
        if (!form) return;

        // Track input changes
        const inputs = form.querySelectorAll('input, textarea, select');
        inputs.forEach(input => {
            input.addEventListener('change', () => {
                hasUnsavedChanges = true;
            });

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

        // Reset flag when form is submitted
        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 in a form. Are you sure you want to leave?';
        return 'You have unsaved changes in a form. Are you sure you want to leave?';
    }
});

// Reset unsaved changes flag when closing modals without submitting
function resetUnsavedChanges() {
    hasUnsavedChanges = false;
}

// Override modal close functions to reset the flag
const originalCloseAddLessonModal = closeAddLessonModal;
closeAddLessonModal = function() {
    resetUnsavedChanges();
    originalCloseAddLessonModal();
};

const originalCloseAddModuleModal = closeAddModuleModal;
closeAddModuleModal = function() {
    resetUnsavedChanges();
    originalCloseAddModuleModal();
};

const originalCloseAddTopicModal = closeAddTopicModal;
closeAddTopicModal = function() {
    resetUnsavedChanges();
    originalCloseAddTopicModal();
};

const originalCloseEditLessonModal = closeEditLessonModal;
closeEditLessonModal = function() {
    resetUnsavedChanges();
    originalCloseEditLessonModal();
};

const originalCloseEditModuleModal = closeEditModuleModal;
closeEditModuleModal = function() {
    resetUnsavedChanges();
    originalCloseEditModuleModal();
};

const originalCloseEditTopicModal = closeEditTopicModal;
closeEditTopicModal = function() {
    resetUnsavedChanges();
    originalCloseEditTopicModal();
};

// Initialize unsaved changes tracking when page loads
document.addEventListener('DOMContentLoaded', () => {
    setupUnsavedChangesTracking();
});


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

</body>
</html>
