<?php
require_once '../../includes/middleware.php';
require_once '../../config/database.php';
require_once '../../includes/functions.php';

$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 lessons
$stmt = $db->prepare("SELECT * FROM course_lessons WHERE course_id = ? ORDER BY sort_order ASC");
$stmt->execute([$courseId]);
$lessons = $stmt->fetchAll();

// 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_module':
                $title = trim($_POST['module_title']);
                $description = trim($_POST['module_description']);
                $sortOrder = intval($_POST['module_sort_order']);
                $estimatedTime = intval($_POST['module_estimated_time']);

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

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

                        $message = 'Module added successfully.';

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

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

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

                    $message = 'Module deleted successfully.';

                } catch (PDOException $e) {
                    $error = 'Error deleting module: ' . $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'];
                $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("INSERT INTO course_lessons (course_id, title, description, content, lesson_type, sort_order, is_preview, estimated_time, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");
                        $stmt->execute([$courseId, $title, $description, $content, $lessonType, $sortOrder, $isPreview, $estimatedTime]);

                        $message = 'Lesson added successfully.';

                        // Refresh lessons
                        $stmt = $db->prepare("SELECT * FROM course_lessons WHERE course_id = ? ORDER BY sort_order ASC");
                        $stmt->execute([$courseId]);
                        $lessons = $stmt->fetchAll();

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

                    // Refresh lessons
                    $stmt = $db->prepare("SELECT * FROM course_lessons WHERE course_id = ? ORDER BY sort_order ASC");
                    $stmt->execute([$courseId]);
                    $lessons = $stmt->fetchAll();

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

$pageTitle = 'Edit Course: ' . htmlspecialchars($course['title']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Content-Security-Policy" content="frame-src https://www.youtube.com https://youtube.com https://vimeo.com https://player.vimeo.com;">
    <title><?php echo htmlspecialchars($pageTitle); ?></title>
    <!-- Load Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Font Awesome for icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        /* Custom Tailwind Configuration and Base Styles */
        :root {
            --primary: #007bff; /* Blue */
            --secondary: #6c757d; /* Gray */
            --success: #28a745; /* Green */
            --danger: #dc3545; /* Red */
            --info: #17a2b8; /* Cyan */
        }
        .text-primary { color: var(--primary); }
        .bg-primary { background-color: var(--primary); }
        .bg-success { background-color: var(--success); }
        .bg-secondary { background-color: var(--secondary); }

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

        /* Custom Styles for Dashboard Layout */
        .admin-sidebar {
            transition: transform 0.3s ease-in-out;
            min-width: 250px;
        }
        @media (max-width: 1024px) {
            .admin-sidebar {
                position: fixed;
                top: 0;
                left: 0;
                transform: translateX(-100%);
                z-index: 50;
                height: 100%;
            }
            .admin-container.sidebar-open .admin-sidebar {
                transform: translateX(0);
            }
            .admin-container.sidebar-open .sidebar-overlay {
                display: block;
            }
        }

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

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

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

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

        .toast-success { background-color: var(--success); }
        .toast-error { background-color: var(--danger); }

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

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

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

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

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

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

        <!-- 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 echo count($lessons); ?></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('modules')">Modules</button>
                    <button class="tab-button px-6 py-3 text-sm font-medium" onclick="switchTab('curriculum')">Curriculum</button>
                    <button class="tab-button px-6 py-3 text-sm font-medium" onclick="switchTab('enrollments')">Enrollments</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>

               <!-- Modules Tab -->
               <div id="modules-tab" class="tab-content">
                   <div class="flex justify-between items-center mb-6">
                       <h3 class="text-xl font-semibold text-gray-800">Course Modules</h3>
                       <button class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition duration-150" onclick="openAddModuleModal()">
                           <i class="fas fa-plus mr-2"></i>Add Module
                       </button>
                   </div>

                   <div id="modules-list">
                       <!-- Modules will be loaded here -->
                   </div>
               </div>

               <!-- Curriculum Tab -->
               <div id="curriculum-tab" class="tab-content">
                   <div class="flex justify-between items-center mb-6">
                       <h3 class="text-xl font-semibold text-gray-800">Course Lessons</h3>
                       <div class="flex space-x-3">
                           <a href="lesson_editor.php?course_id=<?php echo $courseId; ?>" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition duration-150">
                               <i class="fas fa-plus mr-2"></i>Create Lesson
                           </a>
                           <button class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition duration-150" onclick="openAddLessonModal()">
                               <i class="fas fa-plus-circle mr-2"></i>Quick Add
                           </button>
                       </div>
                   </div>

                   <?php if (empty($lessons)): ?>
                       <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 lessons yet</h4>
                           <p class="text-gray-500">Start building your course curriculum by adding lessons.</p>
                       </div>
                   <?php else: ?>
                       <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                           <?php foreach ($lessons as $lesson): ?>
                               <div class="bg-white border border-gray-200 rounded-lg p-6 shadow-sm">
                                   <div class="flex justify-between items-start">
                                       <div class="flex-1">
                                           <h4 class="text-lg font-semibold text-gray-800 mb-2"><?php echo htmlspecialchars($lesson['title']); ?></h4>
                                           <p class="text-gray-600 text-sm mb-3"><?php echo htmlspecialchars(substr($lesson['description'] ?? 'No description', 0, 100)); ?>...</p>
                                           <div class="flex items-center space-x-2">
                                               <span class="px-2 py-1 bg-gray-100 text-gray-700 text-xs rounded-full"><?php echo ucfirst($lesson['lesson_type']); ?></span>
                                               <?php if ($lesson['is_preview']): ?>
                                                   <span class="px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full">Preview</span>
                                               <?php endif; ?>
                                               <span class="text-gray-500 text-sm"><?php echo $lesson['estimated_time']; ?> min</span>
                                           </div>
                                       </div>
                                       <div class="relative">
                                           <button class="p-2 text-gray-400 hover:text-gray-600" onclick="toggleLessonMenu(<?php echo $lesson['id']; ?>)">
                                               <i class="fas fa-ellipsis-v"></i>
                                           </button>
                                           <div id="menu-<?php echo $lesson['id']; ?>" class="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg border border-gray-200 hidden z-10">
                                               <a href="lesson_editor.php?course_id=<?php echo $courseId; ?>&lesson_id=<?php echo $lesson['id']; ?>" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
                                                   <i class="fas fa-edit mr-2"></i>Edit
                                               </a>
                                               <button onclick="deleteLesson(<?php echo $lesson['id']; ?>, '<?php echo htmlspecialchars($lesson['title']); ?>')" class="block w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-gray-100">
                                                   <i class="fas fa-trash mr-2"></i>Delete
                                               </button>
                                           </div>
                                       </div>
                                   </div>
                               </div>
                           <?php endforeach; ?>
                       </div>
                   <?php endif; ?>
               </div>

               <!-- Enrollments Tab -->
               <div id="enrollments-tab" class="tab-content">
                   <h3 class="text-xl font-semibold text-gray-800 mb-6">Student Enrollments</h3>
                   <div id="enrollments-container">
                       <!-- Enrollments will be loaded here -->
                   </div>
               </div>
           </div>
       </div>
   </div>
</div>

<!-- Add Module Modal -->
<div id="addModuleModal" 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">Add Module</h3>
            <button onclick="closeAddModuleModal()" 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="add_module">
                <div class="mb-4">
                    <label for="moduleTitle" class="block text-sm font-medium text-gray-700 mb-2">Module 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="moduleTitle" name="module_title" required>
                </div>
                <div class="mb-4">
                    <label for="moduleDescription" class="block text-sm font-medium text-gray-700 mb-2">Description</label>
                    <textarea class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" id="moduleDescription" name="module_description" rows="3"></textarea>
                </div>
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label for="moduleSortOrder" class="block text-sm font-medium text-gray-700 mb-2">Sort Order</label>
                        <input type="number" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" id="moduleSortOrder" name="module_sort_order" min="1" value="1">
                    </div>
                    <div>
                        <label for="moduleEstimatedTime" class="block text-sm font-medium text-gray-700 mb-2">Estimated Time (min)</label>
                        <input type="number" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" id="moduleEstimatedTime" name="module_estimated_time" min="0" value="0">
                    </div>
                </div>
            </div>
            <div class="flex justify-end space-x-3 p-6 border-t border-gray-200">
                <button type="button" onclick="closeAddModuleModal()" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition duration-150">Cancel</button>
                <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition duration-150">Add 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 will also remove all lessons associated with this module.</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 Lesson Modal -->
<div id="addLessonModal" class="fixed inset-0 bg-gray-900 bg-opacity-50 hidden items-center justify-center z-50">
    <div class="bg-white rounded-lg shadow-2xl max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
        <div class="flex justify-between items-center p-6 border-b border-gray-200">
            <h3 class="text-xl font-bold text-gray-800">Add Lesson</h3>
            <button onclick="closeAddLessonModal()" 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="add_lesson">
                <div class="mb-4">
                    <label for="lessonTitle" class="block text-sm font-medium text-gray-700 mb-2">Lesson Title *</label>
                    <input type="text" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" id="lessonTitle" name="lesson_title" required>
                </div>
                <div class="mb-4">
                    <label for="lessonDescription" class="block text-sm font-medium text-gray-700 mb-2">Description</label>
                    <textarea class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" id="lessonDescription" name="lesson_description" rows="3"></textarea>
                </div>
                <div class="grid grid-cols-2 gap-4 mb-4">
                    <div>
                        <label for="lessonType" class="block text-sm font-medium text-gray-700 mb-2">Lesson Type</label>
                        <select class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" id="lessonType" name="lesson_type">
                            <option value="text">Text</option>
                            <option value="video">Video</option>
                            <option value="quiz">Quiz</option>
                            <option value="assignment">Assignment</option>
                            <option value="resource">Resource</option>
                        </select>
                    </div>
                    <div>
                        <label for="estimatedTime" class="block text-sm font-medium text-gray-700 mb-2">Estimated Time (minutes)</label>
                        <input type="number" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" id="estimatedTime" name="estimated_time" min="1" value="30">
                    </div>
                </div>
                <div class="mb-4">
                    <label for="sortOrder" class="block text-sm font-medium text-gray-700 mb-2">Sort Order</label>
                    <input type="number" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" id="sortOrder" name="sort_order" min="1" value="<?php echo count($lessons) + 1; ?>">
                </div>
                <div class="mb-4">
                    <label for="lessonContent" class="block text-sm font-medium text-gray-700 mb-2">Content</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="lessonContent" name="lesson_content" rows="8"></textarea>
                </div>
                <div class="mb-4">
                    <label class="flex items-center">
                        <input type="checkbox" class="mr-2" id="isPreview" name="is_preview">
                        <span class="text-sm text-gray-700">Allow preview (visible to non-enrolled students)</span>
                    </label>
                </div>
            </div>
            <div class="flex justify-end space-x-3 p-6 border-t border-gray-200">
                <button type="button" onclick="closeAddLessonModal()" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition duration-150">Cancel</button>
                <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition duration-150">Add 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>

<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
    if (tabName === 'modules') {
        loadModules();
    } else if (tabName === 'enrollments') {
        loadEnrollments();
    }
}

// Modal functions
function openAddModuleModal() {
    document.getElementById('addModuleModal').classList.remove('hidden');
    document.getElementById('addModuleModal').classList.add('flex');
}

function closeAddModuleModal() {
    document.getElementById('addModuleModal').classList.add('hidden');
    document.getElementById('addModuleModal').classList.remove('flex');
}

function openAddLessonModal() {
    document.getElementById('addLessonModal').classList.remove('hidden');
    document.getElementById('addLessonModal').classList.add('flex');
}

function closeAddLessonModal() {
    document.getElementById('addLessonModal').classList.add('hidden');
    document.getElementById('addLessonModal').classList.remove('flex');
}

function closeDeleteModuleModal() {
    document.getElementById('deleteModuleModal').classList.add('hidden');
    document.getElementById('deleteModuleModal').classList.remove('flex');
}

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

// Lesson menu toggle
function toggleLessonMenu(lessonId) {
    const menu = document.getElementById('menu-' + lessonId);
    // Hide all other menus first
    document.querySelectorAll('[id^="menu-"]').forEach(m => {
        if (m.id !== 'menu-' + lessonId) m.classList.add('hidden');
    });
    menu.classList.toggle('hidden');
}

// Close menus when clicking outside
document.addEventListener('click', function(e) {
    if (!e.target.closest('.relative')) {
        document.querySelectorAll('[id^="menu-"]').forEach(m => m.classList.add('hidden'));
    }
});

function editLesson(lessonId) {
    // Redirect to lesson edit page or open modal
    window.location.href = `lesson_editor.php?course_id=<?php echo $courseId; ?>&lesson_id=${lessonId}`;
}

function deleteLesson(lessonId, title) {
    document.getElementById('deleteLessonId').value = lessonId;
    document.getElementById('deleteLessonTitle').textContent = title;
    document.getElementById('deleteLessonModal').classList.remove('hidden');
    document.getElementById('deleteLessonModal').classList.add('flex');
}

function deleteModule(moduleId, title) {
    document.getElementById('deleteModuleId').value = moduleId;
    document.getElementById('deleteModuleTitle').textContent = title;
    document.getElementById('deleteModuleModal').classList.remove('hidden');
    document.getElementById('deleteModuleModal').classList.add('flex');
}

function loadModules() {
    const container = document.getElementById('modules-list');
    container.innerHTML = '<div class="text-center py-8"><div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div></div>';

    fetch(`../../api/modules.php?course_id=<?php echo $courseId; ?>`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                let html = '';

                if (data.modules.length === 0) {
                    html = `
                        <div class="text-center py-12">
                            <i class="fas fa-folder text-6xl text-gray-400 mb-4"></i>
                            <h4 class="text-xl font-semibold text-gray-800 mb-2">No modules yet</h4>
                            <p class="text-gray-500">Organize your course content into modules.</p>
                        </div>
                    `;
                } else {
                    data.modules.forEach(module => {
                        html += `
                            <div class="bg-white border border-gray-200 rounded-lg p-6 mb-4 shadow-sm">
                                <div class="flex justify-between items-start">
                                    <div class="flex-1">
                                        <h4 class="text-lg font-semibold text-gray-800 mb-2">${module.title}</h4>
                                        ${module.description ? `<p class="text-gray-600 text-sm mb-3">${module.description}</p>` : ''}
                                        <div class="flex items-center space-x-2">
                                            <span class="px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded-full">Module ${module.sort_order}</span>
                                            <span class="text-gray-500 text-sm">${module.estimated_time} min estimated</span>
                                        </div>
                                    </div>
                                    <div class="relative">
                                        <button class="p-2 text-gray-400 hover:text-gray-600" onclick="toggleModuleMenu(${module.id})">
                                            <i class="fas fa-ellipsis-v"></i>
                                        </button>
                                        <div id="module-menu-${module.id}" class="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg border border-gray-200 hidden z-10">
                                            <button onclick="editModule(${module.id})" class="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
                                                <i class="fas fa-edit mr-2"></i>Edit
                                            </button>
                                            <button onclick="deleteModule(${module.id}, '${module.title.replace(/'/g, "\\'")}')" class="block w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-gray-100">
                                                <i class="fas fa-trash mr-2"></i>Delete
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        `;
                    });
                }

                container.innerHTML = html;
            } else {
                container.innerHTML = '<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">Error loading modules.</div>';
            }
        })
        .catch(error => {
            container.innerHTML = '<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">Error loading modules.</div>';
        });
}

