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

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

$user_id = $_SESSION['user_id'];

// Cek parameter
if (!isset($_GET['attempt_id']) || empty($_GET['attempt_id'])) {
    $_SESSION['error'] = "Attempt quiz tidak valid!";
    redirect('quizzes.php');
}

$attempt_id = sanitize($_GET['attempt_id']);

// Ambil data attempt
$sql_attempt = "SELECT qa.*, q.judul_quiz, q.deskripsi, q.waktu_menit, q.passing_grade, 
                       q.acak_soal, q.batas_percobaan, q.jumlah_soal,
                       l.judul_lesson, l.id_course, c.judul as course_title,
                       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
                WHERE qa.id = ? AND qa.id_siswa = ?";
$stmt_attempt = $conn->prepare($sql_attempt);
$stmt_attempt->bind_param('ii', $attempt_id, $user_id);
$stmt_attempt->execute();
$result_attempt = $stmt_attempt->get_result();

if ($result_attempt->num_rows == 0) {
    $_SESSION['error'] = "Attempt quiz tidak ditemukan!";
    redirect('quizzes.php');
}

$attempt = $result_attempt->fetch_assoc();

// Cek status attempt
if ($attempt['status'] == 'completed') {
    $_SESSION['info'] = "Quiz sudah selesai dikerjakan!";
    redirect("quiz_result.php?attempt_id=" . $attempt_id);
}

// Hitung waktu sisa
$start_time = strtotime($attempt['waktu_mulai']);
$time_limit = $attempt['waktu_menit'] * 60; // Convert to seconds
$end_time = $start_time + $time_limit;
$current_time = time();
$time_remaining = $end_time - $current_time;

// Cek jika waktu habis
if ($time_remaining <= 0 && $attempt['waktu_menit'] > 0) {
    // Auto-submit quiz
    $sql_update = "UPDATE lms_quiz_attempts SET status = 'completed', waktu_selesai = NOW() WHERE id = ?";
    $stmt_update = $conn->prepare($sql_update);
    $stmt_update->bind_param('i', $attempt_id);
    $stmt_update->execute();
    
    $_SESSION['warning'] = "Waktu pengerjaan quiz telah habis!";
    redirect("quiz_result.php?attempt_id=" . $attempt_id);
}

// Ambil soal-soal quiz
$sql_lms_questions = "SELECT * FROM lms_questions 
                  WHERE id_quiz = ? 
                  ORDER BY " . ($attempt['acak_soal'] ? "RAND()" : "id");
