<?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;
$filter_course = $course_id > 0 ? $course_id : null;

// Build query for 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();

// Build main query for lms_quizzes
$sql_lms_quizzes = "SELECT 
    q.id as quiz_id,
    q.judul_quiz,
    q.deskripsi,
    q.waktu_menit,
    q.jumlah_soal,
    q.passing_grade,
    q.created_at,
    l.judul_lesson,
    l.id as lesson_id,
    c.judul as judul_course,
    c.id as course_id,
    cat.nama_kategori,
    COUNT(qa.id) as total_attempts,
    AVG(qa.nilai) as avg_score,
    COUNT(CASE WHEN qa.nilai >= q.passing_grade THEN 1 END) as passed_attempts
    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
    LEFT JOIN lms_categories cat ON c.id_kategori = cat.id
    LEFT JOIN lms_quiz_attempts qa ON q.id = qa.id_quiz
    WHERE c.id_guru = ?";

$params = [$guru_id];
$types = "i";

// Apply course filter if specified
if ($filter_course) {
    $sql_lms_quizzes .= " AND c.id = ?";
    $params[] = $filter_course;
    $types .= "i";
}

$sql_lms_quizzes .= " GROUP BY q.id ORDER BY q.created_at DESC";

$stmt_lms_quizzes = $conn->prepare($sql_lms_quizzes);
if (!empty($params)) {
    $stmt_lms_quizzes->bind_param($types, ...$params);
}
$stmt_lms_quizzes->execute();
$lms_quizzes = $stmt_lms_quizzes->get_result();

// Calculate statistics
$sql_stats = "SELECT 
    COUNT(DISTINCT q.id) as total_lms_quizzes,
    COUNT(DISTINCT qa.id_siswa) as total_students_attempted,
    AVG(qa.nilai) as overall_avg_score,
    COUNT(DISTINCT c.id) as total_lms_courses_with_lms_quizzes
    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
    LEFT JOIN lms_quiz_attempts qa ON q.id = qa.id_quiz
    WHERE c.id_guru = ?";

if ($filter_course) {
    $sql_stats .= " AND c.id = ?";
}

$stmt_stats = $conn->prepare($sql_stats);
if ($filter_course) {
    $stmt_stats->bind_param('ii', $guru_id, $filter_course);
} else {
    $stmt_stats->bind_param('i', $guru_id);
}
$stmt_stats->execute();
$stats = $stmt_stats->get_result()->fetch_assoc();

