<?php 
ini_set('display_errors', 1); error_reporting(E_ALL);
require_once '../db_connect.php'; 
include 'includes/header.php'; 
include 'includes/sidebar.php'; 

$success_msg = ''; $error_msg = '';
$selected_course_id = isset($_GET['course_id']) ? (int)$_GET['course_id'] : 0;

// ==========================================
// 1. DELETE LOGIC (WITH ERROR HANDLING)
// ==========================================
if (isset($_GET['delete_lesson'])) {
    try {
        $pdo->prepare("DELETE FROM lessons WHERE id = ?")->execute([$_GET['delete_lesson']]);
        $success_msg = "Lesson deleted successfully!";
    } catch (Exception $e) {
        $error_msg = "Could not delete lesson. Error: " . $e->getMessage();
    }
}
if (isset($_GET['delete_module'])) {
    try {
        $pdo->prepare("DELETE FROM modules WHERE id = ?")->execute([$_GET['delete_module']]);
        $success_msg = "Module deleted successfully!";
    } catch (Exception $e) {
        $error_msg = "Cannot delete module! Please delete all the lessons inside this module first.";
    }
}

// ==========================================
// 2. ADD & EDIT MODULE
// ==========================================
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_module'])) {
    try {
        $pdo->prepare("INSERT INTO modules (course_id, title) VALUES (?, ?)")->execute([$_POST['course_id'], trim($_POST['module_title'])]);
        $success_msg = "Module added successfully!";
        $selected_course_id = (int)$_POST['course_id'];
    } catch (Exception $e) { $error_msg = "Error adding module: " . $e->getMessage(); }
}

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['edit_module'])) {
    try {
        $pdo->prepare("UPDATE modules SET title = ? WHERE id = ?")->execute([trim($_POST['module_title']), $_POST['module_id']]);
        $success_msg = "Module updated successfully!";
        $selected_course_id = (int)$_POST['course_id'];
    } catch (Exception $e) { $error_msg = "Error updating module: " . $e->getMessage(); }
}

// ==========================================
// 3. ADD & EDIT LESSON
// ==========================================
// Add Lesson
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_lesson'])) {
    $resource_url = null;
    if (isset($_FILES['resource_file']) && $_FILES['resource_file']['error'] == 0) {
        $upload_dir = '../uploads/resources/';
        if (!file_exists($upload_dir)) { mkdir($upload_dir, 0777, true); }
        $ext = strtolower(pathinfo($_FILES['resource_file']['name'], PATHINFO_EXTENSION));
        $file_name = "res_" . time() . "_" . rand(1000, 9999) . "." . $ext;
        if (move_uploaded_file($_FILES["resource_file"]["tmp_name"], $upload_dir . $file_name)) {
            $resource_url = 'uploads/resources/' . $file_name;
        }
    }
    try {
        $stmt = $pdo->prepare("INSERT INTO lessons (module_id, title, video_url, duration, notes, resource_url) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([$_POST['module_id'], trim($_POST['lesson_title']), trim($_POST['video_url']), trim($_POST['duration']), trim($_POST['notes']), $resource_url]);
        $success_msg = "Lesson added successfully!";
        $selected_course_id = (int)$_POST['course_id'];
    } catch (Exception $e) { $error_msg = "Error adding lesson: " . $e->getMessage(); }
}

// Edit Lesson
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['edit_lesson'])) {
    $lesson_id = $_POST['lesson_id'];
    $resource_url = null;
    
    if (isset($_FILES['resource_file']) && $_FILES['resource_file']['error'] == 0) {
        $upload_dir = '../uploads/resources/';
        if (!file_exists($upload_dir)) { mkdir($upload_dir, 0777, true); }
        $ext = strtolower(pathinfo($_FILES['resource_file']['name'], PATHINFO_EXTENSION));
        $file_name = "res_" . time() . "_" . rand(1000, 9999) . "." . $ext;
        if (move_uploaded_file($_FILES["resource_file"]["tmp_name"], $upload_dir . $file_name)) {
            $resource_url = 'uploads/resources/' . $file_name;
        }
    }

    try {
        if ($resource_url) {
            $stmt = $pdo->prepare("UPDATE lessons SET title=?, video_url=?, duration=?, notes=?, resource_url=? WHERE id=?");
            $stmt->execute([trim($_POST['lesson_title']), trim($_POST['video_url']), trim($_POST['duration']), trim($_POST['notes']), $resource_url, $lesson_id]);
        } else {
            $stmt = $pdo->prepare("UPDATE lessons SET title=?, video_url=?, duration=?, notes=? WHERE id=?");
            $stmt->execute([trim($_POST['lesson_title']), trim($_POST['video_url']), trim($_POST['duration']), trim($_POST['notes']), $lesson_id]);
        }
        $success_msg = "Lesson updated successfully!";
        $selected_course_id = (int)$_POST['course_id'];
    } catch (Exception $e) { $error_msg = "Error updating lesson: " . $e->getMessage(); }
}

