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

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

$guru_id = $_SESSION['user_id'];

// Get course ID from URL if specified
$course_id = isset($_GET['course_id']) ? intval($_GET['course_id']) : 0;

// Get lms_courses taught by this 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();
$lms_courses = $stmt_lms_courses->get_result();

// Get lms_lessons for selected course
$lms_lessons = null;
if ($course_id > 0) {
    $sql_lms_lessons = "SELECT id, judul_lesson FROM lms_lessons WHERE id_course = ? ORDER BY urutan";
    $stmt_lms_lessons = $conn->prepare($sql_lms_lessons);
    $stmt_lms_lessons->bind_param('i', $course_id);
    $stmt_lms_lessons->execute();
    $lms_lessons = $stmt_lms_lessons->get_result();
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $judul_quiz = isset($_POST['judul_quiz']) ? sanitize($_POST['judul_quiz']) : '';
    $deskripsi = isset($_POST['deskripsi']) ? sanitize($_POST['deskripsi']) : '';
    $id_lesson = isset($_POST['id_lesson']) ? intval($_POST['id_lesson']) : 0;
    $waktu_menit = isset($_POST['waktu_menit']) ? intval($_POST['waktu_menit']) : 30;
    $jumlah_soal = isset($_POST['jumlah_soal']) ? intval($_POST['jumlah_soal']) : 10;
    $passing_grade = isset($_POST['passing_grade']) ? intval($_POST['passing_grade']) : 60;
    $acak_soal = isset($_POST['acak_soal']) ? 1 : 0;
    $tampilkan_nilai = isset($_POST['tampilkan_nilai']) ? 1 : 0;
    $batas_percobaan = isset($_POST['batas_percobaan']) ? intval($_POST['batas_percobaan']) : 1;
    
    // Validasi
    $errors = [];
    
    if (empty($judul_quiz)) {
        $errors[] = "Judul kuis harus diisi";
    }
    
    if (empty($deskripsi)) {
        $errors[] = "Deskripsi kuis harus diisi";
    }
    
    if ($id_lesson <= 0) {
        $errors[] = "Materi harus dipilih";
    }
    
    if ($waktu_menit <= 0) {
        $errors[] = "Waktu pengerjaan harus lebih dari 0 menit";
    }
    
    if ($jumlah_soal <= 0) {
        $errors[] = "Jumlah soal harus lebih dari 0";
    }
    
    if ($passing_grade < 0 || $passing_grade > 100) {
        $errors[] = "Nilai kelulusan harus antara 0-100";
    }
    
    if ($batas_percobaan <= 0) {
        $errors[] = "Batas percobaan harus lebih dari 0";
    }
    
    // Verify lesson ownership
    if ($id_lesson > 0) {
        $verify_sql = "SELECT l.id FROM lms_lessons l 
                       LEFT JOIN lms_courses c ON l.id_course = c.id 
                       WHERE l.id = ? AND c.id_guru = ?";
        $verify_stmt = $conn->prepare($verify_sql);
        $verify_stmt->bind_param('ii', $id_lesson, $guru_id);
        $verify_stmt->execute();
        $verify_result = $verify_stmt->get_result();
        
        if ($verify_result->num_rows === 0) {
            $errors[] = "Materi tidak valid atau Anda tidak memiliki akses";
        }
        $verify_stmt->close();
    }
    
    if (empty($errors)) {
        // Insert quiz
        $sql = "INSERT INTO lms_quizzes (id_lesson, judul_quiz, deskripsi, waktu_menit, jumlah_soal, passing_grade, acak_soal, tampilkan_nilai, batas_percobaan, created_at) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('issiiiiii', $id_lesson, $judul_quiz, $deskripsi, $waktu_menit, $jumlah_soal, $passing_grade, $acak_soal, $tampilkan_nilai, $batas_percobaan);
        
        if ($stmt->execute()) {
            $quiz_id = $stmt->insert_id;
            $_SESSION['success'] = "Kuis berhasil dibuat! Sekarang Anda dapat menambahkan soal.";
            header("Location: manage_lms_questions.php?quiz_id=" . $quiz_id);
            exit();
        } else {
            $errors[] = "Gagal membuat kuis: " . $conn->error;
        }
        
        $stmt->close();
    }
    
    if (!empty($errors)) {
        $_SESSION['error'] = implode("<br>", $errors);
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Buat Kuis Baru - 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">
    <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);
        }
        
        .form-container {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        
        .preview-card {
            border: 2px dashed #dee2e6;
            border-radius: 10px;
            padding: 20px;
            background: #f8f9fa;
        }
        
        .step-indicator {
            display: flex;
            align-items: center;
            margin-bottom: 30px;
        }
        
        .step {
            display: flex;
            align-items: center;
            flex-direction: column;
            position: relative;
            flex: 1;
        }
        
        .step-number {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #e9ecef;
            color: #6c757d;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin-bottom: 8px;
            border: 3px solid #e9ecef;
        }
        
        .step.active .step-number {
            background: var(--primary-color);
            color: white;
            border-color: var(--primary-color);
        }
        
        .step.completed .step-number {
            background: #28a745;
            color: white;
            border-color: #28a745;
        }
        
        .step-line {
            position: absolute;
            top: 20px;
            left: 50%;
            width: 100%;
            height: 2px;
            background: #e9ecef;
            z-index: -1;
        }
        
        .step:first-child .step-line {
            left: 50%;
        }
        
        .step:last-child .step-line {
            width: 50%;
        }
        
        .quiz-icon {
            width: 60px;
            height: 60px;
            border-radius: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.8rem;
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            margin-bottom: 20px;
        }
        
        .settings-card {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            border-left: 4px solid var(--primary-color);
        }
        
        .form-check-input:checked {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }
    </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" href="manage_lessons.php">
                                <i class="bi bi-collection-play"></i> Kelola Materi
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" 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="course_management.php">
                                <i class="bi bi-gear"></i> Kelola Kursus
                            </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">Buat Kuis Baru</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">
                    <div class="row justify-content-center">
                        <div class="col-lg-10">
                            <!-- Header -->
                            <div class="row mb-4">
                                <div class="col-12">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <h4 class="fw-bold">Buat Kuis Baru</h4>
                                            <p class="text-muted mb-0">Buat kuis untuk mengukur pemahaman siswa</p>
                                        </div>
                                        <a href="manage_quizzes.php<?php echo $course_id ? '?course_id=' . $course_id : ''; ?>" class="btn btn-outline-secondary">
                                            <i class="bi bi-arrow-left me-2"></i>Kembali
                                        </a>
                                    </div>
                                </div>
                            </div>

                            <!-- Step Indicator -->
                            <div class="step-indicator">
                                <div class="step active">
                                    <div class="step-number">1</div>
                                    <small class="text-center">Informasi Kuis</small>
                                    <div class="step-line"></div>
                                </div>
                                <div class="step">
                                    <div class="step-number">2</div>
                                    <small class="text-center">Tambah Soal</small>
                                    <div class="step-line"></div>
                                </div>
                                <div class="step">
                                    <div class="step-number">3</div>
                                    <small class="text-center">Selesai</small>
                                    <div class="step-line"></div>
                                </div>
                            </div>

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

                            <!-- Form Buat Kuis -->
                            <div class="form-container">
                                <form method="POST" id="createQuizForm">
                                    <div class="row">
                                        <div class="col-md-8">
                                            <!-- Informasi Dasar -->
                                            <div class="mb-4">
                                                <h5 class="fw-bold mb-3">
                                                    <i class="bi bi-info-circle me-2"></i>Informasi Dasar
                                                </h5>
                                                
                                                <div class="mb-3">
                                                    <label for="judul_quiz" class="form-label fw-semibold">Judul Kuis</label>
                                                    <input type="text" class="form-control form-control-lg" 
                                                           id="judul_quiz" name="judul_quiz" 
                                                           placeholder="Contoh: Kuis Pemrograman Dasar - Variabel dan Tipe Data"
                                                           value="<?php echo isset($_POST['judul_quiz']) ? htmlspecialchars($_POST['judul_quiz']) : ''; ?>" 
                                                           required>
                                                    <div class="form-text">Buat judul yang jelas dan deskriptif</div>
                                                </div>
                                                
                                                <div class="mb-3">
                                                    <label for="deskripsi" class="form-label fw-semibold">Deskripsi Kuis</label>
                                                    <textarea class="form-control" id="deskripsi" name="deskripsi" 
                                                              rows="4" placeholder="Jelaskan tujuan dan cakupan kuis ini..."
                                                              required><?php echo isset($_POST['deskripsi']) ? htmlspecialchars($_POST['deskripsi']) : ''; ?></textarea>
                                                    <div class="form-text">Berikan instruksi atau informasi penting tentang kuis</div>
                                                </div>
                                            </div>

                                            <!-- Kursus & Materi -->
                                            <div class="mb-4">
                                                <h5 class="fw-bold mb-3">
                                                    <i class="bi bi-journal-bookmark me-2"></i>Kursus & Materi
                                                </h5>
                                                
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <div class="mb-3">
                                                            <label for="course_id" class="form-label fw-semibold">Pilih Kursus</label>
                                                            <select class="form-select" id="course_id" name="course_id" onchange="loadlms_lessons(this.value)">
                                                                <option value="">Pilih Kursus</option>
                                                                <?php while($course = $lms_courses->fetch_assoc()): ?>
                                                                    <option value="<?php echo $course['id']; ?>" 
                                                                        <?php echo (isset($_POST['course_id']) && $_POST['course_id'] == $course['id']) || $course_id == $course['id'] ? 'selected' : ''; ?>>
                                                                        <?php echo htmlspecialchars($course['judul']); ?>
                                                                    </option>
                                                                <?php endwhile; ?>
                                                            </select>
                                                            <div class="form-text">Pilih kursus yang akan dikaitkan dengan kuis</div>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <div class="mb-3">
                                                            <label for="id_lesson" class="form-label fw-semibold">Pilih Materi</label>
                                                            <select class="form-select" id="id_lesson" name="id_lesson" required>
                                                                <option value="">Pilih Materi</option>
                                                                <?php if ($lms_lessons): ?>
                                                                    <?php while($lesson = $lms_lessons->fetch_assoc()): ?>
                                                                        <option value="<?php echo $lesson['id']; ?>" 
                                                                            <?php echo (isset($_POST['id_lesson']) && $_POST['id_lesson'] == $lesson['id']) ? 'selected' : ''; ?>>
                                                                            <?php echo htmlspecialchars($lesson['judul_lesson']); ?>
                                                                        </option>
                                                                    <?php endwhile; ?>
                                                                <?php endif; ?>
                                                            </select>
                                                            <div class="form-text">Pilih materi pembelajaran yang terkait</div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>

                                            <!-- Pengaturan Kuis -->
                                            <div class="mb-4">
                                                <h5 class="fw-bold mb-3">
                                                    <i class="bi bi-gear me-2"></i>Pengaturan Kuis
                                                </h5>
                                                
                                                <div class="row">
                                                    <div class="col-md-4">
                                                        <div class="mb-3">
                                                            <label for="waktu_menit" class="form-label fw-semibold">Waktu Pengerjaan (menit)</label>
                                                            <input type="number" class="form-control" 
                                                                   id="waktu_menit" name="waktu_menit" 
                                                                   min="1" max="180" 
                                                                   value="<?php echo isset($_POST['waktu_menit']) ? $_POST['waktu_menit'] : 30; ?>"
                                                                   required>
                                                            <div class="form-text">Durasi pengerjaan kuis</div>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-4">
                                                        <div class="mb-3">
                                                            <label for="jumlah_soal" class="form-label fw-semibold">Jumlah Soal</label>
                                                            <input type="number" class="form-control" 
                                                                   id="jumlah_soal" name="jumlah_soal" 
                                                                   min="1" max="100" 
                                                                   value="<?php echo isset($_POST['jumlah_soal']) ? $_POST['jumlah_soal'] : 10; ?>"
                                                                   required>
                                                            <div class="form-text">Total soal yang akan ditampilkan</div>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-4">
                                                        <div class="mb-3">
                                                            <label for="passing_grade" class="form-label fw-semibold">Nilai Kelulusan</label>
                                                            <input type="number" class="form-control" 
                                                                   id="passing_grade" name="passing_grade" 
                                                                   min="0" max="100" 
                                                                   value="<?php echo isset($_POST['passing_grade']) ? $_POST['passing_grade'] : 60; ?>"
                                                                   required>
                                                            <div class="form-text">Nilai minimal untuk lulus (0-100)</div>
                                                        </div>
                                                    </div>
                                                </div>
                                                
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <div class="mb-3">
                                                            <label for="batas_percobaan" class="form-label fw-semibold">Batas Percobaan</label>
                                                            <input type="number" class="form-control" 
                                                                   id="batas_percobaan" name="batas_percobaan" 
                                                                   min="1" max="10" 
                                                                   value="<?php echo isset($_POST['batas_percobaan']) ? $_POST['batas_percobaan'] : 1; ?>"
                                                                   required>
                                                            <div class="form-text">Jumlah maksimal percobaan mengerjakan</div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-4">
                                            <!-- Preview & Opsi -->
                                            <div class="sticky-top" style="top: 100px;">
                                                <div class="preview-card mb-4">
                                                    <div class="quiz-icon mx-auto">
                                                        <i class="bi bi-pencil-square"></i>
                                                    </div>
                                                    <h6 class="fw-bold mb-3 text-center">Preview Kuis</h6>
                                                    <div id="previewTitle" class="fw-bold text-primary mb-2 text-center" style="min-height: 24px;">
                                                        Judul kuis akan muncul di sini
                                                    </div>
                                                    <div id="previewDescription" class="small text-muted text-center mb-3" style="min-height: 40px;">
                                                        Deskripsi kuis akan muncul di sini
                                                    </div>
                                                    <div class="row text-center">
                                                        <div class="col-6">
                                                            <small class="text-muted">Waktu</small>
                                                            <div id="previewTime" class="fw-bold">0m</div>
                                                        </div>
                                                        <div class="col-6">
                                                            <small class="text-muted">Soal</small>
                                                            <div id="previewlms_questions" class="fw-bold">0</div>
                                                        </div>
                                                    </div>
                                                    <div class="text-center mt-2">
                                                        <small id="previewPassing" class="badge bg-success">Nilai Lulus: 0</small>
                                                    </div>
                                                </div>
                                                
                                                <!-- Opsi Tambahan -->
                                                <div class="settings-card">
                                                    <h6 class="fw-bold mb-3">
                                                        <i class="bi bi-toggle-on me-2"></i>Opsi Tambahan
                                                    </h6>
                                                    
                                                    <div class="form-check form-switch mb-3">
                                                        <input class="form-check-input" type="checkbox" 
                                                               id="acak_soal" name="acak_soal" value="1" 
                                                               <?php echo isset($_POST['acak_soal']) ? 'checked' : 'checked'; ?>>
                                                        <label class="form-check-label" for="acak_soal">
                                                            Acak urutan soal
                                                        </label>
                                                        <div class="form-text">Soal akan ditampilkan secara acak</div>
                                                    </div>
                                                    
                                                    <div class="form-check form-switch mb-3">
                                                        <input class="form-check-input" type="checkbox" 
                                                               id="tampilkan_nilai" name="tampilkan_nilai" value="1" 
                                                               <?php echo isset($_POST['tampilkan_nilai']) ? 'checked' : 'checked'; ?>>
                                                        <label class="form-check-label" for="tampilkan_nilai">
                                                            Tampilkan nilai setelah selesai
                                                        </label>
                                                        <div class="form-text">Siswa dapat melihat nilai mereka</div>
                                                    </div>
                                                </div>
                                                
                                                <div class="card border-0 bg-light mt-3">
                                                    <div class="card-body">
                                                        <h6 class="fw-bold">
                                                            <i class="bi bi-lightbulb me-2"></i>Tips
                                                        </h6>
                                                        <ul class="small mb-0 ps-3">
                                                            <li>Buat soal dengan tingkat kesulitan beragam</li>
                                                            <li>Berikan waktu yang cukup untuk berpikir</li>
                                                            <li>Gunakan passing grade yang realistis</li>
                                                            <li>Test kuis sebelum diterbitkan</li>
                                                        </ul>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Tombol Aksi -->
                                    <div class="row mt-4">
                                        <div class="col-12">
                                            <div class="d-flex justify-content-between">
                                                <a href="manage_quizzes.php<?php echo $course_id ? '?course_id=' . $course_id : ''; ?>" class="btn btn-outline-secondary">
                                                    <i class="bi bi-x-circle me-2"></i>Batal
                                                </a>
                                                <button type="submit" class="btn btn-primary btn-lg">
                                                    <i class="bi bi-arrow-right-circle me-2"></i>Lanjutkan ke Tambah Soal
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Real-time preview
        document.addEventListener('DOMContentLoaded', function() {
            const judulInput = document.getElementById('judul_quiz');
            const deskripsiInput = document.getElementById('deskripsi');
            const waktuInput = document.getElementById('waktu_menit');
            const soalInput = document.getElementById('jumlah_soal');
            const passingInput = document.getElementById('passing_grade');
            
            const previewTitle = document.getElementById('previewTitle');
            const previewDescription = document.getElementById('previewDescription');
            const previewTime = document.getElementById('previewTime');
            const previewlms_questions = document.getElementById('previewlms_questions');
            const previewPassing = document.getElementById('previewPassing');
            
            // Update preview functions
            function updatePreview() {
                previewTitle.textContent = judulInput.value || 'Judul kuis akan muncul di sini';
                previewDescription.textContent = deskripsiInput.value || 'Deskripsi kuis akan muncul di sini';
                previewTime.textContent = waktuInput.value + 'm';
                previewlms_questions.textContent = soalInput.value;
                previewPassing.textContent = 'Nilai Lulus: ' + passingInput.value;
                
                // Update passing grade badge color
                const passingGrade = parseInt(passingInput.value);
                if (passingGrade >= 80) {
                    previewPassing.className = 'badge bg-success';
                } else if (passingGrade >= 60) {
                    previewPassing.className = 'badge bg-warning';
                } else {
                    previewPassing.className = 'badge bg-danger';
                }
            }
            
            // Add event listeners
            judulInput.addEventListener('input', updatePreview);
            deskripsiInput.addEventListener('input', updatePreview);
            waktuInput.addEventListener('input', updatePreview);
            soalInput.addEventListener('input', updatePreview);
            passingInput.addEventListener('input', updatePreview);
            
            // Initial preview
            updatePreview();
            
            // Form validation
            const form = document.getElementById('createQuizForm');
            form.addEventListener('submit', function(e) {
                const judul = judulInput.value.trim();
                const deskripsi = deskripsiInput.value.trim();
                const waktu = parseInt(waktuInput.value);
                const soal = parseInt(soalInput.value);
                const passing = parseInt(passingInput.value);
                
                if (judul.length < 5) {
                    e.preventDefault();
                    alert('Judul kuis harus minimal 5 karakter');
                    judulInput.focus();
                    return;
                }
                
                if (deskripsi.length < 10) {
                    e.preventDefault();
                    alert('Deskripsi kuis harus minimal 10 karakter');
                    deskripsiInput.focus();
                    return;
                }
                
                if (waktu < 1) {
                    e.preventDefault();
                    alert('Waktu pengerjaan harus minimal 1 menit');
                    waktuInput.focus();
                    return;
                }
                
                if (soal < 1) {
                    e.preventDefault();
                    alert('Jumlah soal harus minimal 1');
                    soalInput.focus();
                    return;
                }
                
                if (passing < 0 || passing > 100) {
                    e.preventDefault();
                    alert('Nilai kelulusan harus antara 0-100');
                    passingInput.focus();
                    return;
                }
            });
        });

        // Load lms_lessons based on selected course
        function loadlms_lessons(courseId) {
            const lms_lessonselect = document.getElementById('id_lesson');
            
            if (!courseId) {
                lms_lessonselect.innerHTML = '<option value="">Pilih Materi</option>';
                return;
            }
            
            // Show loading
            lms_lessonselect.innerHTML = '<option value="">Memuat materi...</option>';
            lms_lessonselect.disabled = true;
            
            // Fetch lms_lessons via AJAX
            fetch(`get_lms_lessons.php?course_id=${courseId}`)
                .then(response => response.json())
                .then(data => {
                    lms_lessonselect.innerHTML = '<option value="">Pilih Materi</option>';
                    if (data.success && data.lms_lessons) {
                        data.lms_lessons.forEach(lesson => {
                            const option = document.createElement('option');
                            option.value = lesson.id;
                            option.textContent = lesson.judul_lesson;
                            lms_lessonselect.appendChild(option);
                        });
                    } else {
                        lms_lessonselect.innerHTML = '<option value="">Tidak ada materi</option>';
                    }
                    lms_lessonselect.disabled = false;
                })
                .catch(error => {
                    console.error('Error:', error);
                    lms_lessonselect.innerHTML = '<option value="">Error memuat materi</option>';
                    lms_lessonselect.disabled = false;
                });
        }

        // Initialize if course is preselected
        document.addEventListener('DOMContentLoaded', function() {
            const lms_courseselect = document.getElementById('course_id');
            if (lms_courseselect.value) {
                loadlms_lessons(lms_courseselect.value);
            }
        });
    </script>
</body>
</html>
<?php
// Tutup koneksi database
if (isset($stmt_lms_courses)) $stmt_lms_courses->close();
if (isset($stmt_lms_lessons)) $stmt_lms_lessons->close();
$conn->close();
?>