<?php
include '../config.php';

if (!isGuru()) {
    redirect('../login.php');
}

$guru_id = $_SESSION['user_id'];
$course_id = isset($_GET['course_id']) ? sanitize($_GET['course_id']) : null;

// Ambil daftar kursus yang diajar guru
$sql_lms_courses = "SELECT id, judul FROM lms_courses WHERE id_guru = ? ORDER BY judul";
$stmt_lms_courses = $conn->prepare($sql_lms_courses);
$stmt_lms_courses->bind_param('i', $guru_id);
$stmt_lms_courses->execute();
$result_lms_courses = $stmt_lms_courses->get_result();

// Jika course_id dipilih, ambil detail kursus dan lms_lessons
$course = null;
$lms_lessons = [];
if ($course_id) {
    // Verifikasi bahwa kursus milik guru
    $sql_course = "SELECT c.*, cat.nama_kategori 
                   FROM lms_courses c 
                   JOIN lms_categories cat ON c.id_kategori = cat.id 
                   WHERE c.id = ? AND c.id_guru = ?";
    $stmt_course = $conn->prepare($sql_course);
    $stmt_course->bind_param('ii', $course_id, $guru_id);
    $stmt_course->execute();
    $course = $stmt_course->get_result()->fetch_assoc();

    if ($course) {
        // Ambil lms_lessons untuk kursus ini
        $sql_lms_lessons = "SELECT * FROM lms_lessons 
                        WHERE id_course = ? 
                        ORDER BY urutan ASC";
        $stmt_lms_lessons = $conn->prepare($sql_lms_lessons);
        $stmt_lms_lessons->bind_param('i', $course_id);
        $stmt_lms_lessons->execute();
        $result_lms_lessons = $stmt_lms_lessons->get_result();
        $lms_lessons = $result_lms_lessons->fetch_all(MYSQLI_ASSOC);
    }
}

// Handle form actions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['add_lesson'])) {
        $judul_lesson = sanitize($_POST['judul_lesson']);
        $konten = $_POST['konten']; // Tidak disanitasi karena mengandung HTML
        $tipe_lesson = sanitize($_POST['tipe_lesson']);
        $durasi_menit = intval($_POST['durasi_menit']);
        $video_url = sanitize($_POST['video_url'] ?? '');
        $quiz_id = intval($_POST['quiz_id'] ?? 0);
        
        // Get next urutan
        $sql_max_urutan = "SELECT MAX(urutan) as max_urutan FROM lms_lessons WHERE id_course = ?";
        $stmt_max = $conn->prepare($sql_max_urutan);
        $stmt_max->bind_param('i', $course_id);
        $stmt_max->execute();
        $max_urutan = $stmt_max->get_result()->fetch_assoc()['max_urutan'] ?? 0;
        $urutan = $max_urutan + 1;

        // Handle video URL - convert to embed URL if needed
        if ($tipe_lesson === 'video' && !empty($video_url)) {
            $video_url = convertToEmbedUrl($video_url);
        }

        $sql_insert = "INSERT INTO lms_lessons (id_course, judul_lesson, konten, video_url, tipe_lesson, urutan, durasi_menit) 
                       VALUES (?, ?, ?, ?, ?, ?, ?)";
        $stmt_insert = $conn->prepare($sql_insert);
        $stmt_insert->bind_param('issssii', $course_id, $judul_lesson, $konten, $video_url, $tipe_lesson, $urutan, $durasi_menit);
        
        if ($stmt_insert->execute()) {
            $_SESSION['success'] = "Materi berhasil ditambahkan!";
            redirect("manage_lessons.php?course_id=" . $course_id);
        } else {
            $_SESSION['error'] = "Gagal menambahkan materi!";
        }
    }

    if (isset($_POST['update_lesson'])) {
        $lesson_id = sanitize($_POST['lesson_id']);
        $judul_lesson = sanitize($_POST['judul_lesson']);
        $konten = $_POST['konten']; // Tidak disanitasi karena mengandung HTML
        $tipe_lesson = sanitize($_POST['tipe_lesson']);
        $durasi_menit = intval($_POST['durasi_menit']);
        $video_url = sanitize($_POST['video_url'] ?? '');

        // Handle video URL - convert to embed URL if needed
        if ($tipe_lesson === 'video' && !empty($video_url)) {
            $video_url = convertToEmbedUrl($video_url);
        }

        $sql_update = "UPDATE lms_lessons SET judul_lesson = ?, konten = ?, video_url = ?, tipe_lesson = ?, durasi_menit = ? 
                       WHERE id = ? AND id_course IN (SELECT id FROM lms_courses WHERE id_guru = ?)";
        $stmt_update = $conn->prepare($sql_update);
        $stmt_update->bind_param('ssssiii', $judul_lesson, $konten, $video_url, $tipe_lesson, $durasi_menit, $lesson_id, $guru_id);
        
        if ($stmt_update->execute()) {
            $_SESSION['success'] = "Materi berhasil diperbarui!";
            redirect("manage_lessons.php?course_id=" . $course_id);
        } else {
            $_SESSION['error'] = "Gagal memperbarui materi!";
        }
    }

    if (isset($_POST['delete_lesson'])) {
        $lesson_id = sanitize($_POST['lesson_id']);

        $sql_delete = "DELETE FROM lms_lessons 
                       WHERE id = ? AND id_course IN (SELECT id FROM lms_courses WHERE id_guru = ?)";
        $stmt_delete = $conn->prepare($sql_delete);
        $stmt_delete->bind_param('ii', $lesson_id, $guru_id);
        
        if ($stmt_delete->execute()) {
            $_SESSION['success'] = "Materi berhasil dihapus!";
            redirect("manage_lessons.php?course_id=" . $course_id);
        } else {
            $_SESSION['error'] = "Gagal menghapus materi!";
        }
    }

    if (isset($_POST['reorder_lms_lessons'])) {
        $order_data = $_POST['order'];
        foreach ($order_data as $urutan => $lesson_id) {
            $sql_reorder = "UPDATE lms_lessons SET urutan = ? 
                           WHERE id = ? AND id_course IN (SELECT id FROM lms_courses WHERE id_guru = ?)";
            $stmt_reorder = $conn->prepare($sql_reorder);
            $stmt_reorder->bind_param('iii', $urutan, $lesson_id, $guru_id);
            $stmt_reorder->execute();
        }
        $_SESSION['success'] = "Urutan materi berhasil diperbarui!";
        redirect("manage_lessons.php?course_id=" . $course_id);
    }
}