// Fetch Data
$courses = $pdo->query("SELECT id, title FROM courses WHERE status='active'")->fetchAll(PDO::FETCH_ASSOC);

$curriculum = [];
if ($selected_course_id) {
    $mod_stmt = $pdo->prepare("SELECT * FROM modules WHERE course_id = ? ORDER BY id ASC");
    $mod_stmt->execute([$selected_course_id]);
    $modules = $mod_stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($modules as $mod) {
        $les_stmt = $pdo->prepare("SELECT * FROM lessons WHERE module_id = ? ORDER BY id ASC");
        $les_stmt->execute([$mod['id']]);
        $curriculum[] = [
            'module' => $mod,
            'lessons' => $les_stmt->fetchAll(PDO::FETCH_ASSOC)
        ];
    }
}
?>

<style>
    :root { --theme-green: #064e3b; --theme-dark: #022c22; --theme-gold: #d4af37; --bg-soft: #f8fafc; }
    .main-content { background-color: var(--bg-soft); min-height: 100vh; padding-bottom: 50px; font-family: 'Outfit', sans-serif; }
    
    /* Header & Mobile Menu */
    .dashboard-header { background: #fff; padding: 20px 30px; border-radius: 20px; box-shadow: 0 5px 20px rgba(0,0,0,0.03); margin-bottom: 25px; border-left: 6px solid var(--theme-green); }
    #sidebarToggle { display: none; width: 45px; height: 45px; border-radius: 12px; background: #f1f5f9; border: 1px solid #e2e8f0; color: var(--theme-green); cursor: pointer; transition: 0.3s; display: inline-flex; align-items: center; justify-content: center; }
    #sidebarToggle:hover { background: var(--theme-green); color: #fff; }
    
    .btn-theme { background: var(--theme-green); color: #fff; border-radius: 12px; padding: 12px 24px; font-weight: 700; border: none; transition: 0.3s; display: inline-flex; align-items: center; justify-content: center; text-decoration: none; }
    .btn-theme:hover { background: var(--theme-dark); color: var(--theme-gold); transform: translateY(-2px); box-shadow: 0 8px 15px rgba(6, 78, 59, 0.2); }

    /* Content Cards & Accordion */
    .content-card { background: #fff; border-radius: 20px; border: 1px solid #e2e8f0; padding: 25px; box-shadow: 0 10px 40px rgba(0,0,0,0.02); }
    .accordion-button { font-weight: 800; color: var(--theme-dark); background-color: #f8fafc; border: 1px solid #e2e8f0; border-radius: 12px !important; padding: 18px 25px; transition: 0.3s; }
    .accordion-button:not(.collapsed) { background-color: rgba(212, 175, 55, 0.1); color: var(--theme-green); box-shadow: none; border-color: rgba(212, 175, 55, 0.4); border-bottom-left-radius: 0 !important; border-bottom-right-radius: 0 !important; }
    .accordion-button:focus { box-shadow: none; }
    .accordion-item { border: none; background: transparent; margin-bottom: 15px; position: relative; }
    .accordion-body { border: 1px solid #e2e8f0; border-top: none; border-bottom-left-radius: 12px; border-bottom-right-radius: 12px; background: #fff; padding: 20px; }
    
    /* Lesson Boxes */
    .lesson-box { background: #fff; border: 1px solid #e2e8f0; padding: 15px 20px; border-radius: 12px; margin-bottom: 12px; display: flex; justify-content: space-between; align-items: center; transition: 0.3s; border-left: 4px solid var(--theme-green); flex-wrap: wrap; gap: 15px; }
    .lesson-box:hover { box-shadow: 0 5px 20px rgba(0,0,0,0.04); transform: translateX(5px); border-color: #cbd5e1; border-left-color: var(--theme-gold); }
    .lesson-title { font-weight: 800; color: var(--theme-dark); margin: 0; font-size: 15px; }
    .lesson-meta { font-size: 12px; color: #64748b; font-weight: 700; margin-top: 5px; display: flex; align-items: center; gap: 10px; }
    
    /* Actions */
    .module-actions { position: absolute; right: 55px; top: 12px; z-index: 10; display: flex; gap: 5px; }
    .action-icon { width: 34px; height: 34px; display: inline-flex; align-items: center; justify-content: center; border-radius: 8px; transition: 0.3s; text-decoration: none; border: none; cursor: pointer;}
    .action-icon.btn-edit { background: #f1f5f9; color: var(--theme-green); }
    .action-icon.btn-edit:hover { background: var(--theme-green); color: #fff; }
    .action-icon.btn-delete { background: #fef2f2; color: #ef4444; }
    .action-icon.btn-delete:hover { background: #ef4444; color: #fff; }
    
    /* Modals & Inputs */
    .modal-content { border-radius: 24px; border: none; box-shadow: 0 20px 50px rgba(0,0,0,0.1); }
    .modal-header { border-bottom: 1px solid #f1f5f9; padding: 20px 30px; }
    .modal-body { padding: 30px; }
    .form-control, .form-select { border-radius: 12px; border: 2px solid #f1f5f9; padding: 12px 15px; font-size: 14px; background: #f8fafc; transition: 0.3s; }
    .form-control:focus, .form-select:focus { border-color: var(--theme-green); background: #fff; box-shadow: 0 0 0 4px rgba(6, 78, 59, 0.1); }

    .empty-state { text-align: center; padding: 60px 20px; background: #fff; border-radius: 20px; border: 2px dashed #cbd5e1; }

    /* Animations */
    .fade-up { animation: fadeInUp 0.4s ease-out forwards; }
    @keyframes fadeInUp { 0% { opacity: 0; transform: translateY(15px); } 100% { opacity: 1; transform: translateY(0); } }

    /* 📱 Mobile Specific Styles */
    @media (max-width: 991.98px) {
        .main-content { padding: 15px !important; }
        .dashboard-header { padding: 20px; flex-direction: column; align-items: flex-start !important; gap: 15px; }
        .dashboard-header .header-top { width: 100%; display: flex; justify-content: flex-start; align-items: center; gap: 15px; }
        .header-title { font-size: 1.2rem; }
        .module-actions { position: relative; right: 0; top: 0; margin-bottom: 10px; width: 100%; justify-content: flex-end; padding-right: 10px; z-index: 1;}
        .accordion-button { padding-top: 35px; } /* Space for mobile actions */
        .lesson-box { flex-direction: column; align-items: flex-start; }
        .lesson-box .d-flex { width: 100%; justify-content: flex-end; border-top: 1px solid #f1f5f9; padding-top: 10px; }
    }
    @media (min-width: 992px) { #sidebarToggle { display: none !important; } }
</style>

<div class="main-content p-3 p-md-4">
    
    <div class="dashboard-header d-flex justify-content-between align-items-center fade-up">
        <div class="header-top">
            <button id="sidebarToggle" class="shadow-sm"><i class="fas fa-bars fs-5"></i></button>
            <div>
                <h4 class="mb-0 fw-bold text-dark header-title"><i class="fas fa-photo-video me-2" style="color: var(--theme-gold);"></i> Course Content</h4>
                <p class="text-muted fw-semibold mb-0 d-none d-md-block" style="font-size: 13px;">Manage modules, video lessons, and resources</p>
            </div>
        </div>
    </div>

    <?php if($success_msg): ?> 
        <div class="alert alert-success d-flex align-items-center mb-4 rounded-4 border-0 shadow-sm fade-up" style="border-left: 5px solid #10b981 !important;">
            <i class="fas fa-check-circle me-3 fa-2x text-success"></i> 
            <div><strong class="d-block text-success">Success!</strong><span class="text-muted small"><?= $success_msg ?></span></div>
        </div>
    <?php endif; ?>
    <?php if($error_msg): ?> 
        <div class="alert alert-danger d-flex align-items-center mb-4 rounded-4 border-0 shadow-sm fade-up" style="border-left: 5px solid #ef4444 !important;">
            <i class="fas fa-exclamation-triangle me-3 fa-2x text-danger"></i> 
            <div><strong class="d-block text-danger">Error!</strong><span class="text-muted small"><?= $error_msg ?></span></div>
        </div>
    <?php endif; ?>

    <div class="content-card mb-4 fade-up" style="animation-delay: 0.1s;">
        <form method="GET" action="manage_content.php" class="row g-3 align-items-end">
            <div class="col-md-9">
                <label class="form-label fw-bold text-muted small text-uppercase"><i class="fas fa-filter me-1"></i> Select Course to Manage</label>
                <select name="course_id" class="form-select border-2 fw-bold text-dark" onchange="this.form.submit()" required>
                    <option value="">-- Choose a Course --</option>
                    <?php foreach($courses as $c): ?>
                        <option value="<?= $c['id'] ?>" <?= $selected_course_id == $c['id'] ? 'selected' : '' ?>><?= htmlspecialchars($c['title']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <button type="submit" class="btn btn-dark w-100 py-2 fw-bold rounded-3" style="background: var(--theme-dark);"><i class="fas fa-sync-alt me-2"></i> Load Content</button>
            </div>
        </form>
    </div>

    <?php if ($selected_course_id): ?>
        <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center mb-4 fade-up" style="animation-delay: 0.2s;">
            <h5 class="fw-bold m-0 text-dark mb-3 mb-md-0"><i class="fas fa-list-ul me-2 text-muted"></i> Curriculum Builder</h5>
            <button class="btn-theme shadow-sm w-100-mobile" data-bs-toggle="modal" data-bs-target="#addModuleModal">
                <i class="fas fa-folder-plus me-2"></i> Add New Module
            </button>
        </div>

        <?php if(empty($curriculum)): ?>
            <div class="empty-state fade-up" style="animation-delay: 0.3s;">
                <i class="fas fa-box-open fa-3x text-muted opacity-25 mb-3 d-block"></i>
                <h5 class="fw-bold text-dark">No modules found!</h5>
                <p class="text-muted">Start building this course by adding the first module.</p>
            </div>
        <?php else: ?>
            <div class="accordion fade-up" id="curriculumAccordion" style="animation-delay: 0.3s;">
                <?php foreach($curriculum as $index => $item): $mod = $item['module']; $lessons = $item['lessons']; ?>
                    <div class="accordion-item shadow-sm">
                        <div class="module-actions">
                            <button type="button" class="action-icon btn-edit" onclick="editModule(<?= $mod['id'] ?>, '<?= htmlspecialchars(addslashes($mod['title'])) ?>')" title="Edit Module"><i class="fas fa-pen"></i></button>
                            <a href="?course_id=<?= $selected_course_id ?>&delete_module=<?= $mod['id'] ?>" class="action-icon btn-delete" onclick="return confirm('Are you sure? Delete all lessons inside this module first!')" title="Delete Module"><i class="fas fa-trash-alt"></i></a>
                        </div>
                        
                        <h2 class="accordion-header position-relative">
                            <button class="accordion-button <?= $index == 0 ? '' : 'collapsed' ?>" type="button" data-bs-toggle="collapse" data-bs-target="#collapse<?= $mod['id'] ?>">
                                <i class="fas fa-layer-group me-2 opacity-50"></i> <?= htmlspecialchars($mod['title']) ?>
                            </button>
                        </h2>
                        
                        <div id="collapse<?= $mod['id'] ?>" class="accordion-collapse collapse <?= $index == 0 ? 'show' : '' ?>" data-bs-parent="#curriculumAccordion">
                            <div class="accordion-body">
                                
                                <?php if(empty($lessons)): ?>
                                    <div class="text-center py-4 bg-light rounded-3 text-muted small fw-bold border"><i class="fas fa-info-circle me-1"></i> No lessons added yet.</div>
                                <?php else: foreach($lessons as $les): ?>
                                    <div class="lesson-box">
                                        <div>
                                            <h6 class="lesson-title"><i class="fas fa-play-circle text-success me-2"></i> <?= htmlspecialchars($les['title']) ?></h6>
                                            <div class="lesson-meta">
                                                <span><i class="far fa-clock text-primary"></i> <?= htmlspecialchars($les['duration']) ?: 'N/A' ?></span>
                                                <?php if($les['resource_url']): ?> 
                                                    <span class="badge bg-danger-subtle text-danger border border-danger-subtle rounded-pill"><i class="fas fa-file-pdf me-1"></i> PDF</span> 
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <div class="d-flex gap-2">
                                            <button type="button" class="btn btn-sm btn-light border fw-bold text-success" onclick="editLesson(<?= $les['id'] ?>, '<?= htmlspecialchars(addslashes($les['title'])) ?>', '<?= htmlspecialchars(addslashes($les['video_url'])) ?>', '<?= htmlspecialchars(addslashes($les['duration'])) ?>', '<?= htmlspecialchars(addslashes(preg_replace('/\r|\n/', '\\n', $les['notes']))) ?>')"><i class="fas fa-pen me-1"></i> Edit</button>
                                            <a href="?course_id=<?= $selected_course_id ?>&delete_lesson=<?= $les['id'] ?>" class="btn btn-sm btn-light border fw-bold text-danger" onclick="return confirm('Delete this lesson permanently?')"><i class="fas fa-trash-alt"></i></a>
                                        </div>
                                    </div>
                                <?php endforeach; endif; ?>

                                <div class="text-center mt-3 pt-3 border-top">
                                    <button class="btn btn-outline-success fw-bold rounded-pill border-2 px-4 shadow-sm" data-bs-toggle="modal" data-bs-target="#addLessonModal" onclick="document.getElementById('lesson_module_id').value = '<?= $mod['id'] ?>';">
                                        <i class="fas fa-plus-circle me-2"></i> Add Lesson to Module
                                    </button>
                                </div>

                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    <?php else: ?>
        <div class="empty-state fade-up" style="animation-delay: 0.2s;">
            <i class="fas fa-hand-pointer fa-3x text-muted opacity-25 mb-3 d-block"></i>
            <h5 class="fw-bold text-dark">Please select a course</h5>
            <p class="text-muted">Choose a course from the dropdown above to view and manage its curriculum.</p>
        </div>
    <?php endif; ?>
</div>

<div class="modal fade" id="addModuleModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <form method="POST">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold text-dark"><i class="fas fa-folder-plus text-success me-2"></i> Create New Module</h5>
                    <button type="button" class="btn-close shadow-none" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="course_id" value="<?= $selected_course_id ?>">
                    <label class="form-label small fw-bold text-uppercase text-muted">Module Title <span class="text-danger">*</span></label>
                    <div class="input-group">
                        <span class="input-group-text border-2 border-end-0 bg-light text-muted"><i class="fas fa-heading"></i></span>
                        <input type="text" name="module_title" class="form-control border-start-0 ps-0 fw-bold" placeholder="E.g. Section 1: Introduction" required>
                    </div>
                </div>
                <div class="modal-footer border-0 p-4 pt-0">
                    <button type="submit" name="add_module" class="btn btn-theme w-100 py-3 shadow-sm">SAVE MODULE</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="editModuleModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <form method="POST">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold text-dark"><i class="fas fa-edit text-warning me-2"></i> Edit Module</h5>
                    <button type="button" class="btn-close shadow-none" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="course_id" value="<?= $selected_course_id ?>">
                    <input type="hidden" name="module_id" id="edit_module_id">
                    <label class="form-label small fw-bold text-uppercase text-muted">Update Title <span class="text-danger">*</span></label>
                    <div class="input-group">
                        <span class="input-group-text border-2 border-end-0 bg-light text-muted"><i class="fas fa-heading"></i></span>
                        <input type="text" name="module_title" id="edit_module_title" class="form-control border-start-0 ps-0 fw-bold" required>
                    </div>
                </div>
                <div class="modal-footer border-0 p-4 pt-0">
                    <button type="submit" name="edit_module" class="btn btn-dark w-100 py-3 fw-bold rounded-3 shadow-sm">UPDATE MODULE</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="addLessonModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <form method="POST" enctype="multipart/form-data">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold text-dark"><i class="fas fa-play-circle text-success me-2"></i> Add New Lesson</h5>
                    <button type="button" class="btn-close shadow-none" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body row g-4">
                    <input type="hidden" name="course_id" value="<?= $selected_course_id ?>">
                    <input type="hidden" name="module_id" id="lesson_module_id">
                    
                    <div class="col-md-8">
                        <label class="form-label small fw-bold text-uppercase text-muted">Lesson Title <span class="text-danger">*</span></label>
                        <input type="text" name="lesson_title" class="form-control fw-bold" placeholder="E.g. What is Web Development?" required>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label small fw-bold text-uppercase text-muted">Duration</label>
                        <input type="text" name="duration" class="form-control" placeholder="E.g. 12:30">
                    </div>
                    <div class="col-md-12">
                        <label class="form-label small fw-bold text-uppercase text-muted">Video URL <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <span class="input-group-text border-2 border-end-0 bg-light text-muted"><i class="fab fa-youtube text-danger"></i></span>
                            <input type="url" name="video_url" class="form-control border-start-0 ps-0" placeholder="https://youtube.com/..." required>
                        </div>
                    </div>
                    <div class="col-md-12">
                        <label class="form-label small fw-bold text-uppercase text-muted">Lesson Notes (Optional)</label>
                        <textarea name="notes" class="form-control" rows="3" placeholder="Write any extra details for students..."></textarea>
                    </div>
                    <div class="col-md-12">
                        <div class="p-3 border-2 border-dashed rounded-3 bg-light" style="border-style: dashed;">
                            <label class="form-label small fw-bold text-dark"><i class="fas fa-file-pdf text-danger me-1"></i> Attach Resource (PDF)</label>
                            <input type="file" name="resource_file" class="form-control bg-white border-0 shadow-none" accept=".pdf">
                        </div>
                    </div>
                </div>
                <div class="modal-footer border-0 p-4 pt-0">
                    <button type="submit" name="add_lesson" class="btn btn-theme w-100 py-3 shadow-sm">UPLOAD LESSON</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="editLessonModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <form method="POST" enctype="multipart/form-data">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold text-dark"><i class="fas fa-edit text-warning me-2"></i> Edit Lesson</h5>
                    <button type="button" class="btn-close shadow-none" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body row g-4">
                    <input type="hidden" name="course_id" value="<?= $selected_course_id ?>">
                    <input type="hidden" name="lesson_id" id="edit_lesson_id">
                    
                    <div class="col-md-8">
                        <label class="form-label small fw-bold text-uppercase text-muted">Lesson Title <span class="text-danger">*</span></label>
                        <input type="text" name="lesson_title" id="edit_lesson_title" class="form-control fw-bold" required>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label small fw-bold text-uppercase text-muted">Duration</label>
                        <input type="text" name="duration" id="edit_duration" class="form-control">
                    </div>
                    <div class="col-md-12">
                        <label class="form-label small fw-bold text-uppercase text-muted">Video URL <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <span class="input-group-text border-2 border-end-0 bg-light text-muted"><i class="fab fa-youtube text-danger"></i></span>
                            <input type="url" name="video_url" id="edit_video_url" class="form-control border-start-0 ps-0" required>
                        </div>
                    </div>
                    <div class="col-md-12">
                        <label class="form-label small fw-bold text-uppercase text-muted">Notes</label>
                        <textarea name="notes" id="edit_notes" class="form-control" rows="3"></textarea>
                    </div>
                    <div class="col-md-12">
                        <div class="p-3 border-2 border-dashed rounded-3 bg-light" style="border-style: dashed;">
                            <label class="form-label small fw-bold text-dark"><i class="fas fa-file-pdf text-danger me-1"></i> Replace Resource (Optional)</label>
                            <input type="file" name="resource_file" class="form-control bg-white border-0 shadow-none" accept=".pdf">
                        </div>
                    </div>
                </div>
                <div class="modal-footer border-0 p-4 pt-0">
                    <button type="submit" name="edit_lesson" class="btn btn-dark w-100 py-3 fw-bold rounded-3 shadow-sm">UPDATE LESSON</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        // Sidebar Toggle for Mobile
        const toggleBtn = document.getElementById('sidebarToggle');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', function(e) {
                e.preventDefault();
                const sidebar = document.querySelector('.sidebar') || document.getElementById('sidebarMenu');
                if (sidebar) { sidebar.classList.toggle('active'); }
            });
        }
    });

    // Populate Modals Data
    function editModule(id, title) {
        document.getElementById('edit_module_id').value = id;
        document.getElementById('edit_module_title').value = title;
        new bootstrap.Modal(document.getElementById('editModuleModal')).show();
    }
    
    function editLesson(id, title, url, duration, notes) {
        document.getElementById('edit_lesson_id').value = id;
        document.getElementById('edit_lesson_title').value = title;
        document.getElementById('edit_video_url').value = url;
        document.getElementById('edit_duration').value = duration;
        document.getElementById('edit_notes').value = notes;
        new bootstrap.Modal(document.getElementById('editLessonModal')).show();
    }
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<?php include 'includes/footer.php'; ?>