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

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

$guru_id = $_SESSION['user_id'];

// Get quiz ID from URL
$quiz_id = isset($_GET['quiz_id']) ? intval($_GET['quiz_id']) : 0;

if ($quiz_id <= 0) {
    $_SESSION['error'] = "Kuis tidak valid";
    redirect('manage_quizzes.php');
}

// Verify quiz ownership
$sql_quiz = "SELECT q.*, l.judul_lesson, c.judul as judul_course, c.id as course_id
             FROM lms_quizzes q
             LEFT JOIN lms_lessons l ON q.id_lesson = l.id
             LEFT JOIN lms_courses c ON l.id_course = c.id
             WHERE q.id = ? AND c.id_guru = ?";
$stmt_quiz = $conn->prepare($sql_quiz);
$stmt_quiz->bind_param('ii', $quiz_id, $guru_id);
$stmt_quiz->execute();
$quiz = $stmt_quiz->get_result()->fetch_assoc();

if (!$quiz) {
    $_SESSION['error'] = "Kuis tidak ditemukan atau Anda tidak memiliki akses";
    redirect('manage_quizzes.php');
}

// Get lms_questions for this quiz
$sql_lms_questions = "SELECT * FROM lms_questions WHERE id_quiz = ? ORDER BY id ASC";
$stmt_lms_questions = $conn->prepare($sql_lms_questions);
$stmt_lms_questions->bind_param('i', $quiz_id);
$stmt_lms_questions->execute();
$lms_questions = $stmt_lms_questions->get_result();

