<?php
include '../../includes/conn.php';
include '../../includes/functions.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $exam_id = intval($_POST['exam_id']);
    $student_id = $_SESSION['user_id'];

    // 🔒 Check if already submitted
    $check_stmt = $pdo->prepare("SELECT submitted_at FROM cbt_exam_results WHERE exam_id = ? AND student_id = ?");
    $check_stmt->execute([$exam_id, $student_id]);
    $existing = $check_stmt->fetch(PDO::FETCH_ASSOC);

    if ($existing && !empty($existing['submitted_at'])) {
        // Already submitted → redirect to result page
        header("Location: exam_result.php?exam_id=$exam_id&already_submitted=1");
        exit;
    }

    // Fetch all questions for this exam
    $questions_stmt = $pdo->prepare("SELECT id FROM cbt_questions WHERE exam_id = ?");
    $questions_stmt->execute([$exam_id]);
    $questions = $questions_stmt->fetchAll(PDO::FETCH_ASSOC);

    // Start transaction
    $pdo->beginTransaction();

    try {
        foreach ($questions as $q) {
            $q_id = $q['id'];
            $answer = $_POST['q_' . $q_id] ?? null;

            // Save answer
            $stmt = $pdo->prepare("
                INSERT INTO cbt_answers (exam_id, question_id, student_id, selected_option)
                VALUES (?, ?, ?, ?)
            ");
            $stmt->execute([$exam_id, $q_id, $student_id, $answer]);
        }

        // Calculate score (optional: if you already do this elsewhere, skip)
        $score_stmt = $pdo->prepare("
            SELECT COUNT(*) AS correct_count
            FROM cbt_answers a
            JOIN cbt_questions q ON a.question_id = q.id
            WHERE a.exam_id = ? AND a.student_id = ? AND a.selected_option = q.correct_option
        ");
        $score_stmt->execute([$exam_id, $student_id]);
        $score = $score_stmt->fetch(PDO::FETCH_ASSOC)['correct_count'] ?? 0;

        // Mark exam as submitted + save score
        $update = $pdo->prepare("
            UPDATE cbt_exam_results 
            SET submitted_at = NOW(), score = ?
            WHERE exam_id = ? AND student_id = ?
        ");
        $update->execute([$score, $exam_id, $student_id]);

        $pdo->commit();

        // ✅ Redirect to result page
        header("Location: exam_result.php?exam_id=$exam_id&success=1");
        exit;

    } catch (Exception $e) {
        $pdo->rollBack();
        die("Error submitting exam: " . $e->getMessage());
    }
}
?>