$stmt_lms_questions = $conn->prepare($sql_lms_questions);
$stmt_lms_questions->bind_param('i', $attempt['id_quiz']);
$stmt_lms_questions->execute();
$result_lms_questions = $stmt_lms_questions->get_result();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit_quiz'])) {
    $quiz_id = $attempt['id_quiz'];
    $total_lms_questions = $result_lms_questions->num_rows;
    $correct_answers = 0;
    
    // Hitung nilai
    foreach ($_POST as $key => $value) {
        if (strpos($key, 'question_') === 0) {
            $question_id = str_replace('question_', '', $key);
            $user_answer = sanitize($value);
            
            // Ambil jawaban benar dari database
            $sql_answer = "SELECT jawaban_benar, poin FROM lms_questions WHERE id = ?";
            $stmt_answer = $conn->prepare($sql_answer);
            $stmt_answer->bind_param('i', $question_id);
            $stmt_answer->execute();
            $result_answer = $stmt_answer->get_result();
            
            if ($result_answer->num_rows > 0) {
                $question_data = $result_answer->fetch_assoc();
                if ($user_answer == $question_data['jawaban_benar']) {
                    $correct_answers += $question_data['poin'];
                }
            }
        }
    }
    
    // Hitung nilai dalam persentase
    $total_points = 0;
    $sql_total_points = "SELECT SUM(poin) as total FROM lms_questions WHERE id_quiz = ?";
    $stmt_total = $conn->prepare($sql_total_points);
    $stmt_total->bind_param('i', $quiz_id);
    $stmt_total->execute();
    $result_total = $stmt_total->get_result();
    if ($result_total->num_rows > 0) {
        $total_data = $result_total->fetch_assoc();
        $total_points = $total_data['total'];
    }
    
    $nilai = $total_points > 0 ? round(($correct_answers / $total_points) * 100, 2) : 0;
    
    // Update attempt
    $sql_complete = "UPDATE lms_quiz_attempts 
                     SET nilai = ?, status = 'completed', waktu_selesai = NOW() 
                     WHERE id = ?";
    $stmt_complete = $conn->prepare($sql_complete);
    $stmt_complete->bind_param('di', $nilai, $attempt_id);
    
    if ($stmt_complete->execute()) {
        $_SESSION['success'] = "Quiz berhasil diselesaikan!";
        redirect("quiz_result.php?attempt_id=" . $attempt_id);
    } else {
        $_SESSION['error'] = "Gagal menyimpan hasil quiz!";
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mengerjakan Quiz - <?php echo $attempt['judul_quiz']; ?></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;
        }
        
        .quiz-header {
            background: white;
            border-bottom: 1px solid #e9ecef;
            padding: 15px 0;
            position: sticky;
            top: 0;
            z-index: 1000;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .quiz-container {
            max-width: 900px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .question-card {
            border: 1px solid #e9ecef;
            border-radius: 10px;
            padding: 25px;
            margin-bottom: 25px;
            background: white;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }
        
        .question-number {
            background: var(--primary-color);
            color: white;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin-right: 15px;
        }
        
        .option-label {
            display: block;
            padding: 12px 15px;
            margin: 8px 0;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .option-label:hover {
            border-color: var(--primary-color);
            background: #f8f9ff;
        }
        
        .option-input:checked + .option-label {
            border-color: var(--primary-color);
            background: #e3f2fd;
            font-weight: bold;
        }
        
        .option-input {
            display: none;
        }
        
        .timer-container {
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            padding: 15px;
            border-radius: 10px;
            text-align: center;
            margin-bottom: 20px;
        }
        
        .timer-warning {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 5px;
            padding: 10px;
            margin: 10px 0;
        }
        
        .question-navigation {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: white;
            padding: 15px;
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            z-index: 1000;
        }
        
        .nav-btn {
            width: 40px;
            height: 40px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 2px;
            text-decoration: none;
            font-weight: bold;
        }
        
        .nav-btn.current {
            background: var(--primary-color);
            color: white;
        }
        
        .nav-btn.answered {
            background: #28a745;
            color: white;
        }
        
        .progress-bar-quiz {
            height: 6px;
            border-radius: 3px;
        }
        
        .quiz-info-card {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <!-- Quiz Header -->
    <header class="quiz-header">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <div class="d-flex align-items-center">
                        <a href="quizzes.php" class="btn btn-outline-primary btn-sm me-3">
                            <i class="bi bi-arrow-left"></i>
                        </a>
                        <div>
                            <h6 class="mb-0 fw-bold"><?php echo $attempt['judul_quiz']; ?></h6>
                            <small class="text-muted">
                                <?php echo $attempt['course_title']; ?> - <?php echo $attempt['nama_guru']; ?>
                            </small>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="d-flex justify-content-end align-items-center">
                        <?php if ($attempt['waktu_menit'] > 0): ?>
                        <div class="me-3 text-end">
                            <small class="text-muted">Waktu Tersisa</small>
                            <div id="timer" class="fw-bold text-danger fs-5">
                                <?php echo gmdate("H:i:s", $time_remaining); ?>
                            </div>
                        </div>
                        <?php endif; ?>
                        <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="dashboard.php">
                                    <i class="bi bi-speedometer2 me-2"></i>Dashboard
                                </a></li>
                                <li><a class="dropdown-item" href="quizzes.php">
                                    <i class="bi bi-pencil-square me-2"></i>Kuis & Ujian
                                </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>
            </div>
        </div>
    </header>

    <div class="container-fluid">
        <div class="quiz-container">
            <!-- Quiz Info -->
            <div class="quiz-info-card">
                <div class="row">
                    <div class="col-md-4">
                        <small class="text-muted">Total Soal</small>
                        <div class="fw-bold"><?php echo $result_lms_questions->num_rows; ?> Soal</div>
                    </div>
                    <div class="col-md-4">
                        <small class="text-muted">Waktu</small>
                        <div class="fw-bold"><?php echo $attempt['waktu_menit']; ?> Menit</div>
                    </div>
                    <div class="col-md-4">
                        <small class="text-muted">Nilai Minimal Lulus</small>
                        <div class="fw-bold"><?php echo $attempt['passing_grade']; ?>%</div>
                    </div>
                </div>
                <?php if (!empty($attempt['deskripsi'])): ?>
                <div class="mt-3">
                    <small class="text-muted">Deskripsi Quiz</small>
                    <p class="mb-0"><?php echo $attempt['deskripsi']; ?></p>
                </div>
                <?php endif; ?>
            </div>

            <!-- Progress -->
            <div class="mb-4">
                <div class="d-flex justify-content-between mb-2">
                    <small class="text-muted">Progress Pengerjaan</small>
                    <small class="text-muted"><span id="answered-count">0</span> dari <?php echo $result_lms_questions->num_rows; ?> soal terjawab</small>
                </div>
                <div class="progress progress-bar-quiz">
                    <div id="progress-bar" class="progress-bar" style="width: 0%"></div>
                </div>
            </div>

            <!-- Quiz Form -->
            <form id="quizForm" method="POST">
                <?php if ($result_lms_questions->num_rows > 0): ?>
                    <?php $question_number = 1; ?>
                    <?php while($question = $result_lms_questions->fetch_assoc()): ?>
                        <div class="question-card" id="question-<?php echo $question_number; ?>">
                            <div class="d-flex align-items-start mb-3">
                                <div class="question-number"><?php echo $question_number; ?></div>
                                <div class="flex-grow-1">
                                    <h5 class="mb-3"><?php echo $question['pertanyaan']; ?></h5>
                                    
                                    <?php if ($question['tipe'] == 'pilihan_ganda'): ?>
                                        <div class="options-container">
                                            <?php if (!empty($question['opsi_a'])): ?>
                                                <input type="radio" id="q<?php echo $question['id']; ?>_a" 
                                                       name="question_<?php echo $question['id']; ?>" value="a" 
                                                       class="option-input">
                                                <label for="q<?php echo $question['id']; ?>_a" class="option-label">
                                                    <strong>A.</strong> <?php echo $question['opsi_a']; ?>
                                                </label>
                                            <?php endif; ?>
                                            
                                            <?php if (!empty($question['opsi_b'])): ?>
                                                <input type="radio" id="q<?php echo $question['id']; ?>_b" 
                                                       name="question_<?php echo $question['id']; ?>" value="b" 
                                                       class="option-input">
                                                <label for="q<?php echo $question['id']; ?>_b" class="option-label">
                                                    <strong>B.</strong> <?php echo $question['opsi_b']; ?>
                                                </label>
                                            <?php endif; ?>
                                            
                                            <?php if (!empty($question['opsi_c'])): ?>
                                                <input type="radio" id="q<?php echo $question['id']; ?>_c" 
                                                       name="question_<?php echo $question['id']; ?>" value="c" 
                                                       class="option-input">
                                                <label for="q<?php echo $question['id']; ?>_c" class="option-label">
                                                    <strong>C.</strong> <?php echo $question['opsi_c']; ?>
                                                </label>
                                            <?php endif; ?>
                                            
                                            <?php if (!empty($question['opsi_d'])): ?>
                                                <input type="radio" id="q<?php echo $question['id']; ?>_d" 
                                                       name="question_<?php echo $question['id']; ?>" value="d" 
                                                       class="option-input">
                                                <label for="q<?php echo $question['id']; ?>_d" class="option-label">
                                                    <strong>D.</strong> <?php echo $question['opsi_d']; ?>
                                                </label>
                                            <?php endif; ?>
                                        </div>
                                    <?php else: ?>
                                        <div class="form-group">
                                            <textarea name="question_<?php echo $question['id']; ?>" 
                                                      class="form-control" rows="5" 
                                                      placeholder="Tulis jawaban essay Anda di sini..."></textarea>
                                        </div>
                                    <?php endif; ?>
                                    
                                    <div class="mt-3">
                                        <small class="text-muted">
                                            <i class="bi bi-star-fill text-warning"></i>
                                            Poin: <?php echo $question['poin']; ?>
                                        </small>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php $question_number++; ?>
                    <?php endwhile; ?>

                    <!-- Submit Button -->
                    <div class="text-center mt-4 mb-5">
                        <button type="submit" name="submit_quiz" class="btn btn-success btn-lg px-5"
                                onclick="return confirm('Apakah Anda yakin ingin mengumpulkan quiz? Setelah dikumpulkan, Anda tidak dapat mengubah jawaban.')">
                            <i class="bi bi-send-check me-2"></i>Kumpulkan Quiz
                        </button>
                    </div>

                <?php else: ?>
                    <div class="text-center py-5">
                        <i class="bi bi-pencil-square text-muted" style="font-size: 4rem;"></i>
                        <h4 class="text-muted mt-3">Tidak ada soal</h4>
                        <p class="text-muted">Belum ada soal yang tersedia untuk quiz ini.</p>
                        <a href="quizzes.php" class="btn btn-primary">Kembali ke Daftar Quiz</a>
                    </div>
                <?php endif; ?>
            </form>
        </div>
    </div>

    <!-- Question Navigation -->
    <?php if ($result_lms_questions->num_rows > 0): ?>
    <div class="question-navigation">
        <div class="d-flex flex-wrap justify-content-center" style="max-width: 200px;">
            <?php for ($i = 1; $i <= $result_lms_questions->num_rows; $i++): ?>
                <a href="#question-<?php echo $i; ?>" class="nav-btn <?php echo $i == 1 ? 'current' : ''; ?>" 
                   data-question="<?php echo $i; ?>">
                    <?php echo $i; ?>
                </a>
            <?php endfor; ?>
        </div>
    </div>
    <?php endif; ?>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Timer Countdown
        <?php if ($attempt['waktu_menit'] > 0): ?>
        function updateTimer() {
            const timerElement = document.getElementById('timer');
            let timeArray = timerElement.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, submit otomatis
                        document.getElementById('quizForm').submit();
                        return;
                    }
                }
            }
            
            // Format ulang waktu
            timerElement.textContent = 
                hours.toString().padStart(2, '0') + ':' +
                minutes.toString().padStart(2, '0') + ':' +
                seconds.toString().padStart(2, '0');
            
            // Ubah warna menjadi merah jika waktu < 5 menit
            if (hours === 0 && minutes < 5) {
                timerElement.className = 'fw-bold text-danger fs-5';
            }
        }
        
        // Update timer setiap detik
        setInterval(updateTimer, 1000);
        <?php endif; ?>

        // Track answered lms_questions
        function updateProgress() {
            const totallms_questions = <?php echo $result_lms_questions->num_rows; ?>;
            const answeredInputs = document.querySelectorAll('.option-input:checked, textarea').length;
            const textareas = document.querySelectorAll('textarea');
            let answeredTextareas = 0;
            
            textareas.forEach(textarea => {
                if (textarea.value.trim() !== '') {
                    answeredTextareas++;
                }
            });
            
            const totalAnswered = answeredInputs + answeredTextareas;
            const progress = (totalAnswered / totallms_questions) * 100;
            
            document.getElementById('answered-count').textContent = totalAnswered;
            document.getElementById('progress-bar').style.width = progress + '%';
            
            // Update navigation buttons
            document.querySelectorAll('.nav-btn').forEach(btn => {
                const questionNum = parseInt(btn.getAttribute('data-question'));
                const questionElement = document.getElementById('question-' + questionNum);
                const hasAnswer = questionElement.querySelector('.option-input:checked, textarea[value!=""]');
                
                if (hasAnswer) {
                    btn.classList.add('answered');
                    btn.classList.remove('current');
                } else {
                    btn.classList.remove('answered');
                }
            });
        }

        // Initialize progress tracking
        document.addEventListener('DOMContentLoaded', function() {
            updateProgress();
            
            // Track radio button changes
            document.querySelectorAll('.option-input').forEach(input => {
                input.addEventListener('change', updateProgress);
            });
            
            // Track textarea changes
            document.querySelectorAll('textarea').forEach(textarea => {
                textarea.addEventListener('input', updateProgress);
            });
            
            // Navigation button click
            document.querySelectorAll('.nav-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    document.querySelectorAll('.nav-btn').forEach(b => {
                        b.classList.remove('current');
                    });
                    this.classList.add('current');
                });
            });
            
            // Auto-save progress setiap 30 detik
            setInterval(function() {
                // Simpan jawaban ke localStorage (opsional)
                const formData = new FormData(document.getElementById('quizForm'));
                const answers = {};
                for (let [key, value] of formData.entries()) {
                    answers[key] = value;
                }
                localStorage.setItem('quiz_answers_<?php echo $attempt_id; ?>', JSON.stringify(answers));
            }, 30000);
            
            // Load saved answers (opsional)
            const savedAnswers = localStorage.getItem('quiz_answers_<?php echo $attempt_id; ?>');
            if (savedAnswers) {
                const answers = JSON.parse(savedAnswers);
                for (let key in answers) {
                    const input = document.querySelector(`[name="${key}"]`);
                    if (input) {
                        if (input.type === 'radio') {
                            const radio = document.querySelector(`[name="${key}"][value="${answers[key]}"]`);
                            if (radio) radio.checked = true;
                        } else {
                            input.value = answers[key];
                        }
                    }
                }
                updateProgress();
            }
        });

        // Prevent accidental page leave
        window.addEventListener('beforeunload', function(e) {
            e.preventDefault();
            e.returnValue = 'Perubahan yang belum disimpan akan hilang. Apakah Anda yakin ingin meninggalkan halaman?';
        });

        // Remove beforeunload ketika form di-submit
        document.getElementById('quizForm').addEventListener('submit', function() {
            window.removeEventListener('beforeunload', arguments.callee);
            localStorage.removeItem('quiz_answers_<?php echo $attempt_id; ?>');
        });
    </script>
</body>
</html>