function toggleModuleMenu(moduleId) {
    const menu = document.getElementById('module-menu-' + moduleId);
    // Hide all other menus first
    document.querySelectorAll('[id^="module-menu-"]').forEach(m => {
        if (m.id !== 'module-menu-' + moduleId) m.classList.add('hidden');
    });
    menu.classList.toggle('hidden');
}

function editModule(moduleId) {
    // Implementation for editing modules
    alert('Module editing will be implemented.');
}

function loadEnrollments() {
    const container = document.getElementById('enrollments-container');
    const courseId = <?php echo $courseId; ?>;
    console.log('Loading enrollments for course ID:', courseId);
    container.innerHTML = '<div class="text-center py-8"><div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div></div>';

    fetch(`../../api/enrollments.php?course_id=${courseId}`)
        .then(response => {
            console.log('API Response status:', response.status);
            console.log('API Response headers:', response.headers);
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('API Response data:', data);
            if (data.success) {
                if (data.enrollments && data.enrollments.length > 0) {
                    let html = `
                        <div class="overflow-x-auto">
                            <table class="min-w-full divide-y divide-gray-200">
                                <thead class="bg-gray-50">
                                    <tr>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Student</th>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Email</th>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Enrollment Date</th>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Progress</th>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                    </tr>
                                </thead>
                                <tbody class="bg-white divide-y divide-gray-200">
                    `;

                    data.enrollments.forEach(enrollment => {
                        const statusClasses = {
                            'completed': 'bg-green-100 text-green-800',
                            'in_progress': 'bg-blue-100 text-blue-800',
                            'enrolled': 'bg-blue-100 text-blue-800',
                            'dropped': 'bg-red-100 text-red-800'
                        };
                        html += `
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${enrollment.first_name && enrollment.last_name ? enrollment.first_name + ' ' + enrollment.last_name : enrollment.username}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${enrollment.email}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${new Date(enrollment.enrollment_date).toLocaleDateString()}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${enrollment.progress_percentage}%</td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${statusClasses[enrollment.status] || 'bg-gray-100 text-gray-800'}">
                                        ${enrollment.status.replace('_', ' ')}
                                    </span>
                                </td>
                            </tr>
                        `;
                    });

                    html += '</tbody></table></div>';
                    container.innerHTML = html;
                } else {
                    container.innerHTML = `
                        <div class="text-center py-12">
                            <i class="fas fa-users text-6xl text-gray-400 mb-4"></i>
                            <h4 class="text-xl font-semibold text-gray-800 mb-2">No enrollments yet</h4>
                            <p class="text-gray-500">Students haven't enrolled in this course yet.</p>
                        </div>
                    `;
                }
            } else {
                container.innerHTML = `<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">Error: ${data.error || 'Unknown error loading enrollments.'}</div>`;
            }
        })
        .catch(error => {
            console.error('Error loading enrollments:', error);
            container.innerHTML = '<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">Error loading enrollments. Please check the console for details.</div>';
        });
}

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

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

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

</body>
</html>