<?php
session_start();
//saveAnswer(currentIndex);
include "connection/config.php"; // Ensure database connection is working

// Retrieve session variables
$matric = $_SESSION['matric_number'] ?? null;
$fname = $_SESSION['student_fname'] ?? null;
$dept=$_SESSION['dept'] ?? null;
$question_level = $_SESSION['question_level'] ?? null; // Ensure question_level is stored

if (!$matric || !$question_level) {
    die("Unauthorized access.");
}

// Define dynamic score table name
$score_table = $question_level . "score";

// Fetch the total correct answers for the student
$sql = "SELECT COUNT(*) FROM answers_record WHERE matric = ? AND is_correct = 1";
$stmt = $pdo->prepare($sql);
$stmt->execute([$matric]);
$score = $stmt->fetchColumn(); // Total correct answers

// Insert or Update the score in the dynamic table
$checkExisting = "SELECT COUNT(*) FROM `$score_table` WHERE matric = ?";
$stmt = $pdo->prepare($checkExisting);
$stmt->execute([$matric]);
$exists = $stmt->fetchColumn();

if ($exists) {
    // Update existing score
    $update = "UPDATE `$score_table` SET score = ? WHERE matric = ?";
    $stmt = $pdo->prepare($update);
    $stmt->execute([$score, $matric, $dept]);
} else {
    // Insert new score
    $insert = "INSERT INTO `$score_table` (matric, fname, score, dept) VALUES (?, ?, ?, ?)";
    $stmt = $pdo->prepare($insert);
    $stmt->execute([$matric, $fname, $score, $dept]);
}
	$stmt = $pdo->prepare("DELETE FROM answers_record WHERE matric = ?");
    $stmt->execute([$matric]);
// Redirect to result page
header("Location: index.php");
exit;
?>