// Handle quiz deletion
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_quiz'])) {
    $quiz_id = intval($_POST['quiz_id']);
    
    // Verify ownership
    $verify_sql = "SELECT q.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 = ?";
    $verify_stmt = $conn->prepare($verify_sql);
    $verify_stmt->bind_param('ii', $quiz_id, $guru_id);
    $verify_stmt->execute();
    $verify_result = $verify_stmt->get_result();
    
    if ($verify_result->num_rows > 0) {
        // Delete quiz attempts first
        $delete_attempts_sql = "DELETE FROM lms_quiz_attempts WHERE id_quiz = ?";
        $delete_attempts_stmt = $conn->prepare($delete_attempts_sql);
        $delete_attempts_stmt->bind_param('i', $quiz_id);
        $delete_attempts_stmt->execute();
        $delete_attempts_stmt->close();
        
        // Delete lms_questions
        $delete_lms_questions_sql = "DELETE FROM lms_questions WHERE id_quiz = ?";
        $delete_lms_questions_stmt = $conn->prepare($delete_lms_questions_sql);
        $delete_lms_questions_stmt->bind_param('i', $quiz_id);
        $delete_lms_questions_stmt->execute();
        $delete_lms_questions_stmt->close();
        
        // Delete quiz
        $delete_quiz_sql = "DELETE FROM lms_quizzes WHERE id = ?";
        $delete_quiz_stmt = $conn->prepare($delete_quiz_sql);
        $delete_quiz_stmt->bind_param('i', $quiz_id);
        
        if ($delete_quiz_stmt->execute()) {
            $_SESSION['success'] = "Kuis berhasil dihapus!";
        } else {
            $_SESSION['error'] = "Gagal menghapus kuis: " . $conn->error;
        }
        $delete_quiz_stmt->close();
    } else {
        $_SESSION['error'] = "Kuis tidak ditemukan atau Anda tidak memiliki akses";
    }
    
    $verify_stmt->close();
    header("Location: manage_quizzes.php" . ($filter_course ? "?course_id=" . $filter_course : ""));
    exit();
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kelola Kuis - 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;
        }
        
        .quiz-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, box-shadow 0.3s;
        }
        
        .quiz-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }
        
        .filter-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .progress-quiz {
            height: 6px;
            border-radius: 3px;
        }
        
        .badge-success { background: #28a745; }
        .badge-warning { background: #ffc107; color: #000; }
        .badge-danger { background: #dc3545; }
        .badge-info { background: #17a2b8; }
        
        .quiz-icon {
            width: 50px;
            height: 50px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
        }
        
        .action-buttons .btn {
            margin: 2px;
        }
        
        .stats-number {
            font-size: 2rem;
            font-weight: bold;
            margin-bottom: 0;
        }
        
        .pass-rate {
            font-size: 0.9rem;
            font-weight: 500;
        }
    </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 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">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h4 class="fw-bold">Kelola Kuis</h4>
                                    <p class="text-muted mb-0">Buat dan kelola kuis untuk mengukur pemahaman siswa</p>
                                </div>
                                <a href="create_quiz.php<?php echo $filter_course ? '?course_id=' . $filter_course : ''; ?>" class="btn btn-primary">
                                    <i class="bi bi-plus-circle me-2"></i>Buat Kuis Baru
                                </a>
                            </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-pencil-square display-6 text-primary mb-3"></i>
                                <h3 class="stats-number"><?php echo $stats['total_lms_quizzes'] ?? 0; ?></h3>
                                <p class="text-muted mb-0">Total Kuis</p>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="stats-card text-center">
                                <i class="bi bi-people display-6 text-success mb-3"></i>
                                <h3 class="stats-number"><?php echo $stats['total_students_attempted'] ?? 0; ?></h3>
                                <p class="text-muted mb-0">Siswa Mengerjakan</p>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="stats-card text-center">
                                <i class="bi bi-graph-up display-6 text-warning mb-3"></i>
                                <h3 class="stats-number"><?php echo number_format($stats['overall_avg_score'] ?? 0, 1); ?></h3>
                                <p class="text-muted mb-0">Rata-rata Nilai</p>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="stats-card text-center">
                                <i class="bi bi-journal-bookmark display-6 text-info mb-3"></i>
                                <h3 class="stats-number"><?php echo $stats['total_lms_courses_with_lms_quizzes'] ?? 0; ?></h3>
                                <p class="text-muted mb-0">Kursus dengan Kuis</p>
                            </div>
                        </div>
                    </div>

                    <!-- Filter Section -->
                    <div class="filter-card">
                        <div class="row">
                            <div class="col-md-6">
                                <h6 class="fw-bold mb-3">Filter berdasarkan Kursus:</h6>
                                <form method="GET" class="d-flex">
                                    <select class="form-select me-2" name="course_id" onchange="this.form.submit()">
                                        <option value="">Semua Kursus</option>
                                        <?php while($course = $lms_courses->fetch_assoc()): ?>
                                            <option value="<?php echo $course['id']; ?>" 
                                                <?php echo $filter_course == $course['id'] ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($course['judul']); ?>
                                            </option>
                                        <?php endwhile; ?>
                                    </select>
                                    <?php if ($filter_course): ?>
                                        <a href="manage_quizzes.php" class="btn btn-outline-secondary">
                                            <i class="bi bi-x-circle"></i>
                                        </a>
                                    <?php endif; ?>
                                </form>
                            </div>
                            <div class="col-md-6">
                                <h6 class="fw-bold mb-3">Cari Kuis:</h6>
                                <div class="input-group">
                                    <input type="text" class="form-control" placeholder="Cari judul kuis atau deskripsi...">
                                    <button class="btn btn-primary" type="button">
                                        <i class="bi bi-search"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- lms_quizzes List -->
                    <div class="row">
                        <div class="col-12">
                            <div class="d-flex justify-content-between align-items-center mb-4">
                                <h5 class="fw-bold mb-0">
                                    Daftar Kuis
                                    <?php if ($filter_course): ?>
                                        <small class="text-muted">(Difilter)</small>
                                    <?php endif; ?>
                                </h5>
                                <span class="badge bg-primary">
                                    <?php echo $lms_quizzes->num_rows; ?> Kuis
                                </span>
                            </div>

                            <?php if ($lms_quizzes->num_rows > 0): ?>
                                <div class="row">
                                    <?php while($quiz = $lms_quizzes->fetch_assoc()): 
                                        $pass_rate = $quiz['total_attempts'] > 0 ? 
                                            ($quiz['passed_attempts'] / $quiz['total_attempts']) * 100 : 0;
                                    ?>
                                        <div class="col-lg-6 col-xl-4 mb-4">
                                            <div class="quiz-card">
                                                <div class="d-flex justify-content-between align-items-start mb-3">
                                                    <div class="quiz-icon">
                                                        <i class="bi bi-pencil-square"></i>
                                                    </div>
                                                    <div class="dropdown">
                                                        <button class="btn btn-sm btn-outline-secondary dropdown-toggle" 
                                                                type="button" data-bs-toggle="dropdown">
                                                            <i class="bi bi-three-dots"></i>
                                                        </button>
                                                        <ul class="dropdown-menu">
                                                            <li>
                                                                <a class="dropdown-item" href="edit_quiz.php?id=<?php echo $quiz['quiz_id']; ?>">
                                                                    <i class="bi bi-pencil me-2"></i>Edit
                                                                </a>
                                                            </li>
                                                            <li>
                                                                <a class="dropdown-item" href="quiz_results.php?id=<?php echo $quiz['quiz_id']; ?>">
                                                                    <i class="bi bi-graph-up me-2"></i>Lihat Hasil
                                                                </a>
                                                            </li>
                                                            <li>
                                                                <a class="dropdown-item" href="manage_lms_questions.php?quiz_id=<?php echo $quiz['quiz_id']; ?>">
                                                                    <i class="bi bi-question-circle me-2"></i>Kelola Soal
                                                                </a>
                                                            </li>
                                                            <li><hr class="dropdown-divider"></li>
                                                            <li>
                                                                <button type="button" class="dropdown-item text-danger" 
                                                                        data-bs-toggle="modal" 
                                                                        data-bs-target="#deleteQuizModal"
                                                                        data-quiz-id="<?php echo $quiz['quiz_id']; ?>"
                                                                        data-quiz-title="<?php echo htmlspecialchars($quiz['judul_quiz']); ?>">
                                                                    <i class="bi bi-trash me-2"></i>Hapus
                                                                </button>
                                                            </li>
                                                        </ul>
                                                    </div>
                                                </div>

                                                <h6 class="fw-bold mb-2"><?php echo htmlspecialchars($quiz['judul_quiz']); ?></h6>
                                                <p class="text-muted small mb-3">
                                                    <?php 
                                                    if (strlen($quiz['deskripsi']) > 100) {
                                                        echo substr($quiz['deskripsi'], 0, 100) . '...';
                                                    } else {
                                                        echo $quiz['deskripsi'];
                                                    }
                                                    ?>
                                                </p>

                                                <div class="mb-3">
                                                    <div class="d-flex justify-content-between align-items-center mb-1">
                                                        <small class="text-muted">Kursus</small>
                                                        <small class="fw-semibold"><?php echo htmlspecialchars($quiz['judul_course']); ?></small>
                                                    </div>
                                                    <div class="d-flex justify-content-between align-items-center mb-1">
                                                        <small class="text-muted">Materi</small>
                                                        <small class="fw-semibold"><?php echo htmlspecialchars($quiz['judul_lesson']); ?></small>
                                                    </div>
                                                    <div class="d-flex justify-content-between align-items-center mb-1">
                                                        <small class="text-muted">Kategori</small>
                                                        <span class="badge bg-light text-dark"><?php echo $quiz['nama_kategori']; ?></span>
                                                    </div>
                                                </div>

                                                <div class="row text-center mb-3">
                                                    <div class="col-4">
                                                        <small class="text-muted">Soal</small>
                                                        <h6 class="fw-bold mb-0"><?php echo $quiz['jumlah_soal']; ?></h6>
                                                    </div>
                                                    <div class="col-4">
                                                        <small class="text-muted">Waktu</small>
                                                        <h6 class="fw-bold mb-0"><?php echo $quiz['waktu_menit']; ?>m</h6>
                                                    </div>
                                                    <div class="col-4">
                                                        <small class="text-muted">Nilai Min</small>
                                                        <h6 class="fw-bold mb-0"><?php echo $quiz['passing_grade']; ?></h6>
                                                    </div>
                                                </div>

                                                <div class="mb-3">
                                                    <div class="d-flex justify-content-between align-items-center mb-1">
                                                        <small class="text-muted">Tingkat Kelulusan</small>
                                                        <small class="pass-rate <?php echo $pass_rate >= 70 ? 'text-success' : ($pass_rate >= 50 ? 'text-warning' : 'text-danger'); ?>">
                                                            <?php echo number_format($pass_rate, 1); ?>%
                                                        </small>
                                                    </div>
                                                    <div class="progress progress-quiz">
                                                        <div class="progress-bar 
                                                            <?php echo $pass_rate >= 70 ? 'bg-success' : 
                                                                  ($pass_rate >= 50 ? 'bg-warning' : 'bg-danger'); ?>" 
                                                             style="width: <?php echo $pass_rate; ?>%">
                                                        </div>
                                                    </div>
                                                </div>

                                                <div class="d-flex justify-content-between align-items-center">
                                                    <small class="text-muted">
                                                        <i class="bi bi-clock me-1"></i>
                                                        <?php echo date('d M Y', strtotime($quiz['created_at'])); ?>
                                                    </small>
                                                    <div class="action-buttons">
                                                        <a href="quiz_preview.php?id=<?php echo $quiz['quiz_id']; ?>" 
                                                           class="btn btn-sm btn-outline-primary" 
                                                           title="Preview Kuis">
                                                            <i class="bi bi-eye"></i>
                                                        </a>
                                                        <a href="quiz_results.php?id=<?php echo $quiz['quiz_id']; ?>" 
                                                           class="btn btn-sm btn-outline-success" 
                                                           title="Lihat Hasil">
                                                            <i class="bi bi-graph-up"></i>
                                                        </a>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endwhile; ?>
                                </div>

                                <!-- Pagination -->
                                <nav aria-label="Page navigation" class="mt-4">
                                    <ul class="pagination justify-content-center">
                                        <li class="page-item disabled">
                                            <a class="page-link" href="#" tabindex="-1">Previous</a>
                                        </li>
                                        <li class="page-item active"><a class="page-link" href="#">1</a></li>
                                        <li class="page-item"><a class="page-link" href="#">2</a></li>
                                        <li class="page-item"><a class="page-link" href="#">3</a></li>
                                        <li class="page-item">
                                            <a class="page-link" href="#">Next</a>
                                        </li>
                                    </ul>
                                </nav>
                            <?php else: ?>
                                <div class="text-center py-5">
                                    <i class="bi bi-pencil-square display-1 text-muted"></i>
                                    <h4 class="text-muted mt-3">Belum ada kuis</h4>
                                    <p class="text-muted mb-4">
                                        <?php if ($filter_course): ?>
                                            Tidak ada kuis di kursus ini
                                        <?php else: ?>
                                            Mulai dengan membuat kuis pertama Anda
                                        <?php endif; ?>
                                    </p>
                                    <a href="create_quiz.php<?php echo $filter_course ? '?course_id=' . $filter_course : ''; ?>" class="btn btn-primary btn-lg">
                                        <i class="bi bi-plus-circle me-2"></i>Buat Kuis Pertama
                                    </a>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Delete Quiz Modal -->
    <div class="modal fade" id="deleteQuizModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Hapus Kuis</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 kuis "<span id="quizTitle"></span>"?</p>
                    <p class="text-danger small">
                        <i class="bi bi-exclamation-triangle"></i> 
                        Tindakan ini tidak dapat dibatalkan. Semua data kuis, soal, dan hasil attempt siswa akan dihapus.
                    </p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                    <form id="deleteQuizForm" method="POST">
                        <input type="hidden" name="quiz_id" id="deleteQuizId">
                        <input type="hidden" name="delete_quiz" value="1">
                        <button type="submit" class="btn btn-danger">Ya, Hapus Kuis</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() {
            // Delete quiz modal handler
            const deleteQuizModal = document.getElementById('deleteQuizModal');
            if (deleteQuizModal) {
                deleteQuizModal.addEventListener('show.bs.modal', function(event) {
                    const button = event.relatedTarget;
                    const quizId = button.getAttribute('data-quiz-id');
                    const quizTitle = button.getAttribute('data-quiz-title');
                    
                    document.getElementById('quizTitle').textContent = quizTitle;
                    document.getElementById('deleteQuizId').value = quizId;
                });
            }

            // Search functionality
            const searchInput = document.querySelector('input[type="text"]');
            const searchButton = document.querySelector('.btn-primary[type="button"]');
            
            if (searchInput && searchButton) {
                searchButton.addEventListener('click', function() {
                    const searchTerm = searchInput.value.trim();
                    if (searchTerm) {
                        // Implement search logic here
                        console.log('Searching for quiz:', searchTerm);
                        alert('Fitur pencarian kuis akan diimplementasikan');
                    }
                });
                
                searchInput.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        searchButton.click();
                    }
                });
            }

            // Auto-refresh statistics (simulated)
            setInterval(() => {
                // Simulate live updates
                const statsNumbers = document.querySelectorAll('.stats-number');
                statsNumbers.forEach(number => {
                    const current = parseInt(number.textContent);
                    if (current < 100) { // Only animate small numbers for demo
                        const newValue = current + Math.floor(Math.random() * 3);
                        number.textContent = newValue;
                    }
                });
            }, 10000); // Update every 10 seconds
        });
    </script>
</body>
</html>
<?php
// Tutup koneksi database
if (isset($stmt_lms_courses)) $stmt_lms_courses->close();
if (isset($stmt_lms_quizzes)) $stmt_lms_quizzes->close();
if (isset($stmt_stats)) $stmt_stats->close();
$conn->close();
?>