<?php
session_start();
include '../admin/includes/database.php';
include '../admin/includes/functions.php';
$conn = new Functions();


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $exam_id = $_POST['exam_id'];
    $student_id = $_POST['student_id'];
    $question_id = $_POST['question_id'];
    $answer = $_POST['answer'];

    // Fetch the correct answer from cbt_options
    $conn->query("SELECT option_text FROM cbt_options WHERE question_id = :question_id AND is_correct = 1");
    $conn->bind(":question_id", $question_id);
    $correct_option = $conn->fetchColumn();

    // Determine if the student's answer is correct (1 = correct, 0 = incorrect)
    $is_correct = (strtolower(trim($answer)) === strtolower(trim($correct_option))) ? 1 : 0;

    // Save or update the answer along with correctness
    $conn->query("INSERT INTO cbt_student_answers (exam_id, student_id, question_id, answer, is_correct) 
                  VALUES (:exam_id, :student_id, :question_id, :answer, :is_correct) 
                  ON DUPLICATE KEY UPDATE answer = :answer, is_correct = :is_correct");

    $conn->bind(":exam_id", $exam_id);
    $conn->bind(":student_id", $student_id);
    $conn->bind(":question_id", $question_id);
    $conn->bind(":answer", $answer);
    $conn->bind(":is_correct", $is_correct);
    $conn->execute();

    echo "Saved";
}




