<?php
session_start();
require 'connection/config.php'; // Ensure this file connects to your database

$question_level = $_SESSION['question_level'] ?? '';
$matric = $_SESSION['matric_number'] ?? 'No Matric';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $question_id = $_POST['question_id'] ?? 'No QID';
    $chosen_option = $_POST['answer'] ?? 'No Answer';

    // Debugging: Log received values
    file_put_contents('debug_log.txt', "Matric: $matric, QID: $question_id, Answer: $chosen_option\n", FILE_APPEND);

    // Validate received data
    if ($matric == 'No Matric' || $question_id == 'No QID' || $chosen_option == 'No Answer') {
        echo "error: missing data";
        exit;
    }

    // Fetch the correct answer from the database
    $stmt = $pdo->prepare("SELECT ans FROM `$question_level` WHERE id = ?");
    $stmt->execute([$question_id]);
    $correct_option = $stmt->fetchColumn();

    if (!$correct_option) {
        echo "error: invalid question";
        exit;
    }

    // Determine if the chosen option is correct
    $is_correct = ($chosen_option === $correct_option) ? 1 : 0;

    // Check if the answer already exists for this question
    $stmt = $pdo->prepare("SELECT id FROM answers_record WHERE matric = ? AND question_id = ?");
    $stmt->execute([$matric, $question_id]);
    $existing_id = $stmt->fetchColumn();

    if ($existing_id) {
        // Update the existing answer
        $query = "UPDATE answers_record 
                  SET chosen_option = ?, correct_option = ?, is_correct = ?, timestamp = NOW()
                  WHERE id = ?";
        $stmt = $pdo->prepare($query);
        $success = $stmt->execute([$chosen_option, $correct_option, $is_correct, $existing_id]);
    } else {
        // Insert a new answer record
        $query = "INSERT INTO answers_record (matric, question_id, chosen_option, correct_option, is_correct, timestamp) 
                  VALUES (?, ?, ?, ?, ?, NOW())";
        $stmt = $pdo->prepare($query);
        $success = $stmt->execute([$matric, $question_id, $chosen_option, $correct_option, $is_correct]);
    }

    // Log database action result
    file_put_contents('debug_log.txt', "DB Save Status: " . ($success ? "Success" : "Fail") . "\n", FILE_APPEND);

    echo $success ? "success" : "error: database issue";
}
?>
