<?php
session_start();
require_once('../public/connection.php');

// Check if the request is valid
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get the data from the POST request
    $student_id = intval($_POST['student_id']);
    $exam_id = intval($_POST['exam_id']);
    $question_id = intval($_POST['question_id']);
    $mark = intval($_POST['mark']); // 1 for correct, 0 for incorrect

    // Validate the request
    if ($student_id && $exam_id && $question_id !== null && ($mark === 0 || $mark === 1)) {
        // Fetch the MCQ score from exam_results
        $stmt = $conn->prepare("SELECT mcq_score FROM exam_results WHERE student_id = ? AND exam_id = ?");
        $stmt->bind_param("ii", $student_id, $exam_id);
        $stmt->execute();
        $stmt->bind_result($mcq_score);
        $stmt->fetch();
        $stmt->close();

        // Default to 0 if mcq_score is not found
        $mcq_score = $mcq_score ?? 0;

        // The full score for the question (you can set your question's max score here)
        $question_max_score = 1; // Assuming each question has a max score of 1, adjust as needed

        // Calculate the total theory score based on the checked answer (correct = 1, incorrect = 0)
        $theory_score = $mark * $question_max_score; // If correct, award full score, otherwise 0

        // Update the theory score and total score in exam_results
        $total_score = $mcq_score + $theory_score;

        // Update exam_results table
        $update_stmt = $conn->prepare("UPDATE exam_results SET theory_score = ?, total_score = ? WHERE student_id = ? AND exam_id = ?");
        $update_stmt->bind_param("diii", $theory_score, $total_score, $student_id, $exam_id);
        if ($update_stmt->execute()) {
            // Respond with success
            echo json_encode(['success' => true]);
        } else {
            // Respond with failure
            echo json_encode(['success' => false]);
        }

        $update_stmt->close();
    } else {
        echo json_encode(['success' => false]);
    }
}
?>

