<?php
require_once __DIR__.'/db.php';
require_student();
$attempt_id = (int)($_POST['attempt_id'] ?? 0);
$quiz_id    = (int)($_POST['quiz_id'] ?? 0);
$student_id = (int)$_SESSION['student_id'];

// Validate attempt belongs to this student and is still active
$chk = $mysqli->query("
    SELECT COUNT(*)
    FROM attempts
    WHERE id = $attempt_id
      AND student_id = $student_id
      AND quiz_id = $quiz_id
      AND status = 'in_progress'
")->fetch_row()[0];

if (!$chk) {
    die('Invalid attempt.');
}

// Grading logic
$questions = $mysqli->query("SELECT id FROM questions WHERE quiz_id = $quiz_id");
$totalQuestions = 0;
$attemptedQuestions = 0;
$totalMarksObtained = 0;

while ($q = $questions->fetch_assoc()) {
    $qid = (int)$q['id'];
    $totalQuestions++;
    // Selected option for this question
    $opt_id = (int)($_POST['q'.$qid] ?? 0);
    if (!$opt_id) {
        // Not attempted
        continue;
    }
    $attemptedQuestions++;
    // Fetch marks of selected option
    $row = $mysqli->query("SELECT marks FROM options WHERE id = $opt_id")->fetch_assoc();
    $marks = $row ? (float)$row['marks'] : 0.0;
    $totalMarksObtained += $marks;
    // Save student's chosen answer
    $stmt = $mysqli->prepare("
        INSERT INTO attempt_answers (attempt_id, question_id, option_id, obtained_marks)
        VALUES (?,?,?,?)
    ");
    $stmt->bind_param("iiid", $attempt_id, $qid, $opt_id, $marks);
    $stmt->execute();
}

// Check if no questions were attempted
if ($attemptedQuestions == 0) {
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Quiz Incomplete</title>
        <link rel="stylesheet" href="assets/submit_quiz.css">
    </head>
    <body>
        <div class="popup-overlay">
            <div class="popup-container">
                <div class="popup-icon">
                    <svg viewBox="0 0 24 24" fill="none">
                        <circle cx="12" cy="12" r="10" stroke="white" stroke-width="2"/>
                        <line x1="12" y1="8" x2="12" y2="12" stroke="white" stroke-width="2" stroke-linecap="round"/>
                        <line x1="12" y1="16" x2="12" y2="16" stroke="white" stroke-width="2" stroke-linecap="round"/>
                    </svg>
                </div>
                <h2 class="popup-title">Time's Up!</h2>
                <p class="popup-message">Quiz cannot be submitted as no answer is selected. Please try again when you're ready.</p>
                <button class="popup-button" onclick="redirect()">OK</button>
            </div>
        </div>
        <script>
            function redirect() {
                window.location.href = 'quiz-index.php';
            }
        </script>
    </body>
    </html>
    <?php
    exit;
}

// Finalize attempt (only if at least 1 question was attempted)
$stmt = $mysqli->prepare("
    UPDATE attempts
    SET status = 'completed',
        score = ?,
        marksObtained = ?,
        completed_at = NOW()
    WHERE id = ?
");
$stmt->bind_param("idi", $attemptedQuestions, $totalMarksObtained, $attempt_id);
$stmt->execute();

// Redirect to certificate
header('Location: '.$base_url.'certificate.php?attempt_id=' . $attempt_id);
exit;