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

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

$user_id = $_SESSION['user_id'];

// Handle filter
$filter = isset($_GET['filter']) ? sanitize($_GET['filter']) : 'all';
$type_filter = isset($_GET['type']) ? sanitize($_GET['type']) : 'all';
$search = isset($_GET['search']) ? sanitize($_GET['search']) : '';

// Build query untuk lms_quizzes - PERBAIKAN: join dengan tabel lms_users untuk nama guru
$sql_lms_quizzes = "SELECT q.*, l.judul_lesson, l.id_course, c.judul as course_title, 
                       u.nama_lengkap as nama_guru, qa.nilai, qa.status as attempt_status,
                       qa.waktu_selesai, qa.id as attempt_id,
                       (SELECT COUNT(*) FROM lms_questions WHERE id_quiz = q.id) as total_lms_questions
                FROM lms_quizzes q 
                JOIN lms_lessons l ON q.id_lesson = l.id 
                JOIN lms_courses c ON l.id_course = c.id 
                JOIN lms_users u ON c.id_guru = u.id  -- PERBAIKAN: join dengan lms_users untuk nama guru
                LEFT JOIN lms_quiz_attempts qa ON q.id = qa.id_quiz AND qa.id_siswa = ?
                WHERE l.id_course IN (
                    SELECT id_course FROM lms_enrollments 
                    WHERE id_siswa = ? AND status = 'active'
                )";

$params = [$user_id, $user_id];
$types = "ii";

// Apply filters
if ($filter === 'completed') {
    $sql_lms_quizzes .= " AND qa.status = 'completed'";
} elseif ($filter === 'in_progress') {
    $sql_lms_quizzes .= " AND qa.status = 'in_progress'";
} elseif ($filter === 'not_started') {
    $sql_lms_quizzes .= " AND qa.id IS NULL";
}

if ($type_filter === 'quiz') {
    $sql_lms_quizzes .= " AND q.judul_quiz LIKE '%Quiz%'";
} elseif ($type_filter === 'exam') {
    $sql_lms_quizzes .= " AND q.judul_quiz LIKE '%Ujian%'";
}

// Apply search
if (!empty($search)) {
    $sql_lms_quizzes .= " AND (q.judul_quiz LIKE ? OR c.judul LIKE ? OR l.judul_lesson LIKE ?)";
    $search_param = "%$search%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $types .= "sss";
}

$sql_lms_quizzes .= " ORDER BY 
                CASE 
                    WHEN qa.status = 'in_progress' THEN 1
                    WHEN qa.id IS NULL THEN 2
                    ELSE 3 
                END,
                q.created_at DESC";

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

// Hitung statistik - PERBAIKAN: join dengan lms_users
$sql_stats = "SELECT 
    COUNT(*) as total_lms_quizzes,
    SUM(CASE WHEN qa.status = 'completed' THEN 1 ELSE 0 END) as completed,
    SUM(CASE WHEN qa.status = 'in_progress' THEN 1 ELSE 0 END) as in_progress,
    SUM(CASE WHEN qa.id IS NULL THEN 1 ELSE 0 END) as not_started,
    AVG(CASE WHEN qa.status = 'completed' THEN qa.nilai ELSE NULL END) as avg_score
    FROM lms_quizzes q 
    JOIN lms_lessons l ON q.id_lesson = l.id 
    JOIN lms_courses c ON l.id_course = c.id 
    JOIN lms_users u ON c.id_guru = u.id  -- PERBAIKAN: join dengan lms_users
    LEFT JOIN lms_quiz_attempts qa ON q.id = qa.id_quiz AND qa.id_siswa = ?
    WHERE l.id_course IN (
        SELECT id_course FROM lms_enrollments 
        WHERE id_siswa = ? AND status = 'active'
    )";
$stmt_stats = $conn->prepare($sql_stats);
$stmt_stats->bind_param('ii', $user_id, $user_id);
$stmt_stats->execute();
$stats = $stmt_stats->get_result()->fetch_assoc();

