<?php
// submit_answers.php
session_start();
$question_level = $_SESSION['question_level'];
$student_name= $_SESSION['student_fname'];
$dept=$_SESSION['dept'];

include('connection/config.php');
// Check if data is sent
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $matric = $_SESSION['matric_number']; // Assuming you saved matric number in session
    $question_level_score = $question_level."score"; // Your score table name

    $answers = $_POST['answers']; // This will be an array
    $score = $_POST['score']; // Total score

    // Insert or Update the student's score
	$stmt = $pdo->prepare("SELECT COUNT(*) FROM `$question_level_score` WHERE matric = ?");
	$stmt->execute([$matric]);
	$count = $stmt->fetchColumn();

	if ($count > 0) {
		// Student has already attempted the test, so update their score
		$stmt = $pdo->prepare("UPDATE `$question_level_score` SET score = ? WHERE matric = ?");
		$stmt->execute([$score, $matric]);
	} else {
		// Student has not attempted the test yet, so insert a new record
		$stmt = $pdo->prepare("INSERT INTO `$question_level_score` (matric, fname, score, dept) VALUES (?, ?, ?, ?)");
		$stmt->execute([$matric, $student_name, $score, $dept]);
	}

    // Optionally: You can also save all chosen answers into another table if needed

    echo "success";
} else {
    echo "Invalid Request.";
}
?>

