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

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

$guru_id = $_SESSION['user_id'];

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

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

// Get quiz details with verification of 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 quiz attempts with student details - PERBAIKAN
$sql_attempts = "SELECT 
    qa.*,
    u.nama_lengkap as nama_siswa,
    u.email as email_siswa,
    u.foto_profil,
    CASE 
        WHEN qa.waktu_selesai IS NOT NULL THEN 
            TIMESTAMPDIFF(MINUTE, qa.waktu_mulai, qa.waktu_selesai)
        ELSE 
            TIMESTAMPDIFF(MINUTE, qa.waktu_mulai, NOW())
    END as waktu_pengerjaan
    FROM lms_quiz_attempts qa
    LEFT JOIN lms_users u ON qa.id_siswa = u.id
    WHERE qa.id_quiz = ? 
    ORDER BY qa.nilai DESC, qa.waktu_selesai DESC";
$stmt_attempts = $conn->prepare($sql_attempts);
$stmt_attempts->bind_param('i', $quiz_id);
$stmt_attempts->execute();
$attempts = $stmt_attempts->get_result();

// Calculate statistics - PERBAIKAN
$sql_stats = "SELECT 
    COUNT(*) as total_attempts,
    AVG(nilai) as avg_score,
    MAX(nilai) as highest_score,
    MIN(nilai) as lowest_score,
    COUNT(CASE WHEN nilai >= ? THEN 1 END) as passed_attempts,
    AVG(CASE 
        WHEN waktu_selesai IS NOT NULL THEN 
            TIMESTAMPDIFF(MINUTE, waktu_mulai, waktu_selesai)
        ELSE NULL
    END) as avg_time,
    COUNT(DISTINCT id_siswa) as unique_students
    FROM lms_quiz_attempts 
    WHERE id_quiz = ?";
$stmt_stats = $conn->prepare($sql_stats);
$stmt_stats->bind_param('ii', $quiz['passing_grade'], $quiz_id);
$stmt_stats->execute();
$stats = $stmt_stats->get_result()->fetch_assoc();

// Calculate pass rate
$pass_rate = $stats['total_attempts'] > 0 ? 
    ($stats['passed_attempts'] / $stats['total_attempts']) * 100 : 0;

// Get score distribution
$sql_distribution = "SELECT 
    CASE 
        WHEN nilai >= 90 THEN '90-100'
        WHEN nilai >= 80 THEN '80-89'
        WHEN nilai >= 70 THEN '70-79'
        WHEN nilai >= 60 THEN '60-69'
        WHEN nilai >= 50 THEN '50-59'
        ELSE '0-49'
    END as score_range,
    COUNT(*) as count
    FROM lms_quiz_attempts 
    WHERE id_quiz = ?
    GROUP BY score_range
    ORDER BY score_range DESC";
$stmt_distribution = $conn->prepare($sql_distribution);
$stmt_distribution->bind_param('i', $quiz_id);
$stmt_distribution->execute();
$distribution = $stmt_distribution->get_result();

