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

$page_title = 'Create Course - ' . $lms_config['lms']['site_name'];

// Get categories for dropdown
$stmt = $db->query("SELECT * FROM course_categories WHERE is_active = 1 ORDER BY name");
$categories = $stmt->fetchAll();

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $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'];

    // Auto-generate slug if empty
    if (empty($slug)) {
        $baseSlug = strtolower(preg_replace('/[^a-zA-Z0-9\-]/', '', str_replace(' ', '-', $title)));
        $slug = $baseSlug;
        $counter = 1;

        // Check if slug exists and append number if needed
        while (true) {
            $stmt = $db->prepare("SELECT COUNT(*) FROM courses WHERE slug = ?");
            $stmt->execute([$slug]);
            $count = $stmt->fetchColumn();

            if ($count == 0) {
                break; // Slug is unique
            }

            $slug = $baseSlug . '-' . $counter;
            $counter++;

            // Prevent infinite loop
            if ($counter > 100) {
                $slug = $baseSlug . '-' . time();
                break;
            }
        }
    }

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

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

            // Insert course
            $stmt = $db->prepare("INSERT INTO courses (title, slug, description, short_description, instructor_id, category_id, thumbnail, banner_image, price, currency, level, duration_hours, language, max_students, prerequisites, learning_objectives, tags, status, is_featured, is_free, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");

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

            $courseId = $db->lastInsertId();

            $message = 'Course created successfully! <a href="edit.php?id=' . $courseId . '" class="text-blue-600 hover:text-blue-800">Add curriculum and content</a>';

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

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

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

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

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

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

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

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

        /* Rating Stars */
        .rating .fas.fa-star {
            color: #ddd; /* Unfilled */
        }
        .rating .fas.fa-star.filled {
            color: #ffc107; /* Filled (Yellow/Gold) */
        }
    </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">
    <!-- Sidebar Navigation (Desktop View) -->
    <aside class="hidden lg:block w-64 bg-white border-r border-accent-subtle p-6 shadow-sm sticky top-16 h-screen">
        <div class="flex flex-col h-full">
            <!-- Logo/Title -->
            <div class="text-xl font-extrabold text-primary-blue mb-10 tracking-wider">
                <?php echo htmlspecialchars($lms_config['lms']['site_name']); ?>
            </div>

            <!-- Navigation Links -->
            <nav class="space-y-2 flex-grow">
                <a href="../dashboard.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <span class="w-5 h-5">🏠</span>
                    <span>Dashboard</span>
                </a>
                <a href="index.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <span class="w-5 h-5">📚</span>
                    <span>My Courses</span>
                </a>
                <a href="new.php" class="flex items-center space-x-3 p-3 rounded-lg bg-primary-blue text-white font-semibold transition duration-150 shadow-md">
                    <span class="w-5 h-5">➕</span>
                    <span>Create Course</span>
                </a>
                <a href="../questions/index.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <span class="w-5 h-5">❓</span>
                    <span>Question Bank</span>
                </a>
                <a href="../exams/index.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <span class="w-5 h-5">📝</span>
                    <span>Exams & Quizzes</span>
                </a>
                <a href="../students.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <span class="w-5 h-5">👥</span>
                    <span>My Students</span>
                </a>
                <a href="../resources.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <span class="w-5 h-5">📖</span>
                    <span>Resources</span>
                </a>
                <a href="../grading/index.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <span class="w-5 h-5">🏆</span>
                    <span>Grades</span>
                </a>
                <a href="../../logout.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <span class="w-5 h-5">🚪</span>
                    <span>Logout</span>
                </a>
            </nav>

            <!-- Footer/User Info (Bottom of Sidebar) -->
            <div class="mt-8 pt-4 border-t border-accent-subtle">
                <p class="text-xs text-gray-500 mb-2">Authenticated User:</p>
                <p class="text-xs text-gray-700 truncate font-mono bg-accent-subtle p-1 rounded"><?php echo htmlspecialchars($user['username'] ?? 'Instructor'); ?></p>
            </div>
        </div>
    </aside>

    <!-- 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">Create Course</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">

        <!-- Mobile Navigation Overlay (Hidden by default) -->
        <div id="mobileMenu" class="fixed inset-0 bg-white z-20 p-6 transform -translate-x-full transition-transform duration-300 lg:hidden">
            <div class="flex justify-between items-center mb-10">
                <div class="text-xl font-extrabold text-primary-blue tracking-wider"><?php echo htmlspecialchars($lms_config['lms']['site_name']); ?></div>
                <button id="closeMobileMenu" class="text-3xl text-text-dark">&times;</button>
            </div>
            <nav class="space-y-4">
                <a href="../dashboard.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">🏠 Dashboard</a>
                <a href="index.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📚 My Courses</a>
                <a href="new.php" class="block p-3 rounded-lg bg-primary-blue text-white font-semibold">➕ Create Course</a>
                <a href="../questions/index.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">❓ Question Bank</a>
                <a href="../exams/index.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📝 Exams & Quizzes</a>
                <a href="../students.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">👥 My Students</a>
                <a href="../resources.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📖 Resources</a>
                <a href="../grading/index.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">🏆 Grades</a>
                <a href="../../logout.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">🚪 Logout</a>
            </nav>
        </div>

        <!-- Create Course Form -->
        <div class="p-6">
            <div class="dashboard-section bg-white p-6 rounded-xl shadow-lg border border-accent-subtle">
                <div class="mb-6">
                    <h2 class="text-3xl font-bold text-gray-900">Create New Course</h2>
                </div>

                <!-- Alerts -->
                <?php if ($message): ?>
                    <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
                        <?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-4">
                        <?php echo htmlspecialchars($error); ?>
                    </div>
                <?php endif; ?>

                <form method="POST" enctype="multipart/form-data" class="space-y-6">
                    <!-- Basic Information -->
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <h2 class="text-xl font-semibold text-gray-800 mb-4">Basic Information</h2>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label for="title" class="block text-sm font-medium text-gray-700 mb-1">Course Title *</label>
                                <input type="text" class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500" id="title" name="title" required>
                            </div>
                            <div>
                                <label for="slug" class="block text-sm font-medium text-gray-700 mb-1">URL Slug</label>
                                <input type="text" class="w-full border border-gray-300 rounded-md px-3 py-2" id="slug" name="slug" placeholder="auto-generated-from-title">
                            </div>
                        </div>
                        <div class="mt-4">
                            <label for="shortDescription" class="block text-sm font-medium text-gray-700 mb-1">Short Description</label>
                            <textarea class="w-full border border-gray-300 rounded-md px-3 py-2" id="shortDescription" name="short_description" rows="3"></textarea>
                        </div>
                        <div class="mt-4">
                            <label for="description" class="block text-sm font-medium text-gray-700 mb-1">Full Description *</label>
                            <textarea class="w-full border border-gray-300 rounded-md px-3 py-2" id="description" name="description" rows="6" required></textarea>
                        </div>
                    </div>

                    <!-- Course Details -->
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <h2 class="text-xl font-semibold text-gray-800 mb-4">Course Details</h2>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label for="category" class="block text-sm font-medium text-gray-700 mb-1">Category</label>
                                <select class="w-full border border-gray-300 rounded-md px-3 py-2" id="category" name="category_id">
                                    <option value="">Select Category</option>
                                    <?php foreach ($categories as $category): ?>
                                        <option value="<?php echo $category['id']; ?>"><?php echo htmlspecialchars($category['name']); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div>
                                <label for="level" class="block text-sm font-medium text-gray-700 mb-1">Difficulty Level</label>
                                <select class="w-full border border-gray-300 rounded-md px-3 py-2" id="level" name="level" required>
                                    <option value="beginner">Beginner</option>
                                    <option value="intermediate">Intermediate</option>
                                    <option value="advanced">Advanced</option>
                                </select>
                            </div>
                            <div>
                                <label for="language" class="block text-sm font-medium text-gray-700 mb-1">Language</label>
                                <input type="text" class="w-full border border-gray-300 rounded-md px-3 py-2" id="language" name="language" value="English" required>
                            </div>
                            <div>
                                <label for="duration" class="block text-sm font-medium text-gray-700 mb-1">Duration (hours)</label>
                                <input type="number" class="w-full border border-gray-300 rounded-md px-3 py-2" id="duration" name="duration_hours" min="1" value="10" required>
                            </div>
                        </div>
                        <div class="mt-4">
                            <label for="prerequisites" class="block text-sm font-medium text-gray-700 mb-1">Prerequisites</label>
                            <textarea class="w-full border border-gray-300 rounded-md px-3 py-2" id="prerequisites" name="prerequisites" rows="3"></textarea>
                        </div>
                        <!-- Learning Objectives -->
                        <div class="mt-4">
                            <label class="block text-sm font-medium text-gray-700 mb-1">Learning Objectives</label>
                            <div id="objectives-container">
                                <div class="flex gap-2 mb-2">
                                    <input type="text" class="flex-1 border border-gray-300 rounded-md px-3 py-2" name="learning_objectives[]" placeholder="What will students learn?">
                                    <button type="button" class="bg-red-500 text-white px-3 py-2 rounded-md hidden remove-objective">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                            <button type="button" class="bg-blue-500 text-white px-4 py-2 rounded-md mt-2" id="add-objective">
                                <i class="fas fa-plus mr-1"></i>Add Objective
                            </button>
                        </div>
                        <!-- Tags -->
                        <div class="mt-4">
                            <label class="block text-sm font-medium text-gray-700 mb-1">Tags</label>
                            <input type="text" class="w-full border border-gray-300 rounded-md px-3 py-2" name="tags_input" id="tags-input" placeholder="Enter tags separated by commas">
                            <div id="tags-container" class="mt-2"></div>
                        </div>
                    </div>

                    <!-- Pricing & Settings -->
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <h2 class="text-xl font-semibold text-gray-800 mb-4">Pricing & Settings</h2>
                        <div class="flex items-center mb-4">
                            <input type="checkbox" class="mr-2" id="isFree" name="is_free" checked>
                            <label for="isFree" class="text-sm font-medium text-gray-700">Free Course</label>
                        </div>
                        <div id="pricing-fields" class="hidden">
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label for="price" class="block text-sm font-medium text-gray-700 mb-1">Price</label>
                                    <div class="flex">
                                        <span class="inline-flex items-center px-3 py-2 border border-r-0 border-gray-300 bg-gray-50 text-gray-500 text-sm rounded-l-md">$</span>
                                        <input type="number" class="flex-1 border border-gray-300 rounded-r-md px-3 py-2" id="price" name="price" min="0" step="0.01" value="0.00">
                                    </div>
                                </div>
                                <div>
                                    <label for="currency" class="block text-sm font-medium text-gray-700 mb-1">Currency</label>
                                    <select class="w-full border border-gray-300 rounded-md px-3 py-2" id="currency" name="currency">
                                        <option value="USD">USD</option>
                                        <option value="EUR">EUR</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="mt-4">
                            <label for="maxStudents" class="block text-sm font-medium text-gray-700 mb-1">Maximum Students</label>
                            <input type="number" class="w-full border border-gray-300 rounded-md px-3 py-2" id="maxStudents" name="max_students" min="1" placeholder="Unlimited">
                        </div>
                        <div class="mt-4">
                            <label for="status" class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                            <select class="w-full border border-gray-300 rounded-md px-3 py-2" id="status" name="status" required>
                                <option value="draft">Draft (not visible to students)</option>
                                <option value="published">Published (visible to students)</option>
                            </select>
                        </div>
                        <div class="flex items-center mt-4">
                            <input type="checkbox" class="mr-2" id="isFeatured" name="is_featured">
                            <label for="isFeatured" class="text-sm font-medium text-gray-700">Featured Course</label>
                        </div>
                    </div>

                    <!-- Media -->
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <h2 class="text-xl font-semibold text-gray-800 mb-4">Media</h2>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label for="thumbnail" class="block text-sm font-medium text-gray-700 mb-1">Course Thumbnail</label>
                                <input type="file" class="w-full border border-gray-300 rounded-md px-3 py-2" id="thumbnail" name="thumbnail" accept="image/*">
                                <p class="text-xs text-gray-500 mt-1">Recommended: 1280x720px, JPG/PNG</p>
                            </div>
                            <div>
                                <label for="bannerImage" class="block text-sm font-medium text-gray-700 mb-1">Banner Image</label>
                                <input type="file" class="w-full border border-gray-300 rounded-md px-3 py-2" id="bannerImage" name="banner_image" accept="image/*">
                                <p class="text-xs text-gray-500 mt-1">Optional banner for course header</p>
                            </div>
                        </div>
                    </div>

                    <div class="flex justify-end">
                        <button type="submit" class="bg-blue-600 text-white px-6 py-3 rounded-lg hover:bg-blue-700 transition font-medium">
                            <i class="fas fa-save mr-2"></i>Create Course
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </main>
</div>

