<?php
require_once '../includes/db.php';

if (!isset($_SESSION['user_id'])) { header('Location: /auth/login.php'); exit; }
$user_id = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    check_csrf();
    $quiz_id = $_POST['quiz_id'];
    $course_id = $_POST['course_id'];
    $answers = $_POST['answers'];

    $total_questions = count($answers);
    $correct_answers = 0;

    foreach ($answers as $question_id => $option_id) {
        $stmt = $pdo->prepare("SELECT is_correct FROM options WHERE id = ? AND question_id = ?");
        $stmt->execute([$option_id, $question_id]);
        $result = $stmt->fetch();
        if ($result && $result['is_correct'] == 1) {
            $correct_answers++;
        }
    }

    $score = ($correct_answers / $total_questions) * 100;

    // Simpan hasil
    $stmt_save = $pdo->prepare("INSERT INTO quiz_attempts (user_id, quiz_id, score) VALUES (?, ?, ?)");
    $stmt_save->execute([$user_id, $quiz_id, $score]);

    // Redirect ke halaman hasil
    header("Location: quiz_result.php?attempt_id=" . $pdo->lastInsertId());
    exit;
}