// Handle question actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = isset($_POST['action']) ? sanitize($_POST['action']) : '';
    
    if ($action === 'add_question') {
        $pertanyaan = isset($_POST['pertanyaan']) ? sanitize($_POST['pertanyaan']) : '';
        $tipe = isset($_POST['tipe']) ? sanitize($_POST['tipe']) : 'pilihan_ganda';
        $poin = isset($_POST['poin']) ? intval($_POST['poin']) : 1;
        
        // Multiple choice options
        $opsi_a = isset($_POST['opsi_a']) ? sanitize($_POST['opsi_a']) : '';
        $opsi_b = isset($_POST['opsi_b']) ? sanitize($_POST['opsi_b']) : '';
        $opsi_c = isset($_POST['opsi_c']) ? sanitize($_POST['opsi_c']) : '';
        $opsi_d = isset($_POST['opsi_d']) ? sanitize($_POST['opsi_d']) : '';
        $jawaban_benar = isset($_POST['jawaban_benar']) ? sanitize($_POST['jawaban_benar']) : '';
        
        $errors = [];
        
        if (empty($pertanyaan)) {
            $errors[] = "Pertanyaan harus diisi";
        }
        
        if ($tipe === 'pilihan_ganda') {
            if (empty($opsi_a) || empty($opsi_b)) {
                $errors[] = "Minimal opsi A dan B harus diisi untuk pilihan ganda";
            }
            if (empty($jawaban_benar)) {
                $errors[] = "Jawaban benar harus dipilih untuk pilihan ganda";
            }
        }
        
        if ($poin <= 0) {
            $errors[] = "Poin harus lebih dari 0";
        }
        
        if (empty($errors)) {
            $sql = "INSERT INTO lms_questions (id_quiz, pertanyaan, tipe, opsi_a, opsi_b, opsi_c, opsi_d, jawaban_benar, poin) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param('isssssssi', $quiz_id, $pertanyaan, $tipe, $opsi_a, $opsi_b, $opsi_c, $opsi_d, $jawaban_benar, $poin);
            
            if ($stmt->execute()) {
                $_SESSION['success'] = "Soal berhasil ditambahkan!";
                header("Location: manage_lms_questions.php?quiz_id=" . $quiz_id);
                exit();
            } else {
                $_SESSION['error'] = "Gagal menambahkan soal: " . $conn->error;
            }
            $stmt->close();
        } else {
            $_SESSION['error'] = implode("<br>", $errors);
        }
    }
    elseif ($action === 'update_question') {
        $question_id = isset($_POST['question_id']) ? intval($_POST['question_id']) : 0;
        $pertanyaan = isset($_POST['pertanyaan']) ? sanitize($_POST['pertanyaan']) : '';
        $tipe = isset($_POST['tipe']) ? sanitize($_POST['tipe']) : 'pilihan_ganda';
        $poin = isset($_POST['poin']) ? intval($_POST['poin']) : 1;
        
        $opsi_a = isset($_POST['opsi_a']) ? sanitize($_POST['opsi_a']) : '';
        $opsi_b = isset($_POST['opsi_b']) ? sanitize($_POST['opsi_b']) : '';
        $opsi_c = isset($_POST['opsi_c']) ? sanitize($_POST['opsi_c']) : '';
        $opsi_d = isset($_POST['opsi_d']) ? sanitize($_POST['opsi_d']) : '';
        $jawaban_benar = isset($_POST['jawaban_benar']) ? sanitize($_POST['jawaban_benar']) : '';
        
        // Verify question ownership
        $verify_sql = "SELECT q.id FROM lms_questions q 
                       LEFT JOIN lms_quizzes qz ON q.id_quiz = qz.id 
                       LEFT JOIN lms_lessons l ON qz.id_lesson = l.id 
                       LEFT JOIN lms_courses c ON l.id_course = c.id 
                       WHERE q.id = ? AND c.id_guru = ?";
        $verify_stmt = $conn->prepare($verify_sql);
        $verify_stmt->bind_param('ii', $question_id, $guru_id);
        $verify_stmt->execute();
        $verify_result = $verify_stmt->get_result();
        
        if ($verify_result->num_rows > 0) {
            $update_sql = "UPDATE lms_questions SET 
                          pertanyaan = ?, tipe = ?, opsi_a = ?, opsi_b = ?, 
                          opsi_c = ?, opsi_d = ?, jawaban_benar = ?, poin = ? 
                          WHERE id = ?";
            
            $update_stmt = $conn->prepare($update_sql);
            $update_stmt->bind_param('sssssssii', $pertanyaan, $tipe, $opsi_a, $opsi_b, $opsi_c, $opsi_d, $jawaban_benar, $poin, $question_id);
            
            if ($update_stmt->execute()) {
                $_SESSION['success'] = "Soal berhasil diperbarui!";
            } else {
                $_SESSION['error'] = "Gagal memperbarui soal: " . $conn->error;
            }
            $update_stmt->close();
        } else {
            $_SESSION['error'] = "Soal tidak ditemukan atau Anda tidak memiliki akses";
        }
        $verify_stmt->close();
        
        header("Location: manage_lms_questions.php?quiz_id=" . $quiz_id);
        exit();
    }
    elseif ($action === 'delete_question') {
        $question_id = isset($_POST['question_id']) ? intval($_POST['question_id']) : 0;
        
        // Verify question ownership
        $verify_sql = "SELECT q.id FROM lms_questions q 
                       LEFT JOIN lms_quizzes qz ON q.id_quiz = qz.id 
                       LEFT JOIN lms_lessons l ON qz.id_lesson = l.id 
                       LEFT JOIN lms_courses c ON l.id_course = c.id 
                       WHERE q.id = ? AND c.id_guru = ?";
        $verify_stmt = $conn->prepare($verify_sql);
        $verify_stmt->bind_param('ii', $question_id, $guru_id);
        $verify_stmt->execute();
        $verify_result = $verify_stmt->get_result();
        
        if ($verify_result->num_rows > 0) {
            $delete_sql = "DELETE FROM lms_questions WHERE id = ?";
            $delete_stmt = $conn->prepare($delete_sql);
            $delete_stmt->bind_param('i', $question_id);
            
            if ($delete_stmt->execute()) {
                $_SESSION['success'] = "Soal berhasil dihapus!";
            } else {
                $_SESSION['error'] = "Gagal menghapus soal: " . $conn->error;
            }
            $delete_stmt->close();
        } else {
            $_SESSION['error'] = "Soal tidak ditemukan atau Anda tidak memiliki akses";
        }
        $verify_stmt->close();
        
        header("Location: manage_lms_questions.php?quiz_id=" . $quiz_id);
        exit();
    }
}

// Calculate statistics
$total_lms_questions = $lms_questions->num_rows;
$total_points = 0;
$multiple_choice_count = 0;
$essay_count = 0;