// Function to convert YouTube/Vimeo URLs to embed URLs
function convertToEmbedUrl($url) {
    // YouTube
    if (preg_match('/youtube\.com\/watch\?v=([a-zA-Z0-9_-]+)/', $url, $matches)) {
        return 'https://www.youtube.com/embed/' . $matches[1];
    }
    if (preg_match('/youtu\.be\/([a-zA-Z0-9_-]+)/', $url, $matches)) {
        return 'https://www.youtube.com/embed/' . $matches[1];
    }
    
    // Vimeo
    if (preg_match('/vimeo\.com\/([0-9]+)/', $url, $matches)) {
        return 'https://player.vimeo.com/video/' . $matches[1];
    }
    
    // If already embed URL, return as is
    if (strpos($url, 'youtube.com/embed') !== false || strpos($url, 'player.vimeo.com/video') !== false) {
        return $url;
    }
    
    return $url;
}

// Ambil daftar kuis untuk kursus ini (jika ada)
$lms_quizzes = [];
if ($course_id) {
    $sql_lms_quizzes = "SELECT q.id, q.judul_quiz 
                    FROM lms_quizzes q 
                    JOIN lms_lessons l ON q.id_lesson = l.id 
                    WHERE l.id_course = ? 
                    ORDER BY q.judul_quiz";
    $stmt_lms_quizzes = $conn->prepare($sql_lms_quizzes);
    $stmt_lms_quizzes->bind_param('i', $course_id);
    $stmt_lms_quizzes->execute();
    $result_lms_quizzes = $stmt_lms_quizzes->get_result();
    $lms_quizzes = $result_lms_quizzes->fetch_all(MYSQLI_ASSOC);
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kelola Materi - SMANSAB LMS</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.14.0/Sortable.min.css">
    <!-- Summernote CSS -->
    <link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-lite.min.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #3f51b5;
            --secondary-color: #f5f5f5;
        }
        
        .sidebar {
            background: var(--primary-color);
            color: white;
            min-height: 100vh;
            padding: 0;
        }
        
        .sidebar-sticky {
            position: sticky;
            top: 0;
            height: 100vh;
            padding-top: 20px;
            overflow-y: auto;
        }
        
        .sidebar .nav-link {
            color: rgba(255, 255, 255, 0.8);
            padding: 12px 20px;
            margin: 2px 0;
            border-radius: 0;
            transition: all 0.3s;
        }
        
        .sidebar .nav-link:hover {
            color: white;
            background: rgba(255, 255, 255, 0.1);
        }
        
        .sidebar .nav-link.active {
            color: white;
            background: rgba(255, 255, 255, 0.2);
            border-left: 4px solid #fff;
        }
        
        .sidebar .nav-link i {
            width: 20px;
            margin-right: 10px;
        }
        
        .main-content {
            background: #f8f9fa;
            min-height: 100vh;
        }
        
        .navbar-custom {
            background: white;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .course-header {
            background: linear-gradient(135deg, var(--primary-color), #7986cb);
            color: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 25px;
        }
        
        .lesson-card {
            border: none;
            border-radius: 10px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 15px;
            transition: all 0.3s;
            background: white;
        }
        
        .lesson-card:hover {
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }
        
        .lesson-card.sortable-ghost {
            opacity: 0.4;
        }
        
        .lesson-card.sortable-chosen {
            background: #f8f9fa;
        }
        
        .lesson-type-badge {
            font-size: 0.7rem;
            padding: 4px 8px;
        }
        
        .drag-handle {
            cursor: move;
            color: #6c757d;
            padding: 10px;
        }
        
        .drag-handle:hover {
            color: var(--primary-color);
        }
        
        .empty-lms_lessons {
            text-align: center;
            padding: 60px 20px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .lesson-actions .btn {
            margin: 2px;
        }
        
        .tab-content {
            background: white;
            border-radius: 0 0 10px 10px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .nav-tabs .nav-link {
            color: #495057;
            border: none;
            padding: 1rem 2rem;
        }
        
        .nav-tabs .nav-link.active {
            background: var(--primary-color);
            color: white;
            border: none;
        }
        
        .content-type-fields {
            display: none;
        }
        
        .content-type-fields.active {
            display: block;
        }
        
        /* Summernote Customization */
        .note-editor.note-frame {
            border: 1px solid #dee2e6;
            border-radius: 0.375rem;
        }
        
        .note-editor.note-frame .note-toolbar {
            background: #f8f9fa;
            border-bottom: 1px solid #dee2e6;
        }
        
        .note-editor.note-frame .note-statusbar {
            background: #f8f9fa;
            border-top: 1px solid #dee2e6;
        }
        
        .note-editable {
            min-height: 200px;
        }
        
        .video-preview {
            background: #f8f9fa;
            border: 2px dashed #dee2e6;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            margin-bottom: 15px;
        }
        
        .video-preview iframe {
            max-width: 100%;
            border-radius: 8px;
        }
        
        .url-help {
            font-size: 0.875rem;
            color: #6c757d;
        }
        
        .url-examples {
            background: #e9ecef;
            border-radius: 5px;
            padding: 10px;
            margin-top: 5px;
            font-size: 0.8rem;
        }
        
        .video-required {
            color: #dc3545;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3 col-lg-2 sidebar">
                <div class="sidebar-sticky">
                    <div class="text-center mb-4">
                        <h4 class="fw-bold">
                            <i class="bi bi-book-half"></i><br>
                            SMANSAB LMS
                        </h4>
                        <small class="text-white-50">Guru Dashboard</small>
                    </div>
                    
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="dashboard.php">
                                <i class="bi bi-speedometer2"></i> Dashboard
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="my_courses.php">
                                <i class="bi bi-journal-bookmark"></i> Kursus Saya
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="manage_lessons.php">
                                <i class="bi bi-collection-play"></i> Kelola Materi
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="manage_quizzes.php">
                                <i class="bi bi-pencil-square"></i> Kelola Kuis
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="students_progress.php">
                                <i class="bi bi-graph-up"></i> Progress Siswa
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="profile.php">
                                <i class="bi bi-person"></i> Profil Saya
                            </a>
                        </li>
                        <li class="nav-item mt-4">
                            <a class="nav-link" href="../logout.php">
                                <i class="bi bi-box-arrow-right"></i> Logout
                            </a>
                        </li>
                    </ul>
                    
                    <div class="mt-5 px-3">
                        <small class="text-white-50">
                            <i class="bi bi-info-circle"></i> Butuh bantuan?
                            <a href="#" class="text-white">Hubungi Admin</a>
                        </small>
                    </div>
                </div>
            </div>

            <!-- Main Content -->
            <div class="col-md-9 col-lg-10 main-content">
                <!-- Top Navbar -->
                <nav class="navbar navbar-custom">
                    <div class="container-fluid">
                        <div class="d-flex align-items-center">
                            <button class="btn btn-outline-primary me-3 d-md-none" type="button">
                                <i class="bi bi-list"></i>
                            </button>
                            <h5 class="mb-0">Kelola Materi Pembelajaran</h5>
                        </div>
                        <div class="d-flex align-items-center">
                            <div class="dropdown">
                                <button class="btn btn-outline-primary dropdown-toggle" type="button" 
                                        data-bs-toggle="dropdown">
                                    <i class="bi bi-person-circle me-2"></i>
                                    <?php echo $_SESSION['nama_lengkap']; ?>
                                </button>
                                <ul class="dropdown-menu">
                                    <li><a class="dropdown-item" href="profile.php">
                                        <i class="bi bi-person me-2"></i>Profil
                                    </a></li>
                                    <li><a class="dropdown-item" href="my_courses.php">
                                        <i class="bi bi-journal-bookmark me-2"></i>Kursus Saya
                                    </a></li>
                                    <li><hr class="dropdown-divider"></li>
                                    <li><a class="dropdown-item" href="../logout.php">
                                        <i class="bi bi-box-arrow-right me-2"></i>Logout
                                    </a></li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </nav>

                <div class="container-fluid mt-4">
                    <!-- Alert Messages -->
                    <?php if (isset($_SESSION['success'])): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <?php if (isset($_SESSION['error'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <!-- Course Selection -->
                    <div class="card border-0 shadow-sm mb-4">
                        <div class="card-body">
                            <h6 class="mb-3">Pilih Kursus:</h6>
                            <form method="GET" class="row g-3 align-items-end">
                                <div class="col-md-8">
                                    <select name="course_id" class="form-select" onchange="this.form.submit()">
                                        <option value="">-- Pilih Kursus --</option>
                                        <?php while($course_option = $result_lms_courses->fetch_assoc()): ?>
                                            <option value="<?php echo $course_option['id']; ?>" 
                                                <?php echo $course_id == $course_option['id'] ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($course_option['judul']); ?>
                                            </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <a href="my_courses.php" class="btn btn-outline-primary w-100">
                                        <i class="bi bi-arrow-left me-2"></i>Kembali ke Kursus
                                    </a>
                                </div>
                            </form>
                        </div>
                    </div>

                    <?php if ($course): ?>
                        <!-- Course Header -->
                        <div class="course-header">
                            <div class="row align-items-center">
                                <div class="col-md-8">
                                    <h4 class="fw-bold mb-2"><?php echo htmlspecialchars($course['judul']); ?></h4>
                                    <p class="mb-1">
                                        <i class="bi bi-tag me-2"></i><?php echo $course['nama_kategori']; ?>
                                    </p>
                                    <p class="mb-0">
                                        <i class="bi bi-clock me-2"></i>
                                        <?php echo $course['durasi_jam']; ?> jam • 
                                        <?php echo $course['level']; ?> • 
                                        <?php echo count($lms_lessons); ?> materi
                                    </p>
                                </div>
                                <div class="col-md-4 text-end">
                                    <span class="badge bg-light text-dark fs-6 p-2">
                                        <i class="bi bi-star-fill text-warning me-1"></i>
                                        <?php echo $course['rating']; ?> Rating
                                    </span>
                                </div>
                            </div>
                        </div>

                        <!-- Tab Navigation -->
                        <ul class="nav nav-tabs" id="lms_lessonsTab" role="tablist">
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active" id="list-tab" data-bs-toggle="tab" 
                                        data-bs-target="#list" type="button" role="tab">
                                    <i class="bi bi-list-ul me-2"></i>Daftar Materi
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="add-tab" data-bs-toggle="tab" 
                                        data-bs-target="#add" type="button" role="tab">
                                    <i class="bi bi-plus-circle me-2"></i>Tambah Materi
                                </button>
                            </li>
                        </ul>

                        <!-- Tab Content -->
                        <div class="tab-content p-4" id="lms_lessonsTabContent">
                            <!-- List lms_lessons Tab -->
                            <div class="tab-pane fade show active" id="list" role="tabpanel">
                                <?php if (!empty($lms_lessons)): ?>
                                    <div class="d-flex justify-content-between align-items-center mb-4">
                                        <h6 class="mb-0">Total <?php echo count($lms_lessons); ?> Materi</h6>
                                        <form method="POST" id="reorderForm">
                                            <input type="hidden" name="reorder_lms_lessons" value="1">
                                            <div id="orderData"></div>
                                            <button type="submit" class="btn btn-success btn-sm">
                                                <i class="bi bi-check-circle me-1"></i>Simpan Urutan
                                            </button>
                                        </form>
                                    </div>

                                    <div id="lms_lessonsList" class="sortable-list">
                                        <?php foreach($lms_lessons as $lesson): 
                                            $type_badges = [
                                                'teks' => ['bg-primary', 'bi-file-text', 'Teks'],
                                                'video' => ['bg-success', 'bi-play-circle', 'Video'],
                                                'quiz' => ['bg-warning', 'bi-pencil-square', 'Kuis'],
                                                'tugas' => ['bg-info', 'bi-journal-check', 'Tugas']
                                            ];
                                            $badge = $type_badges[$lesson['tipe_lesson']] ?? ['bg-secondary', 'bi-file', 'Unknown'];
                                        ?>
                                            <div class="lesson-card card" data-lesson-id="<?php echo $lesson['id']; ?>">
                                                <div class="card-body">
                                                    <div class="row align-items-center">
                                                        <div class="col-auto">
                                                            <div class="drag-handle">
                                                                <i class="bi bi-grip-vertical"></i>
                                                            </div>
                                                        </div>
                                                        <div class="col-auto text-center" style="width: 60px;">
                                                            <div class="bg-light rounded p-2">
                                                                <i class="bi <?php echo $badge[1]; ?> text-primary"></i>
                                                            </div>
                                                            <small class="text-muted">#<?php echo $lesson['urutan']; ?></small>
                                                        </div>
                                                        <div class="col">
                                                            <h6 class="card-title mb-1"><?php echo htmlspecialchars($lesson['judul_lesson']); ?></h6>
                                                            <div class="d-flex align-items-center">
                                                                <span class="badge <?php echo $badge[0]; ?> lesson-type-badge me-2">
                                                                    <?php echo $badge[2]; ?>
                                                                </span>
                                                                <small class="text-muted">
                                                                    <i class="bi bi-clock me-1"></i>
                                                                    <?php echo $lesson['durasi_menit']; ?> menit
                                                                </small>
                                                                <?php if ($lesson['tipe_lesson'] === 'video' && !empty($lesson['video_url'])): ?>
                                                                    <small class="text-success ms-2">
                                                                        <i class="bi bi-check-circle"></i> Video tersedia
                                                                    </small>
                                                                <?php endif; ?>
                                                            </div>
                                                        </div>
                                                        <div class="col-auto">
                                                            <div class="lesson-actions">
                                                                <button type="button" class="btn btn-outline-primary btn-sm" 
                                                                        data-bs-toggle="modal" 
                                                                        data-bs-target="#editLessonModal"
                                                                        data-lesson-id="<?php echo $lesson['id']; ?>"
                                                                        data-judul="<?php echo htmlspecialchars($lesson['judul_lesson']); ?>"
                                                                        data-konten="<?php echo htmlspecialchars($lesson['konten']); ?>"
                                                                        data-tipe="<?php echo $lesson['tipe_lesson']; ?>"
                                                                        data-durasi="<?php echo $lesson['durasi_menit']; ?>"
                                                                        data-video-url="<?php echo htmlspecialchars($lesson['video_url'] ?? ''); ?>">
                                                                    <i class="bi bi-pencil"></i>
                                                                </button>
                                                                <button type="button" class="btn btn-outline-danger btn-sm" 
                                                                        data-bs-toggle="modal" 
                                                                        data-bs-target="#deleteLessonModal"
                                                                        data-lesson-id="<?php echo $lesson['id']; ?>"
                                                                        data-judul="<?php echo htmlspecialchars($lesson['judul_lesson']); ?>">
                                                                    <i class="bi bi-trash"></i>
                                                                </button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                <?php else: ?>
                                    <div class="empty-lms_lessons">
                                        <i class="bi bi-collection text-muted" style="font-size: 4rem;"></i>
                                        <h4 class="text-muted mt-3">Belum Ada Materi</h4>
                                        <p class="text-muted mb-4">Mulai dengan menambahkan materi pertama untuk kursus ini</p>
                                        <button type="button" class="btn btn-primary" data-bs-toggle="tab" data-bs-target="#add">
                                            <i class="bi bi-plus-circle me-2"></i>Tambah Materi Pertama
                                        </button>
                                    </div>
                                <?php endif; ?>
                            </div>

                            <!-- Add Lesson Tab -->
                            <div class="tab-pane fade" id="add" role="tabpanel">
                                <form method="POST" id="addLessonForm">
                                    <input type="hidden" name="add_lesson" value="1">
                                    
                                    <div class="row">
                                        <div class="col-md-8">
                                            <div class="mb-3">
                                                <label for="judul_lesson" class="form-label">Judul Materi *</label>
                                                <input type="text" class="form-control" id="judul_lesson" name="judul_lesson" required>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label for="tipe_lesson" class="form-label">Tipe Materi *</label>
                                                <select class="form-select" id="tipe_lesson" name="tipe_lesson" required onchange="showContentFields(this.value)">
                                                    <option value="teks">Teks</option>
                                                    <option value="video">Video</option>
                                                    <option value="quiz">Kuis</option>
                                                    <option value="tugas">Tugas</option>
                                                </select>
                                            </div>
                                            
                                            <!-- Fields for Video -->
                                            <div id="videoFields" class="content-type-fields">
                                                <div class="mb-3">
                                                    <label for="video_url" class="form-label">
                                                        URL Video <span class="video-required">*</span>
                                                    </label>
                                                    <input type="url" class="form-control" id="video_url" name="video_url" 
                                                           placeholder="https://www.youtube.com/watch?v=... atau https://vimeo.com/..."
                                                           oninput="previewVideo(this.value)">
                                                    <div class="url-help">
                                                        <strong>Format URL yang didukung:</strong>
                                                        <div class="url-examples">
                                                            YouTube: https://www.youtube.com/watch?v=VIDEO_ID<br>
                                                            YouTube Short: https://youtu.be/VIDEO_ID<br>
                                                            Vimeo: https://vimeo.com/VIDEO_ID
                                                        </div>
                                                    </div>
                                                </div>
                                                <div id="videoPreview" class="video-preview">
                                                    <i class="bi bi-play-circle fs-1 text-muted"></i>
                                                    <p class="text-muted mt-2">Preview video akan muncul di sini</p>
                                                </div>
                                            </div>
                                            
                                            <!-- Fields for Quiz -->
                                            <div id="quizFields" class="content-type-fields">
                                                <div class="mb-3">
                                                    <label for="quiz_id" class="form-label">Pilih Kuis</label>
                                                    <select class="form-select" id="quiz_id" name="quiz_id">
                                                        <option value="">-- Pilih Kuis --</option>
                                                        <?php foreach($lms_quizzes as $quiz): ?>
                                                            <option value="<?php echo $quiz['id']; ?>">
                                                                <?php echo htmlspecialchars($quiz['judul_quiz']); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                    <?php if (empty($lms_quizzes)): ?>
                                                        <div class="form-text">
                                                            <a href="manage_quizzes.php?course_id=<?php echo $course_id; ?>" class="text-primary">
                                                                Buat kuis terlebih dahulu
                                                            </a>
                                                        </div>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                            
                                            <!-- Fields for Tugas -->
                                            <div id="tugasFields" class="content-type-fields">
                                                <div class="mb-3">
                                                    <label class="form-label">Instruksi Tugas</label>
                                                    <div class="alert alert-info">
                                                        <i class="bi bi-info-circle"></i>
                                                        Gunakan editor di bawah untuk menulis instruksi tugas yang jelas dan lengkap.
                                                        Sertakan deadline, format file, dan kriteria penilaian.
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label for="durasi_menit" class="form-label">Durasi (menit) *</label>
                                                <input type="number" class="form-control" id="durasi_menit" name="durasi_menit" 
                                                       min="1" max="480" value="30" required>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="card bg-light">
                                                <div class="card-body">
                                                    <h6 class="card-title">Tips Materi yang Baik:</h6>
                                                    <ul class="small mb-0">
                                                        <li>Gunakan judul yang jelas dan deskriptif</li>
                                                        <li>Pilih tipe materi yang sesuai dengan konten</li>
                                                        <li>Estimasi durasi yang realistis</li>
                                                        <li>Struktur konten yang mudah dipahami</li>
                                                    </ul>
                                                    <hr>
                                                    <h6 class="card-title">Panduan Tipe Materi:</h6>
                                                    <ul class="small mb-0">
                                                        <li><strong>Teks:</strong> Artikel, penjelasan teori</li>
                                                        <li><strong>Video:</strong> Tutorial, penjelasan visual</li>
                                                        <li><strong>Kuis:</strong> Evaluasi pemahaman</li>
                                                        <li><strong>Tugas:</strong> Praktik dan penerapan</li>
                                                    </ul>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="konten" class="form-label">Konten Materi *</label>
                                        <textarea class="form-control summernote" id="konten" name="konten" required></textarea>
                                    </div>
                                    
                                    <div class="d-flex justify-content-between">
                                        <button type="button" class="btn btn-secondary" data-bs-toggle="tab" data-bs-target="#list">
                                            <i class="bi bi-arrow-left me-2"></i>Kembali ke Daftar
                                        </button>
                                        <button type="submit" class="btn btn-primary">
                                            <i class="bi bi-plus-circle me-2"></i>Tambah Materi
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    <?php else: ?>
                        <!-- No Course Selected -->
                        <div class="text-center py-5">
                            <i class="bi bi-journal-bookmark text-muted" style="font-size: 4rem;"></i>
                            <h4 class="text-muted mt-3">Pilih Kursus</h4>
                            <p class="text-muted">Silakan pilih kursus dari dropdown di atas untuk mengelola materinya</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit Lesson Modal -->
    <div class="modal fade" id="editLessonModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Edit Materi</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="POST">
                    <input type="hidden" name="update_lesson" value="1">
                    <input type="hidden" name="lesson_id" id="editLessonId">
                    
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="editJudulLesson" class="form-label">Judul Materi *</label>
                            <input type="text" class="form-control" id="editJudulLesson" name="judul_lesson" required>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="editTipeLesson" class="form-label">Tipe Materi *</label>
                                    <select class="form-select" id="editTipeLesson" name="tipe_lesson" required onchange="showEditContentFields(this.value)">
                                        <option value="teks">Teks</option>
                                        <option value="video">Video</option>
                                        <option value="quiz">Kuis</option>
                                        <option value="tugas">Tugas</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="editDurasiMenit" class="form-label">Durasi (menit) *</label>
                                    <input type="number" class="form-control" id="editDurasiMenit" name="durasi_menit" 
                                           min="1" max="480" required>
                                </div>
                            </div>
                        </div>

                        <!-- Video Fields for Edit Modal -->
                        <div id="editVideoFields" class="content-type-fields">
                            <div class="mb-3">
                                <label for="editVideoUrl" class="form-label">
                                    URL Video <span class="video-required">*</span>
                                </label>
                                <input type="url" class="form-control" id="editVideoUrl" name="video_url" 
                                       placeholder="https://www.youtube.com/watch?v=... atau https://vimeo.com/..."
                                       oninput="previewEditVideo(this.value)">
                                <div class="url-help">
                                    <strong>Format URL yang didukung:</strong>
                                    <div class="url-examples">
                                        YouTube: https://www.youtube.com/watch?v=VIDEO_ID<br>
                                        YouTube Short: https://youtu.be/VIDEO_ID<br>
                                        Vimeo: https://vimeo.com/VIDEO_ID
                                    </div>
                                </div>
                            </div>
                            <div id="editVideoPreview" class="video-preview">
                                <i class="bi bi-play-circle fs-1 text-muted"></i>
                                <p class="text-muted mt-2">Preview video akan muncul di sini</p>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="editKonten" class="form-label">Konten Materi *</label>
                            <textarea class="form-control summernote" id="editKonten" name="konten" required></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                        <button type="submit" class="btn btn-primary">Simpan Perubahan</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Delete Lesson Modal -->
    <div class="modal fade" id="deleteLessonModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Hapus Materi</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="POST">
                    <input type="hidden" name="delete_lesson" value="1">
                    <input type="hidden" name="lesson_id" id="deleteLessonId">
                    
                    <div class="modal-body">
                        <p>Apakah Anda yakin ingin menghapus materi "<span id="deleteLessonTitle"></span>"?</p>
                        <p class="text-danger small">
                            <i class="bi bi-exclamation-triangle"></i> 
                            Tindakan ini tidak dapat dibatalkan. Semua data materi akan dihapus.
                        </p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                        <button type="submit" class="btn btn-danger">Ya, Hapus Materi</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- jQuery (required for Summernote) -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.14.0/Sortable.min.js"></script>
    <!-- Summernote JS -->
    <script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-lite.min.js"></script>
    <script>
        // Function to convert URL to embed URL
        function convertToEmbedUrl(url) {
            // YouTube watch URL
            if (url.includes('youtube.com/watch?v=')) {
                const videoId = url.split('v=')[1].split('&')[0];
                return `https://www.youtube.com/embed/${videoId}`;
            }
            // YouTube short URL
            else if (url.includes('youtu.be/')) {
                const videoId = url.split('youtu.be/')[1].split('?')[0];
                return `https://www.youtube.com/embed/${videoId}`;
            }
            // Vimeo URL
            else if (url.includes('vimeo.com/')) {
                const videoId = url.split('vimeo.com/')[1].split('/')[0];
                return `https://player.vimeo.com/video/${videoId}`;
            }
            // If already embed URL, return as is
            else if (url.includes('youtube.com/embed') || url.includes('player.vimeo.com/video')) {
                return url;
            }
            return url;
        }

        // Video preview for add form
        function previewVideo(url) {
            const preview = document.getElementById('videoPreview');
            if (url) {
                const embedUrl = convertToEmbedUrl(url);
                if (embedUrl !== url) {
                    preview.innerHTML = `
                        <iframe width="100%" height="315" src="${embedUrl}" 
                                frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" 
                                allowfullscreen>
                        </iframe>
                        <p class="text-success mt-2"><i class="bi bi-check-circle"></i> URL video valid</p>
                    `;
                } else {
                    preview.innerHTML = `
                        <i class="bi bi-exclamation-triangle fs-1 text-warning"></i>
                        <p class="text-warning mt-2">URL tidak valid. Pastikan format URL sesuai contoh.</p>
                    `;
                }
            } else {
                preview.innerHTML = `
                    <i class="bi bi-play-circle fs-1 text-muted"></i>
                    <p class="text-muted mt-2">Preview video akan muncul di sini</p>
                `;
            }
        }

        // Video preview for edit form
        function previewEditVideo(url) {
            const preview = document.getElementById('editVideoPreview');
            if (url) {
                const embedUrl = convertToEmbedUrl(url);
                if (embedUrl !== url) {
                    preview.innerHTML = `
                        <iframe width="100%" height="315" src="${embedUrl}" 
                                frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" 
                                allowfullscreen>
                        </iframe>
                        <p class="text-success mt-2"><i class="bi bi-check-circle"></i> URL video valid</p>
                    `;
                } else {
                    preview.innerHTML = `
                        <i class="bi bi-exclamation-triangle fs-1 text-warning"></i>
                        <p class="text-warning mt-2">URL tidak valid. Pastikan format URL sesuai contoh.</p>
                    `;
                }
            } else {
                preview.innerHTML = `
                    <i class="bi bi-play-circle fs-1 text-muted"></i>
                    <p class="text-muted mt-2">Preview video akan muncul di sini</p>
                `;
            }
        }

        // Show/hide content type specific fields for add form
        function showContentFields(type) {
            // Hide all fields first
            document.querySelectorAll('.content-type-fields').forEach(field => {
                field.classList.remove('active');
            });

            // Show fields for selected type
            if (type === 'video') {
                document.getElementById('videoFields').classList.add('active');
            } else if (type === 'quiz') {
                document.getElementById('quizFields').classList.add('active');
            } else if (type === 'tugas') {
                document.getElementById('tugasFields').classList.add('active');
            }

            // Update placeholder text based on type
            let placeholder = '';
            switch(type) {
                case 'teks':
                    placeholder = '<p>Mulai menulis konten teks materi di sini...</p>';
                    break;
                case 'video':
                    placeholder = '<p>Tambahkan penjelasan atau transkrip video di sini...</p>';
                    break;
                case 'quiz':
                    placeholder = '<p>Tambahkan instruksi atau penjelasan tentang kuis di sini...</p>';
                    break;
                case 'tugas':
                    placeholder = '<p>Tulis instruksi tugas yang jelas dan lengkap di sini...</p>';
                    break;
            }
            
            // Set Summernote content
            $('#konten').summernote('code', placeholder);
        }

        // Show/hide content type specific fields for edit modal
        function showEditContentFields(type) {
            // Hide all fields first
            document.querySelectorAll('#editLessonModal .content-type-fields').forEach(field => {
                field.style.display = 'none';
            });

            // Show fields for selected type
            if (type === 'video') {
                document.getElementById('editVideoFields').style.display = 'block';
            }
        }

        // Initialize Summernote
        $(document).ready(function() {
            // Initialize Summernote for main form
            $('#konten').summernote({
                height: 300,
                toolbar: [
                    ['style', ['style']],
                    ['font', ['bold', 'italic', 'underline', 'clear']],
                    ['fontname', ['fontname']],
                    ['color', ['color']],
                    ['para', ['ul', 'ol', 'paragraph']],
                    ['table', ['table']],
                    ['insert', ['link', 'picture', 'video']],
                    ['view', ['fullscreen', 'codeview', 'help']]
                ],
                fontNames: ['Arial', 'Arial Black', 'Comic Sans MS', 'Courier New', 'Helvetica', 'Impact', 'Tahoma', 'Times New Roman', 'Verdana'],
                fontSizes: ['8', '9', '10', '11', '12', '14', '18', '24', '36'],
                placeholder: 'Tulis konten materi di sini...'
            });

            // Initialize Summernote for edit modal when shown
            $('#editLessonModal').on('shown.bs.modal', function () {
                $('#editKonten').summernote({
                    height: 200,
                    toolbar: [
                        ['style', ['style']],
                        ['font', ['bold', 'italic', 'underline', 'clear']],
                        ['fontname', ['fontname']],
                        ['color', ['color']],
                        ['para', ['ul', 'ol', 'paragraph']],
                        ['table', ['table']],
                        ['insert', ['link', 'picture', 'video']],
                        ['view', ['fullscreen', 'codeview', 'help']]
                    ]
                });
            });

            // Destroy Summernote when edit modal is hidden to prevent conflicts
            $('#editLessonModal').on('hidden.bs.modal', function () {
                $('#editKonten').summernote('destroy');
            });

            // Edit Lesson Modal Handler dengan video_url
            $('#editLessonModal').on('show.bs.modal', function(event) {
                const button = event.relatedTarget;
                const lessonId = button.getAttribute('data-lesson-id');
                const judul = button.getAttribute('data-judul');
                const konten = button.getAttribute('data-konten');
                const tipe = button.getAttribute('data-tipe');
                const durasi = button.getAttribute('data-durasi');
                const videoUrl = button.getAttribute('data-video-url') || '';

                document.getElementById('editLessonId').value = lessonId;
                document.getElementById('editJudulLesson').value = judul;
                document.getElementById('editTipeLesson').value = tipe;
                document.getElementById('editDurasiMenit').value = durasi;
                document.getElementById('editVideoUrl').value = videoUrl;

                // Show/hide fields based on type
                showEditContentFields(tipe);

                // Preview video if exists
                if (tipe === 'video' && videoUrl) {
                    previewEditVideo(videoUrl);
                }

                // Set Summernote content after a delay
                setTimeout(() => {
                    $('#editKonten').summernote('code', konten);
                }, 500);
            });
        });

        // Delete Lesson Modal Handler
        document.addEventListener('DOMContentLoaded', function() {
            const deleteLessonModal = document.getElementById('deleteLessonModal');
            if (deleteLessonModal) {
                deleteLessonModal.addEventListener('show.bs.modal', function(event) {
                    const button = event.relatedTarget;
                    document.getElementById('deleteLessonId').value = button.getAttribute('data-lesson-id');
                    document.getElementById('deleteLessonTitle').textContent = button.getAttribute('data-judul');
                });
            }

            // Initialize Sortable
            const lms_lessonsList = document.getElementById('lms_lessonsList');
            if (lms_lessonsList) {
                new Sortable(lms_lessonsList, {
                    handle: '.drag-handle',
                    ghostClass: 'sortable-ghost',
                    chosenClass: 'sortable-chosen',
                    animation: 150,
                    onEnd: function(evt) {
                        updateOrderData();
                    }
                });

                function updateOrderData() {
                    const orderData = document.getElementById('orderData');
                    orderData.innerHTML = '';
                    const lessonCards = lms_lessonsList.querySelectorAll('.lesson-card');
                    
                    lessonCards.forEach((card, index) => {
                        const lessonId = card.getAttribute('data-lesson-id');
                        const input = document.createElement('input');
                        input.type = 'hidden';
                        input.name = 'order[' + index + ']';
                        input.value = lessonId;
                        orderData.appendChild(input);
                    });
                }

                // Initialize order data
                updateOrderData();
            }

            // Tab persistence
            const triggerTabList = [].slice.call(document.querySelectorAll('#lms_lessonsTab button'));
            triggerTabList.forEach(function (triggerEl) {
                triggerEl.addEventListener('click', function (event) {
                    const tabId = triggerEl.getAttribute('data-bs-target');
                    localStorage.setItem('activelms_lessonsTab', tabId);
                });
            });

            const activeTab = localStorage.getItem('activelms_lessonsTab');
            if (activeTab) {
                const triggerEl = document.querySelector(`#lms_lessonsTab button[data-bs-target="${activeTab}"]`);
                if (triggerEl) {
                    bootstrap.Tab.getInstance(triggerEl).show();
                }
            }

            // Initialize content fields on page load
            showContentFields('teks');
        });
    </script>
</body>
</html>