<!-- Custom Confirmation Modal (Hidden by default) -->
<div id="confirmation-modal" class="fixed inset-0 bg-gray-900 bg-opacity-50 hidden items-center justify-center z-50">
    <div class="bg-white p-6 rounded-lg shadow-2xl max-w-sm w-full transform transition-all">
        <h3 class="text-xl font-bold text-gray-800 mb-4" id="modal-title">Confirm Action</h3>
        <p class="text-gray-600 mb-6" id="modal-message">Are you sure you want to perform this action?</p>
        <div class="flex justify-end space-x-3">
            <button id="modal-cancel" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 transition">Cancel</button>
            <button id="modal-confirm" class="px-4 py-2 text-white rounded-md transition"></button>
        </div>
    </div>
</div>


<script>
    // --- UI/Utility Functions ---

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    // Auto-generate slug
    document.getElementById('title').addEventListener('input', function() {
        const title = this.value;
        const baseSlug = title.toLowerCase().replace(/[^a-z0-9\s-]/g, '').replace(/\s+/g, '-').replace(/-+/g, '-').trim('-');
        // Note: PHP will handle uniqueness on the server side
        document.getElementById('slug').value = baseSlug;
    });

    // Toggle pricing
    document.getElementById('isFree').addEventListener('change', function() {
        document.getElementById('pricing-fields').classList.toggle('hidden', this.checked);
    });

    // Objectives
    document.getElementById('add-objective').addEventListener('click', function() {
        const container = document.getElementById('objectives-container');
        const div = document.createElement('div');
        div.className = 'flex gap-2 mb-2';
        div.innerHTML = '<input type="text" class="flex-1 border border-gray-300 rounded-md px-3 py-2" name="learning_objectives[]" placeholder="What will students learn?"><button type="button" class="bg-red-500 text-white px-3 py-2 rounded-md remove-objective"><i class="fas fa-trash"></i></button>';
        container.appendChild(div);
        updateRemoveButtons();
    });

    document.getElementById('objectives-container').addEventListener('click', function(e) {
        if (e.target.classList.contains('remove-objective') || e.target.parentElement.classList.contains('remove-objective')) {
            e.target.closest('.flex').remove();
            updateRemoveButtons();
        }
    });

    function updateRemoveButtons() {
        const objectives = document.querySelectorAll('#objectives-container .flex');
        objectives.forEach((obj, index) => {
            const btn = obj.querySelector('.remove-objective');
            btn.classList.toggle('hidden', objectives.length <= 1);
        });
    }

    // Tags
    let tags = [];
    document.getElementById('tags-input').addEventListener('keydown', function(e) {
        if (e.key === 'Enter' || e.key === ',') {
            e.preventDefault();
            const tag = this.value.trim();
            if (tag && !tags.includes(tag)) {
                tags.push(tag);
                updateTagsDisplay();
                this.value = '';
            }
        }
    });

    function updateTagsDisplay() {
        const container = document.getElementById('tags-container');
        container.innerHTML = '';
        tags.forEach((tag, index) => {
            const span = document.createElement('span');
            span.className = 'inline-block bg-blue-100 text-blue-800 px-2 py-1 rounded mr-2 mb-2';
            span.innerHTML = `${tag} <button type="button" class="ml-1 text-red-500" onclick="removeTag(${index})">&times;</button>`;
            container.appendChild(span);
        });
        // Hidden inputs
        tags.forEach(tag => {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'tags[]';
            input.value = tag;
            container.appendChild(input);
        });
    }

    function removeTag(index) {
        tags.splice(index, 1);
        updateTagsDisplay();
    }
</script>
</body>
</html>