<?php
require_once 'inc/connect.php';


if (!isset($_SESSION['student_id'], $_SESSION['token'], $_SESSION['exam_id'])) {
    echo json_encode(['success' => false, 'correct' => 0, 'score' => 0]);

    exit;
}
$data = json_decode(file_get_contents("php://input"), true);

// Extract incoming data
$ref = intval($data['question_set_ref']);
$question_id = $data['question_id'];
$exam_id = $data['examination_id'];
$token_id = $data['token_id'];
$answer = $data['submitted_answer'];

// Step 1: Fetch the correct answer from question_set
$stmt = $mysqli->prepare("SELECT correct_answer FROM question_set WHERE serial = ?");
$stmt->bind_param("i", $ref);
$stmt->execute();
$result = $stmt->get_result();
$correct_serial = 0;

if ($row = $result->fetch_assoc()) {
    $correct_serial = intval($row['correct_answer']);
}
$stmt->close();

// Step 2: Compare submitted answer to correct serial
$is_correct = ($answer == $correct_serial);
$score = $is_correct ? 1 : 0;








// Step 3: Close any previous submissions for this question_set_ref and token_id
$closebb = $mysqli->prepare("UPDATE token_management 
                           SET last_activity = NOW() 
                           WHERE  token_id = ?");
$closebb->bind_param("s",  $token_id);
$closebb->execute();






// Step 3: Close any previous submissions for this question_set_ref and token_id
$close = $mysqli->prepare("UPDATE student_attempt_log 
                           SET status = 'closed' 
                           WHERE question_set_ref = ? AND token_id = ?");
$close->bind_param("is", $ref, $token_id);
$close->execute();




// Step 3: Insert or replace into student_attempt_log
$log = $mysqli->prepare("REPLACE INTO student_attempt_log 
    (question_set_ref, question_id, examination_id, submitted_answer, correct_answer, loading_time, time_of_submission, submitted_status, score, token_id, status)
    VALUES (?, ?, ?, ?, ?, NOW(), NOW(), 'submitted', ?, ?, 'open')");
$log->bind_param("isssiis", $ref, $question_id, $exam_id, $answer, $correct_serial, $score, $token_id);
$log->execute();

echo json_encode(['success' => true, 'correct' => $is_correct, 'score' => $score]);