// Ambil quiz attempts terbaru - PERBAIKAN: join dengan lms_users
$sql_recent_attempts = "SELECT qa.*, q.judul_quiz, l.judul_lesson, c.judul as course_title,
                               c.id as course_id, u.nama_lengkap as nama_guru
                        FROM lms_quiz_attempts qa 
                        JOIN lms_quizzes q ON qa.id_quiz = q.id 
                        JOIN lms_lessons l ON q.id_lesson = l.id 
                        JOIN lms_courses c ON l.id_course = c.id 
                        JOIN lms_users u ON c.id_guru = u.id  -- PERBAIKAN: join dengan lms_users
                        WHERE qa.id_siswa = ? 
                        ORDER BY qa.waktu_mulai DESC 
                        LIMIT 5";
$stmt_recent = $conn->prepare($sql_recent_attempts);
$stmt_recent->bind_param('i', $user_id);
$stmt_recent->execute();
$result_recent = $stmt_recent->get_result();

// Handle start quiz
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['start_quiz'])) {
    $quiz_id = sanitize($_POST['quiz_id']);
    
    // Cek apakah sudah ada attempt yang sedang berjalan
    $sql_check = "SELECT * FROM lms_quiz_attempts 
                  WHERE id_quiz = ? AND id_siswa = ? AND status = 'in_progress'";
    $stmt_check = $conn->prepare($sql_check);
    $stmt_check->bind_param('ii', $quiz_id, $user_id);
    $stmt_check->execute();
    $result_check = $stmt_check->get_result();
    
    if ($result_check->num_rows > 0) {
        // Lanjutkan attempt yang ada
        $attempt = $result_check->fetch_assoc();
        $_SESSION['info'] = "Meneruskan attempt sebelumnya...";
        redirect("take_quiz.php?attempt_id=" . $attempt['id']);
    } else {
        // Buat attempt baru
        $sql_insert = "INSERT INTO lms_quiz_attempts (id_quiz, id_siswa) VALUES (?, ?)";
        $stmt_insert = $conn->prepare($sql_insert);
        $stmt_insert->bind_param('ii', $quiz_id, $user_id);
        
        if ($stmt_insert->execute()) {
            $attempt_id = $conn->insert_id;
            $_SESSION['success'] = "Quiz dimulai!";
            redirect("take_quiz.php?attempt_id=" . $attempt_id);
        } else {
            $_SESSION['error'] = "Gagal memulai quiz!";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kuis & Ujian - 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);
        }
        
        .stat-card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            transition: transform 0.3s;
        }
        
        .stat-card:hover {
            transform: translateY(-5px);
        }
        
        .quiz-card {
            border: none;
            border-radius: 10px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            transition: transform 0.3s;
            margin-bottom: 20px;
        }
        
        .quiz-card:hover {
            transform: translateY(-3px);
        }
        
        .filter-btn {
            border: 1px solid #dee2e6;
            border-radius: 20px;
            padding: 8px 16px;
            margin: 0 5px 10px 0;
            transition: all 0.3s;
        }
        
        .filter-btn.active {
            background: var(--primary-color);
            color: white;
            border-color: var(--primary-color);
        }
        
        .score-badge {
            font-size: 0.8rem;
            padding: 6px 12px;
        }
        
        .status-badge {
            font-size: 0.7rem;
            padding: 4px 8px;
        }
        
        .timer-warning {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 5px;
            padding: 10px;
            margin: 10px 0;
        }
        
        .progress-thin {
            height: 4px;
        }
        
        .quiz-type-badge {
            font-size: 0.6rem;
            padding: 3px 6px;
        }
    </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">Siswa 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="progress.php">
                                <i class="bi bi-graph-up"></i> Progress Belajar
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="quizzes.php">
                                <i class="bi bi-pencil-square"></i> Kuis & Ujian
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="certificates.php">
                                <i class="bi bi-award"></i> Sertifikat
                            </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">Kuis & Ujian</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="../courses.php">
                                        <i class="bi bi-search me-2"></i>Jelajah Kursus
                                    </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">
                    <!-- 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">Kuis & Ujian</h4>
                                    <p class="text-muted mb-0">Kelola dan kerjakan kuis serta ujian Anda</p>
                                </div>
                                <div class="dropdown">
                                    <button class="btn btn-outline-primary dropdown-toggle" type="button" 
                                            data-bs-toggle="dropdown">
                                        <i class="bi bi-download me-2"></i>Export
                                    </button>
                                    <ul class="dropdown-menu">
                                        <li><a class="dropdown-item" href="#"><i class="bi bi-file-pdf me-2"></i>Laporan PDF</a></li>
                                        <li><a class="dropdown-item" href="#"><i class="bi bi-file-excel me-2"></i>Data Excel</a></li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="card stat-card border-0 text-white bg-primary">
                                <div class="card-body">
                                    <div class="row align-items-center">
                                        <div class="col-8">
                                            <h6 class="card-title mb-2">Total Kuis</h6>
                                            <h2 class="fw-bold"><?php echo $stats['total_lms_quizzes']; ?></h2>
                                            <small>Kuis tersedia</small>
                                        </div>
                                        <div class="col-4 text-end">
                                            <i class="bi bi-pencil-square" style="font-size: 2.5rem;"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="card stat-card border-0 text-white bg-success">
                                <div class="card-body">
                                    <div class="row align-items-center">
                                        <div class="col-8">
                                            <h6 class="card-title mb-2">Selesai</h6>
                                            <h2 class="fw-bold"><?php echo $stats['completed']; ?></h2>
                                            <small>Kuis dikerjakan</small>
                                        </div>
                                        <div class="col-4 text-end">
                                            <i class="bi bi-check-circle" style="font-size: 2.5rem;"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="card stat-card border-0 text-white bg-warning">
                                <div class="card-body">
                                    <div class="row align-items-center">
                                        <div class="col-8">
                                            <h6 class="card-title mb-2">Dalam Proses</h6>
                                            <h2 class="fw-bold"><?php echo $stats['in_progress']; ?></h2>
                                            <small>Sedang dikerjakan</small>
                                        </div>
                                        <div class="col-4 text-end">
                                            <i class="bi bi-clock" style="font-size: 2.5rem;"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="card stat-card border-0 text-white bg-info">
                                <div class="card-body">
                                    <div class="row align-items-center">
                                        <div class="col-8">
                                            <h6 class="card-title mb-2">Rata-rata Nilai</h6>
                                            <h2 class="fw-bold"><?php echo number_format($stats['avg_score'] ?? 0, 1); ?></h2>
                                            <small>Skor rata-rata</small>
                                        </div>
                                        <div class="col-4 text-end">
                                            <i class="bi bi-graph-up" style="font-size: 2.5rem;"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filter dan Search -->
                    <div class="card border-0 shadow-sm mb-4">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <h6 class="mb-3">Filter Status:</h6>
                                    <div class="d-flex flex-wrap">
                                        <a href="?filter=all&type=<?php echo $type_filter; ?><?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?>" 
                                           class="filter-btn <?php echo $filter === 'all' ? 'active' : ''; ?>">
                                            Semua (<?php echo $stats['total_lms_quizzes']; ?>)
                                        </a>
                                        <a href="?filter=not_started&type=<?php echo $type_filter; ?><?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?>" 
                                           class="filter-btn <?php echo $filter === 'not_started' ? 'active' : ''; ?>">
                                            Belum Mulai (<?php echo $stats['not_started']; ?>)
                                        </a>
                                        <a href="?filter=in_progress&type=<?php echo $type_filter; ?><?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?>" 
                                           class="filter-btn <?php echo $filter === 'in_progress' ? 'active' : ''; ?>">
                                            Dalam Proses (<?php echo $stats['in_progress']; ?>)
                                        </a>
                                        <a href="?filter=completed&type=<?php echo $type_filter; ?><?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?>" 
                                           class="filter-btn <?php echo $filter === 'completed' ? 'active' : ''; ?>">
                                            Selesai (<?php echo $stats['completed']; ?>)
                                        </a>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <h6 class="mb-3">Tipe:</h6>
                                    <select name="type" class="form-select" onchange="window.location.href='?filter=<?php echo $filter; ?>&type='+this.value+'<?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?>'">
                                        <option value="all" <?php echo $type_filter === 'all' ? 'selected' : ''; ?>>Semua Tipe</option>
                                        <option value="quiz" <?php echo $type_filter === 'quiz' ? 'selected' : ''; ?>>Kuis</option>
                                        <option value="exam" <?php echo $type_filter === 'exam' ? 'selected' : ''; ?>>Ujian</option>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <h6 class="mb-3">Cari:</h6>
                                    <form method="GET" class="d-flex">
                                        <input type="text" name="search" class="form-control me-2" 
                                               placeholder="Cari kuis..." 
                                               value="<?php echo htmlspecialchars($search); ?>">
                                        <button type="submit" class="btn btn-primary">
                                            <i class="bi bi-search"></i>
                                        </button>
                                        <?php if (!empty($filter) && $filter !== 'all'): ?>
                                            <input type="hidden" name="filter" value="<?php echo $filter; ?>">
                                        <?php endif; ?>
                                        <?php if (!empty($type_filter) && $type_filter !== 'all'): ?>
                                            <input type="hidden" name="type" value="<?php echo $type_filter; ?>">
                                        <?php endif; ?>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Daftar Kuis -->
                        <div class="col-lg-8 mb-4">
                            <div class="card border-0 shadow-sm">
                                <div class="card-header bg-white border-0">
                                    <h6 class="mb-0">
                                        <i class="bi bi-list-task me-2"></i>
                                        Daftar Kuis & Ujian
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <?php if ($result_lms_quizzes->num_rows > 0): ?>
                                        <?php while($quiz = $result_lms_quizzes->fetch_assoc()): 
                                            $is_completed = $quiz['attempt_status'] === 'completed';
                                            $is_in_progress = $quiz['attempt_status'] === 'in_progress';
                                            $is_passed = $is_completed && $quiz['nilai'] >= $quiz['passing_grade'];
                                            $time_remaining = null;
                                            
                                            if ($is_in_progress && $quiz['waktu_menit'] > 0 && !empty($quiz['waktu_mulai'])) {
                                                $start_time = strtotime($quiz['waktu_mulai']);
                                                $end_time = $start_time + ($quiz['waktu_menit'] * 60);
                                                $current_time = time();
                                                $time_remaining = $end_time - $current_time;
                                            } else {
                                                $time_remaining = null;
                                            }
                                        ?>
                                            <div class="quiz-card card">
                                                <div class="card-body">
                                                    <div class="row align-items-center">
                                                        <div class="col-md-8">
                                                            <div class="d-flex align-items-start mb-2">
                                                                <div class="flex-shrink-0">
                                                                    <?php if (strpos($quiz['judul_quiz'], 'Ujian') !== false): ?>
                                                                        <i class="bi bi-clipboard-check text-danger me-3" style="font-size: 1.5rem;"></i>
                                                                    <?php else: ?>
                                                                        <i class="bi bi-pencil-square text-primary me-3" style="font-size: 1.5rem;"></i>
                                                                    <?php endif; ?>
                                                                </div>
                                                                <div class="flex-grow-1">
                                                                    <h6 class="card-title mb-1"><?php echo $quiz['judul_quiz']; ?></h6>
                                                                    <p class="card-text small text-muted mb-1">
                                                                        <i class="bi bi-journal-text"></i> <?php echo $quiz['judul_lesson']; ?>
                                                                    </p>
                                                                    <p class="card-text small text-muted mb-2">
                                                                        <i class="bi bi-book"></i> <?php echo $quiz['course_title']; ?> - Oleh: <?php echo $quiz['nama_guru']; ?>
                                                                    </p>
                                                                    <div class="d-flex flex-wrap gap-2">
                                                                        <span class="quiz-type-badge badge 
                                                                            <?php echo strpos($quiz['judul_quiz'], 'Ujian') !== false ? 'bg-danger' : 'bg-primary'; ?>">
                                                                            <?php echo strpos($quiz['judul_quiz'], 'Ujian') !== false ? 'Ujian' : 'Kuis'; ?>
                                                                        </span>
                                                                        <span class="quiz-type-badge badge bg-secondary">
                                                                            <?php echo $quiz['total_lms_questions']; ?> Soal
                                                                        </span>
                                                                        <?php if ($quiz['waktu_menit'] > 0): ?>
                                                                            <span class="quiz-type-badge badge bg-warning text-dark">
                                                                                <i class="bi bi-clock"></i> <?php echo $quiz['waktu_menit']; ?> menit
                                                                            </span>
                                                                        <?php endif; ?>
                                                                        <span class="quiz-type-badge badge bg-info">
                                                                            Lulus: <?php echo $quiz['passing_grade']; ?>%
                                                                        </span>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div class="col-md-4 text-end">
                                                            <?php if ($is_completed): ?>
                                                                <div class="mb-2">
                                                                    <span class="score-badge badge 
                                                                        <?php echo $is_passed ? 'bg-success' : 'bg-danger'; ?>">
                                                                        Nilai: <?php echo $quiz['nilai']; ?>%
                                                                    </span>
                                                                </div>
                                                                <div class="mb-2">
                                                                    <span class="status-badge badge 
                                                                        <?php echo $is_passed ? 'bg-success' : 'bg-danger'; ?>">
                                                                        <?php echo $is_passed ? 'LULUS' : 'TIDAK LULUS'; ?>
                                                                    </span>
                                                                </div>
                                                                <a href="quiz_result.php?attempt_id=<?php echo $quiz['attempt_id']; ?>" 
                                                                   class="btn btn-outline-primary btn-sm">
                                                                    <i class="bi bi-eye me-1"></i>Lihat Hasil
                                                                </a>
                                                            <?php elseif ($is_in_progress): ?>
                                                                <?php if ($time_remaining && $time_remaining > 0): ?>
                                                                    <div class="timer-warning mb-2">
                                                                        <small class="text-warning">
                                                                            <i class="bi bi-exclamation-triangle me-1"></i>
                                                                            Waktu tersisa: 
                                                                            <span id="timer-<?php echo $quiz['id']; ?>">
                                                                                <?php echo gmdate("H:i:s", $time_remaining); ?>
                                                                            </span>
                                                                        </small>
                                                                    </div>
                                                                <?php endif; ?>
                                                                <form method="POST" class="d-inline">
                                                                    <input type="hidden" name="quiz_id" value="<?php echo $quiz['id']; ?>">
                                                                    <button type="submit" name="start_quiz" 
                                                                            class="btn btn-warning btn-sm">
                                                                        <i class="bi bi-play-circle me-1"></i>Lanjutkan
                                                                    </button>
                                                                </form>
                                                            <?php else: ?>
                                                                <form method="POST" class="d-inline">
                                                                    <input type="hidden" name="quiz_id" value="<?php echo $quiz['id']; ?>">
                                                                    <button type="submit" name="start_quiz" 
                                                                            class="btn btn-primary btn-sm">
                                                                        <i class="bi bi-play-circle me-1"></i>Mulai
                                                                    </button>
                                                                </form>
                                                            <?php endif; ?>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <div class="text-center py-5">
                                            <i class="bi bi-pencil-square text-muted" style="font-size: 3rem;"></i>
                                            <h5 class="text-muted mt-3">Tidak ada kuis yang ditemukan</h5>
                                            <p class="text-muted">
                                                <?php if (!empty($search) || $filter !== 'all' || $type_filter !== 'all'): ?>
                                                    Coba ubah filter pencarian Anda
                                                <?php else: ?>
                                                    Belum ada kuis yang tersedia untuk kursus yang Anda ikuti
                                                <?php endif; ?>
                                            </p>
                                            <a href="my_courses.php" class="btn btn-primary">
                                                <i class="bi bi-journal-bookmark me-2"></i>Lihat Kursus Saya
                                            </a>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>

                        <!-- Sidebar -->
                        <div class="col-lg-4 mb-4">
                            <!-- Attempts Terbaru -->
                            <div class="card border-0 shadow-sm mb-4">
                                <div class="card-header bg-white border-0">
                                    <h6 class="mb-0">
                                        <i class="bi bi-clock-history me-2"></i>
                                        Attempt Terbaru
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <?php if ($result_recent->num_rows > 0): ?>
                                        <div class="list-group list-group-flush">
                                            <?php while($attempt = $result_recent->fetch_assoc()): ?>
                                                <div class="list-group-item px-0 border-0">
                                                    <div class="d-flex align-items-start">
                                                        <div class="flex-shrink-0">
                                                            <div class="bg-<?php echo $attempt['nilai'] >= 60 ? 'success' : 'danger'; ?> rounded-circle p-2">
                                                                <i class="bi bi-<?php echo $attempt['nilai'] >= 60 ? 'check' : 'x'; ?> text-white"></i>
                                                            </div>
                                                        </div>
                                                        <div class="flex-grow-1 ms-3">
                                                            <h6 class="mb-0 small"><?php echo $attempt['judul_quiz']; ?></h6>
                                                            <small class="text-muted">
                                                                <?php echo $attempt['course_title']; ?>
                                                            </small>
                                                            <div class="mt-1">
                                                                <span class="badge bg-<?php echo $attempt['nilai'] >= 60 ? 'success' : 'danger'; ?>">
                                                                    <?php echo $attempt['nilai']; ?>%
                                                                </span>
                                                               <small class="text-muted ms-2">
                                                                    <?php echo !empty($attempt['waktu_selesai']) ? date('d M H:i', strtotime($attempt['waktu_selesai'])) : 'Belum selesai'; ?>
                                                                </small>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            <?php endwhile; ?>
                                        </div>
                                    <?php else: ?>
                                        <div class="text-center py-3">
                                            <i class="bi bi-clock text-muted" style="font-size: 2rem;"></i>
                                            <p class="text-muted mt-2 small">Belum ada attempt terbaru</p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Tips Mengerjakan Kuis -->
                            <div class="card border-0 shadow-sm">
                                <div class="card-header bg-white border-0">
                                    <h6 class="mb-0">
                                        <i class="bi bi-lightbulb me-2"></i>
                                        Tips Mengerjakan
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <div class="alert alert-info alert-dismissible fade show mb-3" role="alert">
                                        <small>
                                            <strong>Baca soal dengan teliti!</strong> Pastikan Anda memahami pertanyaan sebelum menjawab.
                                        </small>
                                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                    </div>
                                    <div class="alert alert-warning alert-dismissible fade show mb-3" role="alert">
                                        <small>
                                            <strong>Kelola waktu!</strong> Perhatikan timer dan jangan terlalu lama di satu soal.
                                        </small>
                                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                    </div>
                                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                                        <small>
                                            <strong>Review jawaban!</strong> Manfaatkan waktu tersisa untuk memeriksa ulang jawaban.
                                        </small>
                                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Timer countdown untuk quiz yang sedang berjalan
        function updateTimers() {
            const timers = document.querySelectorAll('[id^="timer-"]');
            timers.forEach(timer => {
                const timeArray = timer.textContent.split(':');
                let hours = parseInt(timeArray[0]);
                let minutes = parseInt(timeArray[1]);
                let seconds = parseInt(timeArray[2]);
                
                // Kurangi 1 detik
                seconds--;
                
                if (seconds < 0) {
                    seconds = 59;
                    minutes--;
                    
                    if (minutes < 0) {
                        minutes = 59;
                        hours--;
                        
                        if (hours < 0) {
                            // Waktu habis
                            timer.textContent = "Waktu Habis!";
                            timer.className = "text-danger fw-bold";
                            return;
                        }
                    }
                }
                
                // Format ulang waktu
                timer.textContent = 
                    hours.toString().padStart(2, '0') + ':' +
                    minutes.toString().padStart(2, '0') + ':' +
                    seconds.toString().padStart(2, '0');
            });
        }
        
        // Update timer setiap detik
        setInterval(updateTimers, 1000);
        
        // Konfirmasi sebelum memulai quiz
        document.addEventListener('DOMContentLoaded', function() {
            const startButtons = document.querySelectorAll('button[name="start_quiz"]');
            startButtons.forEach(button => {
                button.addEventListener('click', function(e) {
                    const quizTitle = this.closest('.quiz-card').querySelector('.card-title').textContent;
                    if (!confirm(`Apakah Anda yakin ingin memulai quiz:\n"${quizTitle}"?`)) {
                        e.preventDefault();
                    }
                });
            });
        });
    </script>
</body>
</html>