// Handle export request
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="hasil_kuis_' . $quiz_id . '.csv"');
    
    $output = fopen('php://output', 'w');
    
    // Header CSV
    fputcsv($output, [
        'Nama Siswa', 
        'Email', 
        'Nilai', 
        'Status', 
        'Waktu Mulai', 
        'Waktu Selesai',
        'Durasi (menit)'
    ]);
    
    // Data
    while($attempt = $attempts->fetch_assoc()) {
        $status = $attempt['nilai'] >= $quiz['passing_grade'] ? 'Lulus' : 'Tidak Lulus';
        fputcsv($output, [
            $attempt['nama_siswa'],
            $attempt['email_siswa'],
            $attempt['nilai'],
            $status,
            $attempt['waktu_mulai'],
            $attempt['waktu_selesai'],
            $attempt['waktu_pengerjaan']
        ]);
    }
    
    fclose($output);
    exit();
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hasil Kuis - <?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">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <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);
        }
        
        .results-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 40px 0;
            margin-bottom: 30px;
        }
        
        .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;
        }
        
        .results-container {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }
        
        .attempt-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 15px;
            border: 2px solid #e9ecef;
            transition: all 0.3s;
        }
        
        .attempt-card:hover {
            border-color: var(--primary-color);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }
        
        .attempt-card.passed {
            border-left: 4px solid #28a745;
        }
        
        .attempt-card.failed {
            border-left: 4px solid #dc3545;
        }
        
        .student-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            object-fit: cover;
        }
        
        .avatar-placeholder {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: var(--primary-color);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
        }
        
        .score-badge {
            font-size: 1.1rem;
            font-weight: bold;
            padding: 8px 15px;
        }
        
        .progress-quiz {
            height: 8px;
            border-radius: 4px;
        }
        
        .chart-container {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .filter-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .export-btn {
            background: linear-gradient(45deg, #28a745, #20c997);
            border: none;
            color: white;
        }
        
        .time-badge {
            background: #6c757d;
            color: white;
            font-size: 0.8rem;
        }
    </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" href="manage_quizzes.php">
                                <i class="bi bi-pencil-square"></i> Kelola Kuis
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" 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">Hasil 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">
                    <!-- Results Header -->
                    <div class="results-header">
                        <div class="container">
                            <nav aria-label="breadcrumb">
                                <ol class="breadcrumb breadcrumb-dark">
                                    <li class="breadcrumb-item"><a href="manage_quizzes.php" class="text-white-50">Kelola Kuis</a></li>
                                    <li class="breadcrumb-item active text-white">Hasil Kuis</li>
                                </ol>
                            </nav>
                            
                            <div class="row align-items-center">
                                <div class="col-lg-8">
                                    <h1 class="display-5 fw-bold mb-3"><?php echo htmlspecialchars($quiz['judul_quiz']); ?></h1>
                                    <p class="lead mb-4 opacity-75">Analisis hasil pengerjaan kuis oleh siswa</p>
                                    
                                    <div class="row">
                                        <div class="col-md-3 col-6 mb-3">
                                            <div class="text-white">
                                                <i class="bi bi-people display-6 mb-2"></i>
                                                <h4 class="fw-bold"><?php echo $stats['unique_students'] ?? 0; ?></h4>
                                                <small>Siswa Unik</small>
                                            </div>
                                        </div>
                                        <div class="col-md-3 col-6 mb-3">
                                            <div class="text-white">
                                                <i class="bi bi-check-circle display-6 mb-2"></i>
                                                <h4 class="fw-bold"><?php echo number_format($pass_rate, 1); ?>%</h4>
                                                <small>Tingkat Kelulusan</small>
                                            </div>
                                        </div>
                                        <div class="col-md-3 col-6 mb-3">
                                            <div class="text-white">
                                                <i class="bi bi-star display-6 mb-2"></i>
                                                <h4 class="fw-bold"><?php echo number_format($stats['avg_score'] ?? 0, 1); ?></h4>
                                                <small>Rata-rata Nilai</small>
                                            </div>
                                        </div>
                                        <div class="col-md-3 col-6 mb-3">
                                            <div class="text-white">
                                                <i class="bi bi-clock display-6 mb-2"></i>
                                                <h4 class="fw-bold"><?php echo number_format($stats['avg_time'] ?? 0, 1); ?>m</h4>
                                                <small>Rata-rata Waktu</small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-lg-4 text-center">
                                    <div class="bg-white rounded-3 p-4 shadow">
                                        <h5 class="fw-bold mb-3">Aksi Cepat</h5>
                                        <div class="d-grid gap-2">
                                            <a href="quiz_preview.php?id=<?php echo $quiz_id; ?>" class="btn btn-outline-primary">
                                                <i class="bi bi-eye me-2"></i>Preview Kuis
                                            </a>
                                            <a href="manage_lms_questions.php?quiz_id=<?php echo $quiz_id; ?>" class="btn btn-outline-success">
                                                <i class="bi bi-pencil me-2"></i>Kelola Soal
                                            </a>
                                            <a href="quiz_results.php?id=<?php echo $quiz_id; ?>&export=csv" class="btn export-btn">
                                                <i class="bi bi-download me-2"></i>Export CSV
                                            </a>
                                            <a href="manage_quizzes.php?course_id=<?php echo $quiz['course_id']; ?>" class="btn btn-outline-secondary">
                                                <i class="bi bi-arrow-left me-2"></i>Kembali
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="container">
                        <!-- Statistics Cards -->
                        <div class="row mb-4">
                            <div class="col-xl-2 col-md-4 col-6 mb-3">
                                <div class="stats-card text-center">
                                    <i class="bi bi-people display-6 text-primary mb-3"></i>
                                    <h3 class="fw-bold"><?php echo $stats['total_attempts'] ?? 0; ?></h3>
                                    <p class="text-muted mb-0">Total Attempt</p>
                                </div>
                            </div>
                            <div class="col-xl-2 col-md-4 col-6 mb-3">
                                <div class="stats-card text-center">
                                    <i class="bi bi-person-check display-6 text-success mb-3"></i>
                                    <h3 class="fw-bold"><?php echo $stats['passed_attempts'] ?? 0; ?></h3>
                                    <p class="text-muted mb-0">Lulus</p>
                                </div>
                            </div>
                            <div class="col-xl-2 col-md-4 col-6 mb-3">
                                <div class="stats-card text-center">
                                    <i class="bi bi-person-x display-6 text-danger mb-3"></i>
                                    <h3 class="fw-bold"><?php echo ($stats['total_attempts'] ?? 0) - ($stats['passed_attempts'] ?? 0); ?></h3>
                                    <p class="text-muted mb-0">Tidak Lulus</p>
                                </div>
                            </div>
                            <div class="col-xl-2 col-md-4 col-6 mb-3">
                                <div class="stats-card text-center">
                                    <i class="bi bi-trophy display-6 text-warning mb-3"></i>
                                    <h3 class="fw-bold"><?php echo $stats['highest_score'] ?? 0; ?></h3>
                                    <p class="text-muted mb-0">Nilai Tertinggi</p>
                                </div>
                            </div>
                            <div class="col-xl-2 col-md-4 col-6 mb-3">
                                <div class="stats-card text-center">
                                    <i class="bi bi-graph-down display-6 text-info mb-3"></i>
                                    <h3 class="fw-bold"><?php echo $stats['lowest_score'] ?? 0; ?></h3>
                                    <p class="text-muted mb-0">Nilai Terendah</p>
                                </div>
                            </div>
                            <div class="col-xl-2 col-md-4 col-6 mb-3">
                                <div class="stats-card text-center">
                                    <i class="bi bi-check-circle display-6 text-secondary mb-3"></i>
                                    <h3 class="fw-bold"><?php echo $quiz['passing_grade']; ?></h3>
                                    <p class="text-muted mb-0">Nilai Lulus</p>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <!-- Main Content -->
                            <div class="col-lg-8">
                                <!-- Filter Section -->
                                <div class="filter-card">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <h6 class="fw-bold mb-3">Filter Status:</h6>
                                            <div class="btn-group w-100" role="group">
                                                <button type="button" class="btn btn-outline-primary active" data-filter="all">
                                                    Semua (<?php echo $stats['total_attempts'] ?? 0; ?>)
                                                </button>
                                                <button type="button" class="btn btn-outline-success" data-filter="passed">
                                                    Lulus (<?php echo $stats['passed_attempts'] ?? 0; ?>)
                                                </button>
                                                <button type="button" class="btn btn-outline-danger" data-filter="failed">
                                                    Tidak Lulus (<?php echo ($stats['total_attempts'] ?? 0) - ($stats['passed_attempts'] ?? 0); ?>)
                                                </button>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <h6 class="fw-bold mb-3">Cari Siswa:</h6>
                                            <div class="input-group">
                                                <input type="text" class="form-control" placeholder="Nama siswa atau email..." id="searchStudent">
                                                <button class="btn btn-primary" type="button">
                                                    <i class="bi bi-search"></i>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Results List -->
                                <div class="results-container">
                                    <div class="d-flex justify-content-between align-items-center mb-4">
                                        <h4 class="fw-bold mb-0">
                                            <i class="bi bi-list-check me-2"></i>Daftar Hasil
                                        </h4>
                                        <span class="badge bg-primary" id="resultsCount">
                                            <?php echo $attempts->num_rows; ?> Hasil
                                        </span>
                                    </div>

                                    <?php if ($attempts->num_rows > 0): ?>
                                        <div class="results-list" id="resultsList">
                                            <?php while($attempt = $attempts->fetch_assoc()): 
                                            $is_passed = $attempt['nilai'] >= $quiz['passing_grade'];
                                            $status_class = $is_passed ? 'passed' : 'failed';
                                            $status_badge = $is_passed ? 'bg-success' : 'bg-danger';
                                            $status_text = $is_passed ? 'Lulus' : 'Tidak Lulus';
                                            
                                            // Handle null values for waktu_selesai
                                            $end_time_display = $attempt['waktu_selesai'] ? 
                                                date('d M Y H:i', strtotime($attempt['waktu_selesai'])) : 'Belum selesai';
                                            $duration_display = $attempt['waktu_selesai'] ? 
                                                $attempt['waktu_pengerjaan'] . ' menit' : 'Masih dikerjakan';
                                        ?>
                                            <div class="attempt-card <?php echo $status_class; ?>" data-status="<?php echo $is_passed ? 'passed' : 'failed'; ?>" data-student="<?php echo htmlspecialchars(strtolower($attempt['nama_siswa'])); ?>">
                                                <div class="row align-items-center">
                                                    <div class="col-md-1 text-center">
                                                        <?php if (!empty($attempt['foto_profil'])): ?>
                                                            <img src="../<?php echo $attempt['foto_profil']; ?>" 
                                                                alt="<?php echo htmlspecialchars($attempt['nama_siswa']); ?>" 
                                                                class="student-avatar">
                                                        <?php else: ?>
                                                            <div class="avatar-placeholder mx-auto">
                                                                <?php echo strtoupper(substr($attempt['nama_siswa'], 0, 1)); ?>
                                                            </div>
                                                        <?php endif; ?>
                                                    </div>
                                                    <div class="col-md-4">
                                                        <h6 class="fw-bold mb-1"><?php echo htmlspecialchars($attempt['nama_siswa']); ?></h6>
                                                        <small class="text-muted"><?php echo $attempt['email_siswa']; ?></small>
                                                    </div>
                                                    <div class="col-md-2 text-center">
                                                        <span class="badge <?php echo $status_badge; ?> score-badge">
                                                            <?php echo $attempt['nilai']; ?>
                                                        </span>
                                                        <div class="small text-muted mt-1"><?php echo $status_text; ?></div>
                                                    </div>
                                                    <div class="col-md-3">
                                                        <div class="small text-muted">
                                                            <div class="mb-1">
                                                                <i class="bi bi-clock me-1"></i>
                                                                <?php echo date('d M Y H:i', strtotime($attempt['waktu_mulai'])); ?>
                                                            </div>
                                                            <div>
                                                                <i class="bi bi-stopwatch me-1"></i>
                                                                <?php echo $duration_display; ?>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-2 text-end">
                                                        <button class="btn btn-sm btn-outline-primary" 
                                                                data-bs-toggle="modal" 
                                                                data-bs-target="#attemptDetailModal"
                                                                data-student-name="<?php echo htmlspecialchars($attempt['nama_siswa']); ?>"
                                                                data-score="<?php echo $attempt['nilai']; ?>"
                                                                data-status="<?php echo $status_text; ?>"
                                                                data-start-time="<?php echo date('d M Y H:i', strtotime($attempt['waktu_mulai'])); ?>"
                                                                data-end-time="<?php echo $end_time_display; ?>"
                                                                data-duration="<?php echo $duration_display; ?>">
                                                            <i class="bi bi-eye"></i>
                                                        </button>
                                                        <button class="btn btn-sm btn-outline-warning">
                                                            <i class="bi bi-envelope"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endwhile; ?>
                                        </div>
                                    <?php else: ?>
                                        <div class="text-center py-5">
                                            <i class="bi bi-clipboard-x display-1 text-muted"></i>
                                            <h4 class="text-muted mt-3">Belum ada hasil</h4>
                                            <p class="text-muted mb-4">Siswa belum mengerjakan kuis ini</p>
                                            <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>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Sidebar Charts -->
                            <div class="col-lg-4">
                                <!-- Score Distribution Chart -->
                                <div class="chart-container">
                                    <h5 class="fw-bold mb-4">
                                        <i class="bi bi-bar-chart me-2"></i>Distribusi Nilai
                                    </h5>
                                    <canvas id="scoreDistributionChart" width="400" height="300"></canvas>
                                </div>

                                <!-- Pass Rate Chart -->
                                <div class="chart-container">
                                    <h5 class="fw-bold mb-4">
                                        <i class="bi bi-pie-chart me-2"></i>Tingkat Kelulusan
                                    </h5>
                                    <canvas id="passRateChart" width="400" height="300"></canvas>
                                </div>

                                <!-- Performance Summary -->
                                <div class="stats-card">
                                    <h5 class="fw-bold mb-4">
                                        <i class="bi bi-graph-up me-2"></i>Ringkasan Performa
                                    </h5>
                                    
                                    <div class="mb-3">
                                        <div class="d-flex justify-content-between mb-2">
                                            <small class="text-muted">Rata-rata Nilai</small>
                                            <small class="fw-semibold"><?php echo number_format($stats['avg_score'] ?? 0, 1); ?>/100</small>
                                        </div>
                                        <div class="progress progress-quiz">
                                            <div class="progress-bar 
                                                <?php echo ($stats['avg_score'] ?? 0) >= 80 ? 'bg-success' : 
                                                      (($stats['avg_score'] ?? 0) >= 60 ? 'bg-warning' : 'bg-danger'); ?>" 
                                                 style="width: <?php echo $stats['avg_score'] ?? 0; ?>%">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <div class="d-flex justify-content-between mb-2">
                                            <small class="text-muted">Tingkat Kelulusan</small>
                                            <small class="fw-semibold"><?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="mb-3">
                                        <div class="d-flex justify-content-between mb-2">
                                            <small class="text-muted">Efisiensi Waktu</small>
                                            <small class="fw-semibold"><?php echo number_format($stats['avg_time'] ?? 0, 1); ?>m</small>
                                        </div>
                                        <div class="progress progress-quiz">
                                            <div class="progress-bar 
                                                <?php echo ($stats['avg_time'] ?? 0) <= ($quiz['waktu_menit'] * 0.7) ? 'bg-success' : 
                                                      (($stats['avg_time'] ?? 0) <= ($quiz['waktu_menit'] * 0.9) ? 'bg-warning' : 'bg-danger'); ?>" 
                                                 style="width: <?php echo (($stats['avg_time'] ?? 0) / $quiz['waktu_menit']) * 100; ?>%">
                                            </div>
                                        </div>
                                        <small class="text-muted">Dari <?php echo $quiz['waktu_menit']; ?> menit tersedia</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

   <!-- Attempt Detail Modal -->
    <div class="modal fade" id="attemptDetailModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Detail Attempt</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div id="attemptDetailContent">
                        <!-- Content will be loaded via JavaScript -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
                    <button type="button" class="btn btn-primary">
                        <i class="bi bi-envelope me-2"></i>Kirim Feedback
                    </button>
                </div>
            </div>
        </div>
    </div>
    <script>
    // Attempt detail modal
    const attemptDetailModal = document.getElementById('attemptDetailModal');
    if (attemptDetailModal) {
        attemptDetailModal.addEventListener('show.bs.modal', function(event) {
            const button = event.relatedTarget;
            const studentName = button.getAttribute('data-student-name');
            const score = button.getAttribute('data-score');
            const status = button.getAttribute('data-status');
            const startTime = button.getAttribute('data-start-time');
            const endTime = button.getAttribute('data-end-time');
            const duration = button.getAttribute('data-duration');
            
            const modalContent = document.getElementById('attemptDetailContent');
            modalContent.innerHTML = `
                <div class="row">
                    <div class="col-md-6">
                        <h6 class="fw-bold">Informasi Siswa</h6>
                        <div class="mb-3">
                            <strong>Nama:</strong> ${studentName}
                        </div>
                    </div>
                    <div class="col-md-6">
                        <h6 class="fw-bold">Hasil Kuis</h6>
                        <div class="mb-2">
                            <strong>Nilai:</strong> 
                            <span class="badge ${score >= <?php echo $quiz['passing_grade']; ?> ? 'bg-success' : 'bg-danger'}">
                                ${score}
                            </span>
                        </div>
                        <div class="mb-2">
                            <strong>Status:</strong> ${status}
                        </div>
                    </div>
                </div>
                
                <div class="row mt-3">
                    <div class="col-md-6">
                        <h6 class="fw-bold">Waktu Pengerjaan</h6>
                        <div class="mb-2">
                            <strong>Mulai:</strong> ${startTime}
                        </div>
                        <div class="mb-2">
                            <strong>Selesai:</strong> ${endTime || 'Belum selesai'}
                        </div>
                        <div class="mb-2">
                            <strong>Durasi:</strong> ${duration || '0'} menit
                        </div>
                    </div>
                    <div class="col-md-6">
                        <h6 class="fw-bold">Analisis</h6>
                        <div class="mb-2">
                            <strong>Target Nilai:</strong> <?php echo $quiz['passing_grade']; ?>
                        </div>
                        <div class="mb-2">
                            <strong>Selisih:</strong> ${score - <?php echo $quiz['passing_grade']; ?>} poin
                        </div>
                        <div class="mb-2">
                            <strong>Status Pengerjaan:</strong> 
                            ${endTime ? 
                                (duration <= <?php echo $quiz['waktu_menit'] * 0.7; ?> ? 'Sangat Baik' : 
                                 duration <= <?php echo $quiz['waktu_menit'] * 0.9; ?> ? 'Baik' : 'Perlu Improvement') : 
                                'Masih dalam pengerjaan'}
                        </div>
                    </div>
                </div>
                
                <div class="mt-4">
                    <h6 class="fw-bold">Rekomendasi</h6>
                    <div class="alert ${score >= <?php echo $quiz['passing_grade']; ?> ? 'alert-success' : 'alert-warning'}">
                        ${score >= <?php echo $quiz['passing_grade']; ?> ? 
                            'Siswa telah mencapai target pembelajaran. Pertahankan performa!' :
                            'Siswa perlu meningkatkan pemahaman pada materi terkait. Disarankan untuk mengulang pembelajaran.'}
                    </div>
                </div>
            `;
        });
    }
</script>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Filter functionality
            const filterButtons = document.querySelectorAll('[data-filter]');
            const attemptCards = document.querySelectorAll('.attempt-card');
            const resultsCount = document.getElementById('resultsCount');
            
            filterButtons.forEach(button => {
                button.addEventListener('click', function() {
                    const filter = this.getAttribute('data-filter');
                    
                    // Update active button
                    filterButtons.forEach(btn => btn.classList.remove('active'));
                    this.classList.add('active');
                    
                    // Filter cards
                    let visibleCount = 0;
                    attemptCards.forEach(card => {
                        if (filter === 'all' || card.getAttribute('data-status') === filter) {
                            card.style.display = 'block';
                            visibleCount++;
                        } else {
                            card.style.display = 'none';
                        }
                    });
                    
                    // Update results count
                    resultsCount.textContent = visibleCount + ' Hasil';
                });
            });
            
            // Search functionality
            const searchInput = document.getElementById('searchStudent');
            searchInput.addEventListener('input', function() {
                const searchTerm = this.value.toLowerCase();
                
                let visibleCount = 0;
                attemptCards.forEach(card => {
                    const studentName = card.getAttribute('data-student');
                    if (studentName.includes(searchTerm)) {
                        card.style.display = 'block';
                        visibleCount++;
                    } else {
                        card.style.display = 'none';
                    }
                });
                
                resultsCount.textContent = visibleCount + ' Hasil';
            });
            
            // Attempt detail modal
            const attemptDetailModal = document.getElementById('attemptDetailModal');
            if (attemptDetailModal) {
                attemptDetailModal.addEventListener('show.bs.modal', function(event) {
                    const button = event.relatedTarget;
                    const studentName = button.getAttribute('data-student-name');
                    const score = button.getAttribute('data-score');
                    const status = button.getAttribute('data-status');
                    const startTime = button.getAttribute('data-start-time');
                    const endTime = button.getAttribute('data-end-time');
                    const duration = button.getAttribute('data-duration');
                    
                    const modalContent = document.getElementById('attemptDetailContent');
                    modalContent.innerHTML = `
                        <div class="row">
                            <div class="col-md-6">
                                <h6 class="fw-bold">Informasi Siswa</h6>
                                <div class="mb-3">
                                    <strong>Nama:</strong> ${studentName}
                                </div>
                            </div>
                            <div class="col-md-6">
                                <h6 class="fw-bold">Hasil Kuis</h6>
                                <div class="mb-2">
                                    <strong>Nilai:</strong> 
                                    <span class="badge ${score >= <?php echo $quiz['passing_grade']; ?> ? 'bg-success' : 'bg-danger'}">
                                        ${score}
                                    </span>
                                </div>
                                <div class="mb-2">
                                    <strong>Status:</strong> ${status}
                                </div>
                            </div>
                        </div>
                        
                        <div class="row mt-3">
                            <div class="col-md-6">
                                <h6 class="fw-bold">Waktu Pengerjaan</h6>
                                <div class="mb-2">
                                    <strong>Mulai:</strong> ${startTime}
                                </div>
                                <div class="mb-2">
                                    <strong>Selesai:</strong> ${endTime}
                                </div>
                                <div class="mb-2">
                                    <strong>Durasi:</strong> ${duration} menit
                                </div>
                            </div>
                            <div class="col-md-6">
                                <h6 class="fw-bold">Analisis</h6>
                                <div class="mb-2">
                                    <strong>Target Nilai:</strong> <?php echo $quiz['passing_grade']; ?>
                                </div>
                                <div class="mb-2">
                                    <strong>Selisih:</strong> ${score - <?php echo $quiz['passing_grade']; ?>} poin
                                </div>
                                <div class="mb-2">
                                    <strong>Efisiensi Waktu:</strong> 
                                    ${duration <= <?php echo $quiz['waktu_menit'] * 0.7; ?> ? 'Sangat Baik' : 
                                      duration <= <?php echo $quiz['waktu_menit'] * 0.9; ?> ? 'Baik' : 'Perlu Improvement'}
                                </div>
                            </div>
                        </div>
                        
                        <div class="mt-4">
                            <h6 class="fw-bold">Rekomendasi</h6>
                            <div class="alert ${score >= <?php echo $quiz['passing_grade']; ?> ? 'alert-success' : 'alert-warning'}">
                                ${score >= <?php echo $quiz['passing_grade']; ?> ? 
                                    'Siswa telah mencapai target pembelajaran. Pertahankan performa!' :
                                    'Siswa perlu meningkatkan pemahaman pada materi terkait. Disarankan untuk mengulang pembelajaran.'}
                            </div>
                        </div>
                    `;
                });
            }
            
            // Charts
            // Score Distribution Chart
            const scoreDistributionCtx = document.getElementById('scoreDistributionChart').getContext('2d');
            const scoreDistributionChart = new Chart(scoreDistributionCtx, {
                type: 'bar',
                data: {
                    labels: [<?php
                        $distribution_ranges = [];
                        $distribution_counts = [];
                        while($range = $distribution->fetch_assoc()) {
                            $distribution_ranges[] = "'" . $range['score_range'] . "'";
                            $distribution_counts[] = $range['count'];
                        }
                        echo implode(', ', $distribution_ranges);
                    ?>],
                    datasets: [{
                        label: 'Jumlah Siswa',
                        data: [<?php echo implode(', ', $distribution_counts); ?>],
                        backgroundColor: [
                            '#28a745',
                            '#20c997',
                            '#ffc107',
                            '#fd7e14',
                            '#dc3545',
                            '#6c757d'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: {
                            display: false
                        },
                        title: {
                            display: true,
                            text: 'Distribusi Nilai Siswa'
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: 'Jumlah Siswa'
                            }
                        },
                        x: {
                            title: {
                                display: true,
                                text: 'Rentang Nilai'
                            }
                        }
                    }
                }
            });
            
            // Pass Rate Chart
            const passRateCtx = document.getElementById('passRateChart').getContext('2d');
            const passRateChart = new Chart(passRateCtx, {
                type: 'doughnut',
                data: {
                    labels: ['Lulus', 'Tidak Lulus'],
                    datasets: [{
                        data: [
                            <?php echo $stats['passed_attempts'] ?? 0; ?>,
                            <?php echo ($stats['total_attempts'] ?? 0) - ($stats['passed_attempts'] ?? 0); ?>
                        ],
                        backgroundColor: [
                            '#28a745',
                            '#dc3545'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        },
                        title: {
                            display: true,
                            text: 'Persentase Kelulusan'
                        }
                    }
                }
            });
        });
    </script>
</body>
</html>
<?php
// Tutup koneksi database
if (isset($stmt_quiz)) $stmt_quiz->close();
if (isset($stmt_attempts)) $stmt_attempts->close();
if (isset($stmt_stats)) $stmt_stats->close();
if (isset($stmt_distribution)) $stmt_distribution->close();
$conn->close();
?>