while($question = $lms_questions->fetch_assoc()) {
    $total_points += $question['poin'];
    if ($question['tipe'] === 'pilihan_ganda') {
        $multiple_choice_count++;
    } else {
        $essay_count++;
    }
}
$lms_questions->data_seek(0); // Reset pointer
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kelola Soal - <?php echo htmlspecialchars($quiz['judul_quiz']); ?> - 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);
        }
        
        .stats-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            border: none;
        }
        
        .question-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            border: none;
            transition: transform 0.3s;
        }
        
        .question-card:hover {
            transform: translateY(-2px);
        }
        
        .form-container {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .option-item {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
            border-left: 4px solid var(--primary-color);
        }
        
        .correct-answer {
            background: #d4edda;
            border-left-color: #28a745;
        }
        
        .question-number {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: var(--primary-color);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin-right: 15px;
        }
        
        .badge-mc { background: #17a2b8; }
        .badge-essay { background: #6c757d; }
        
        .action-buttons .btn {
            margin: 2px;
        }
        
        .tab-content {
            background: white;
            border-radius: 0 0 10px 10px;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .nav-tabs-custom .nav-link {
            border: none;
            padding: 15px 25px;
            font-weight: 500;
            color: #6c757d;
            border-bottom: 3px solid transparent;
        }
        
        .nav-tabs-custom .nav-link.active {
            color: var(--primary-color);
            border-bottom: 3px solid var(--primary-color);
            background: transparent;
        }
    </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">Kelola Soal Kuis</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">
                    <!-- Notifikasi -->
                    <?php if (isset($_SESSION['success'])): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['success']; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                        <?php unset($_SESSION['success']); ?>
                    <?php endif; ?>

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

                    <!-- Header Section -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <nav aria-label="breadcrumb">
                                <ol class="breadcrumb">
                                    <li class="breadcrumb-item"><a href="manage_quizzes.php">Kelola Kuis</a></li>
                                    <li class="breadcrumb-item active"><?php echo htmlspecialchars($quiz['judul_quiz']); ?></li>
                                </ol>
                            </nav>
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h4 class="fw-bold">Kelola Soal</h4>
                                    <p class="text-muted mb-0">
                                        Kuis: <strong><?php echo htmlspecialchars($quiz['judul_quiz']); ?></strong> | 
                                        Kursus: <?php echo htmlspecialchars($quiz['judul_course']); ?>
                                    </p>
                                </div>
                                <div>
                                    <a href="manage_quizzes.php?course_id=<?php echo $quiz['course_id']; ?>" class="btn btn-outline-secondary me-2">
                                        <i class="bi bi-arrow-left me-2"></i>Kembali
                                    </a>
                                    <a href="quiz_preview.php?id=<?php echo $quiz_id; ?>" class="btn btn-primary">
                                        <i class="bi bi-eye me-2"></i>Preview Kuis
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="stats-card text-center">
                                <i class="bi bi-question-circle display-6 text-primary mb-3"></i>
                                <h3 class="fw-bold"><?php echo $total_lms_questions; ?></h3>
                                <p class="text-muted mb-0">Total Soal</p>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="stats-card text-center">
                                <i class="bi bi-check-circle display-6 text-success mb-3"></i>
                                <h3 class="fw-bold"><?php echo $multiple_choice_count; ?></h3>
                                <p class="text-muted mb-0">Pilihan Ganda</p>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="stats-card text-center">
                                <i class="bi bi-pencil display-6 text-warning mb-3"></i>
                                <h3 class="fw-bold"><?php echo $essay_count; ?></h3>
                                <p class="text-muted mb-0">Essay</p>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="stats-card text-center">
                                <i class="bi bi-star display-6 text-info mb-3"></i>
                                <h3 class="fw-bold"><?php echo $total_points; ?></h3>
                                <p class="text-muted mb-0">Total Poin</p>
                            </div>
                        </div>
                    </div>

                    <!-- Tabs Navigation -->
                    <ul class="nav nav-tabs nav-tabs-custom" id="lms_questionsTabs" 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 Soal (<?php echo $total_lms_questions; ?>)
                            </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 Soal
                            </button>
                        </li>
                    </ul>

                    <!-- Tabs Content -->
                    <div class="tab-content" id="lms_questionsTabsContent">
                        <!-- Tab 1: Daftar Soal -->
                        <div class="tab-pane fade show active" id="list" role="tabpanel">
                            <?php if ($total_lms_questions > 0): ?>
                                <div class="lms_questions-list">
                                    <?php 
                                    $question_number = 1;
                                    while($question = $lms_questions->fetch_assoc()): 
                                    ?>
                                        <div class="question-card">
                                            <div class="d-flex justify-content-between align-items-start mb-3">
                                                <div class="d-flex align-items-center">
                                                    <div class="question-number"><?php echo $question_number; ?></div>
                                                    <div>
                                                        <h6 class="fw-bold mb-1"><?php echo htmlspecialchars($question['pertanyaan']); ?></h6>
                                                        <div class="d-flex gap-2">
                                                            <span class="badge <?php echo $question['tipe'] === 'pilihan_ganda' ? 'badge-mc' : 'badge-essay'; ?>">
                                                                <?php echo $question['tipe'] === 'pilihan_ganda' ? 'Pilihan Ganda' : 'Essay'; ?>
                                                            </span>
                                                            <span class="badge bg-light text-dark">
                                                                <?php echo $question['poin']; ?> Poin
                                                            </span>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="action-buttons">
                                                    <button class="btn btn-sm btn-outline-warning" 
                                                            data-bs-toggle="modal" 
                                                            data-bs-target="#editQuestionModal"
                                                            data-question-id="<?php echo $question['id']; ?>"
                                                            data-pertanyaan="<?php echo htmlspecialchars($question['pertanyaan']); ?>"
                                                            data-tipe="<?php echo $question['tipe']; ?>"
                                                            data-opsi-a="<?php echo htmlspecialchars($question['opsi_a']); ?>"
                                                            data-opsi-b="<?php echo htmlspecialchars($question['opsi_b']); ?>"
                                                            data-opsi-c="<?php echo htmlspecialchars($question['opsi_c']); ?>"
                                                            data-opsi-d="<?php echo htmlspecialchars($question['opsi_d']); ?>"
                                                            data-jawaban-benar="<?php echo $question['jawaban_benar']; ?>"
                                                            data-poin="<?php echo $question['poin']; ?>">
                                                        <i class="bi bi-pencil"></i>
                                                    </button>
                                                    <button class="btn btn-sm btn-outline-danger" 
                                                            data-bs-toggle="modal" 
                                                            data-bs-target="#deleteQuestionModal"
                                                            data-question-id="<?php echo $question['id']; ?>"
                                                            data-pertanyaan="<?php echo htmlspecialchars($question['pertanyaan']); ?>">
                                                        <i class="bi bi-trash"></i>
                                                    </button>
                                                </div>
                                            </div>

                                            <?php if ($question['tipe'] === 'pilihan_ganda'): ?>
                                                <div class="options-list">
                                                    <div class="option-item <?php echo $question['jawaban_benar'] === 'A' ? 'correct-answer' : ''; ?>">
                                                        <strong>A.</strong> <?php echo htmlspecialchars($question['opsi_a']); ?>
                                                        <?php if ($question['jawaban_benar'] === 'A'): ?>
                                                            <span class="badge bg-success float-end">Jawaban Benar</span>
                                                        <?php endif; ?>
                                                    </div>
                                                    <div class="option-item <?php echo $question['jawaban_benar'] === 'B' ? 'correct-answer' : ''; ?>">
                                                        <strong>B.</strong> <?php echo htmlspecialchars($question['opsi_b']); ?>
                                                        <?php if ($question['jawaban_benar'] === 'B'): ?>
                                                            <span class="badge bg-success float-end">Jawaban Benar</span>
                                                        <?php endif; ?>
                                                    </div>
                                                    <?php if (!empty($question['opsi_c'])): ?>
                                                        <div class="option-item <?php echo $question['jawaban_benar'] === 'C' ? 'correct-answer' : ''; ?>">
                                                            <strong>C.</strong> <?php echo htmlspecialchars($question['opsi_c']); ?>
                                                            <?php if ($question['jawaban_benar'] === 'C'): ?>
                                                                <span class="badge bg-success float-end">Jawaban Benar</span>
                                                            <?php endif; ?>
                                                        </div>
                                                    <?php endif; ?>
                                                    <?php if (!empty($question['opsi_d'])): ?>
                                                        <div class="option-item <?php echo $question['jawaban_benar'] === 'D' ? 'correct-answer' : ''; ?>">
                                                            <strong>D.</strong> <?php echo htmlspecialchars($question['opsi_d']); ?>
                                                            <?php if ($question['jawaban_benar'] === 'D'): ?>
                                                                <span class="badge bg-success float-end">Jawaban Benar</span>
                                                            <?php endif; ?>
                                                        </div>
                                                    <?php endif; ?>
                                                </div>
                                            <?php else: ?>
                                                <div class="alert alert-info">
                                                    <i class="bi bi-info-circle me-2"></i>
                                                    Soal essay - jawaban akan dinilai manual oleh guru
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                        <?php $question_number++; ?>
                                    <?php endwhile; ?>
                                </div>
                            <?php else: ?>
                                <div class="text-center py-5">
                                    <i class="bi bi-question-circle display-1 text-muted"></i>
                                    <h4 class="text-muted mt-3">Belum ada soal</h4>
                                    <p class="text-muted mb-4">Mulai dengan menambahkan soal pertama untuk kuis ini</p>
                                    <button class="btn btn-primary" data-bs-toggle="tab" data-bs-target="#add">
                                        <i class="bi bi-plus-circle me-2"></i>Tambah Soal Pertama
                                    </button>
                                </div>
                            <?php endif; ?>
                        </div>

                        <!-- Tab 2: Tambah Soal -->
                        <div class="tab-pane fade" id="add" role="tabpanel">
                            <div class="form-container">
                                <h5 class="fw-bold mb-4">
                                    <i class="bi bi-plus-circle me-2"></i>Tambah Soal Baru
                                </h5>
                                
                                <form method="POST" id="addQuestionForm">
                                    <input type="hidden" name="action" value="add_question">
                                    
                                    <div class="mb-4">
                                        <label for="tipe" class="form-label fw-semibold">Tipe Soal</label>
                                        <select class="form-select" id="tipe" name="tipe" required>
                                            <option value="pilihan_ganda">Pilihan Ganda</option>
                                            <option value="essay">Essay</option>
                                        </select>
                                        <div class="form-text">Pilih tipe soal yang ingin dibuat</div>
                                    </div>
                                    
                                    <div class="mb-4">
                                        <label for="pertanyaan" class="form-label fw-semibold">Pertanyaan</label>
                                        <textarea class="form-control" id="pertanyaan" name="pertanyaan" 
                                                  rows="4" placeholder="Tulis pertanyaan di sini..." required></textarea>
                                        <div class="form-text">Gunakan format yang jelas dan mudah dipahami</div>
                                    </div>
                                    
                                    <!-- Multiple Choice Options -->
                                    <div id="multipleChoiceOptions">
                                        <h6 class="fw-bold mb-3">Opsi Jawaban</h6>
                                        
                                        <div class="mb-3">
                                            <label for="opsi_a" class="form-label">Opsi A</label>
                                            <input type="text" class="form-control" id="opsi_a" name="opsi_a" 
                                                   placeholder="Jawaban A">
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="opsi_b" class="form-label">Opsi B</label>
                                            <input type="text" class="form-control" id="opsi_b" name="opsi_b" 
                                                   placeholder="Jawaban B">
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="opsi_c" class="form-label">Opsi C</label>
                                            <input type="text" class="form-control" id="opsi_c" name="opsi_c" 
                                                   placeholder="Jawaban C (opsional)">
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="opsi_d" class="form-label">Opsi D</label>
                                            <input type="text" class="form-control" id="opsi_d" name="opsi_d" 
                                                   placeholder="Jawaban D (opsional)">
                                        </div>
                                        
                                        <div class="mb-4">
                                            <label for="jawaban_benar" class="form-label fw-semibold">Jawaban Benar</label>
                                            <select class="form-select" id="jawaban_benar" name="jawaban_benar">
                                                <option value="">Pilih jawaban benar</option>
                                                <option value="A">A</option>
                                                <option value="B">B</option>
                                                <option value="C">C</option>
                                                <option value="D">D</option>
                                            </select>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-4">
                                        <label for="poin" class="form-label fw-semibold">Poin</label>
                                        <input type="number" class="form-control" id="poin" name="poin" 
                                               min="1" max="10" value="1" required>
                                        <div class="form-text">Nilai untuk soal ini (1-10)</div>
                                    </div>
                                    
                                    <div class="d-flex justify-content-between">
                                        <button type="button" class="btn btn-outline-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 Soal
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit Question Modal -->
    <div class="modal fade" id="editQuestionModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Edit Soal</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="POST" id="editQuestionForm">
                    <input type="hidden" name="action" value="update_question">
                    <input type="hidden" name="question_id" id="editQuestionId">
                    
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="editTipe" class="form-label">Tipe Soal</label>
                            <select class="form-select" id="editTipe" name="tipe" required>
                                <option value="pilihan_ganda">Pilihan Ganda</option>
                                <option value="essay">Essay</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label for="editPertanyaan" class="form-label">Pertanyaan</label>
                            <textarea class="form-control" id="editPertanyaan" name="pertanyaan" rows="4" required></textarea>
                        </div>
                        
                        <div id="editMultipleChoiceOptions">
                            <div class="mb-3">
                                <label for="editOpsiA" class="form-label">Opsi A</label>
                                <input type="text" class="form-control" id="editOpsiA" name="opsi_a">
                            </div>
                            
                            <div class="mb-3">
                                <label for="editOpsiB" class="form-label">Opsi B</label>
                                <input type="text" class="form-control" id="editOpsiB" name="opsi_b">
                            </div>
                            
                            <div class="mb-3">
                                <label for="editOpsiC" class="form-label">Opsi C</label>
                                <input type="text" class="form-control" id="editOpsiC" name="opsi_c">
                            </div>
                            
                            <div class="mb-3">
                                <label for="editOpsiD" class="form-label">Opsi D</label>
                                <input type="text" class="form-control" id="editOpsiD" name="opsi_d">
                            </div>
                            
                            <div class="mb-3">
                                <label for="editJawabanBenar" class="form-label">Jawaban Benar</label>
                                <select class="form-select" id="editJawabanBenar" name="jawaban_benar">
                                    <option value="">Pilih jawaban benar</option>
                                    <option value="A">A</option>
                                    <option value="B">B</option>
                                    <option value="C">C</option>
                                    <option value="D">D</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="editPoin" class="form-label">Poin</label>
                            <input type="number" class="form-control" id="editPoin" name="poin" min="1" max="10" required>
                        </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 Question Modal -->
    <div class="modal fade" id="deleteQuestionModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Hapus Soal</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Apakah Anda yakin ingin menghapus soal ini?</p>
                    <p class="fw-semibold" id="deleteQuestionText"></p>
                    <p class="text-danger small">
                        <i class="bi bi-exclamation-triangle"></i> 
                        Tindakan ini tidak dapat dibatalkan.
                    </p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                    <form method="POST" id="deleteQuestionForm">
                        <input type="hidden" name="action" value="delete_question">
                        <input type="hidden" name="question_id" id="deleteQuestionId">
                        <button type="submit" class="btn btn-danger">Ya, Hapus Soal</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Toggle multiple choice options based on question type
            const questionType = document.getElementById('tipe');
            const multipleChoiceOptions = document.getElementById('multipleChoiceOptions');
            
            function toggleOptions() {
                if (questionType.value === 'pilihan_ganda') {
                    multipleChoiceOptions.style.display = 'block';
                    document.getElementById('jawaban_benar').required = true;
                    document.getElementById('opsi_a').required = true;
                    document.getElementById('opsi_b').required = true;
                } else {
                    multipleChoiceOptions.style.display = 'none';
                    document.getElementById('jawaban_benar').required = false;
                    document.getElementById('opsi_a').required = false;
                    document.getElementById('opsi_b').required = false;
                }
            }
            
            questionType.addEventListener('change', toggleOptions);
            toggleOptions(); // Initial call
            
            // Edit question modal handler
            const editQuestionModal = document.getElementById('editQuestionModal');
            if (editQuestionModal) {
                editQuestionModal.addEventListener('show.bs.modal', function(event) {
                    const button = event.relatedTarget;
                    const questionId = button.getAttribute('data-question-id');
                    const pertanyaan = button.getAttribute('data-pertanyaan');
                    const tipe = button.getAttribute('data-tipe');
                    const opsiA = button.getAttribute('data-opsi-a');
                    const opsiB = button.getAttribute('data-opsi-b');
                    const opsiC = button.getAttribute('data-opsi-c');
                    const opsiD = button.getAttribute('data-opsi-d');
                    const jawabanBenar = button.getAttribute('data-jawaban-benar');
                    const poin = button.getAttribute('data-poin');
                    
                    document.getElementById('editQuestionId').value = questionId;
                    document.getElementById('editPertanyaan').value = pertanyaan;
                    document.getElementById('editTipe').value = tipe;
                    document.getElementById('editOpsiA').value = opsiA;
                    document.getElementById('editOpsiB').value = opsiB;
                    document.getElementById('editOpsiC').value = opsiC;
                    document.getElementById('editOpsiD').value = opsiD;
                    document.getElementById('editJawabanBenar').value = jawabanBenar;
                    document.getElementById('editPoin').value = poin;
                    
                    // Toggle options for edit modal
                    toggleEditOptions();
                });
            }
            
            // Toggle options for edit modal
            const editTipe = document.getElementById('editTipe');
            const editMultipleChoiceOptions = document.getElementById('editMultipleChoiceOptions');
            
            function toggleEditOptions() {
                if (editTipe.value === 'pilihan_ganda') {
                    editMultipleChoiceOptions.style.display = 'block';
                } else {
                    editMultipleChoiceOptions.style.display = 'none';
                }
            }
            
            editTipe.addEventListener('change', toggleEditOptions);
            
            // Delete question modal handler
            const deleteQuestionModal = document.getElementById('deleteQuestionModal');
            if (deleteQuestionModal) {
                deleteQuestionModal.addEventListener('show.bs.modal', function(event) {
                    const button = event.relatedTarget;
                    const questionId = button.getAttribute('data-question-id');
                    const pertanyaan = button.getAttribute('data-pertanyaan');
                    
                    document.getElementById('deleteQuestionId').value = questionId;
                    document.getElementById('deleteQuestionText').textContent = pertanyaan;
                });
            }
            
            // Form validation for add question
            const addQuestionForm = document.getElementById('addQuestionForm');
            if (addQuestionForm) {
                addQuestionForm.addEventListener('submit', function(e) {
                    const pertanyaan = document.getElementById('pertanyaan').value.trim();
                    const tipe = document.getElementById('tipe').value;
                    const poin = parseInt(document.getElementById('poin').value);
                    
                    if (pertanyaan.length < 5) {
                        e.preventDefault();
                        alert('Pertanyaan harus minimal 5 karakter');
                        document.getElementById('pertanyaan').focus();
                        return;
                    }
                    
                    if (poin < 1 || poin > 10) {
                        e.preventDefault();
                        alert('Poin harus antara 1-10');
                        document.getElementById('poin').focus();
                        return;
                    }
                    
                    if (tipe === 'pilihan_ganda') {
                        const opsiA = document.getElementById('opsi_a').value.trim();
                        const opsiB = document.getElementById('opsi_b').value.trim();
                        const jawabanBenar = document.getElementById('jawaban_benar').value;
                        
                        if (opsiA.length === 0 || opsiB.length === 0) {
                            e.preventDefault();
                            alert('Opsi A dan B harus diisi untuk soal pilihan ganda');
                            return;
                        }
                        
                        if (!jawabanBenar) {
                            e.preventDefault();
                            alert('Pilih jawaban benar untuk soal pilihan ganda');
                            return;
                        }
                    }
                });
            }
        });
    </script>
</body>
</html>
<?php
// Tutup koneksi database
if (isset($stmt_quiz)) $stmt_quiz->close();
if (isset($stmt_lms_questions)) $stmt_lms_questions->close();
$conn->close();
?>