<?php
ob_start();
require_once('operations.php');
error_reporting(E_ALL ^ E_NOTICE);

$db = new Operations();

// ✅ Validate required POST fields
if (!isset($_POST['examcode'], $_POST['admissionno'], $_POST['token'])) {
    die("Missing exam submission data.");
}

$examcode    = $_POST['examcode'];
$admissionno = $_POST['admissionno'];
$token       = $_POST['token'];

// ✅ Fetch exam session from DB using token + examcode + admissionno
$sessionData = $db->findExamSession($examcode, $admissionno, $token);
if (!$sessionData) {
    die("Invalid or expired exam session.");
}

// Decode stored questions
$questions = json_decode($sessionData['question_list'], true);
if (!$questions) {
    die("No questions found for this exam session.");
}

// Student info from session table
$lname  = $sessionData['lname'];
$fname  = $sessionData['fname'];
$class2 = $sessionData['class'];

//$class2 = "NILL";

// ✅ Get answers from POST
if (isset($_POST['choices']) && is_array($_POST['choices'])) {
    $answers = $_POST['choices'];
} else {
    die("No answers submitted.");
}

$score = 0;
$date  = date('Y-m-d');

// ✅ Compute score
foreach ($questions as $index => $q) {
    $qnum           = $index + 1;
    $question_id    = $q['id'];
    $correct_answer = trim($q['answer']);
    $student_answer = trim($answers[$qnum] ?? ''); // allow blank

    if ($student_answer === $correct_answer) {
        $score++;
    }

    // Record each answer (even if blank)
    $db->addExamAudit($examcode, $admissionno, $question_id, $student_answer, $date);
}

// ✅ Fetch exam info for subject and class
$db->findExamsById($examcode);

// ✅ Save score in permanent table
$db->addScores(
    $db->subject_id,
    $examcode,
    $lname,
    $fname,
    $db->class,
    $admissionno,
    $score,
    $class2
);

// ✅ Delete this student's row from exam_sessions table (cleanup)
$db->deleteExamSession($examcode, $admissionno, $token);

?>

<!DOCTYPE html>
<html>
<head>
    <title>Exam Submitted</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
</head>
<body class="bg-light text-center p-5">
    <div class="container">
        <div class="alert alert-success">
            <h1>Exam Submitted Successfully!</h1>
            <!-- Uncomment if you want to display score -->
            <!-- <p class="lead">Score: <strong class="text-primary"><?= htmlspecialchars($score) ?></strong></p> -->
            <a href="studentLogin.php" class="btn btn-primary mt-3">Go Back</a>
        </div>
    </div>
    
    <script>
    localStorage.clear();
    sessionStorage.clear();
    </script>
</body>
</html>
