<?php
session_start();
include '../admin/includes/database.php';
include '../admin/includes/functions.php';
$conn = new Functions();

if (!isset($_SESSION['student'])) {
    header("Location: login.php");
    exit();
}

// Fetch student ID from the session username
$conn->query("SELECT studentID FROM student WHERE username = :username");
$conn->bind(":username", $_SESSION['student']);
$student_id = $conn->fetchColumn();

$exam_id = $_POST['exam_id'];
$question_ids = $_POST['question_ids'];
$student_answers = $_POST['answer'];

$total_questions = count($question_ids);
$correct_answers = 0;

// Loop through each question and check the answer
foreach ($question_ids as $question_id) {
    // Get the student's answer (if available)
    $student_answer = isset($student_answers[$question_id]) ? $student_answers[$question_id] : '';

    // Fetch the correct answer from cbt_options
    $conn->query("SELECT option_text FROM cbt_options WHERE question_id = :question_id AND is_correct = 1");
    $conn->bind(":question_id", $question_id);
    $correct_answer = $conn->fetchColumn();

    // Determine if the answer is correct
    $is_correct = ($correct_answer && strtolower(trim($student_answer)) == strtolower(trim($correct_answer))) ? 1 : 0;

    // Count correct answers for scoring
    if ($is_correct) {
        $correct_answers++;
    }

    // Save the student's answer and correctness to the database
    $conn->query("INSERT INTO cbt_student_answers (student_id, exam_id, question_id, answer, is_correct) 
                  VALUES (:student_id, :exam_id, :question_id, :answer, :is_correct)
                  ON DUPLICATE KEY UPDATE answer = :answer, is_correct = :is_correct");

    $conn->bind(":student_id", $student_id);
    $conn->bind(":exam_id", $exam_id);
    $conn->bind(":question_id", $question_id);
    $conn->bind(":answer", $student_answer);
    $conn->bind(":is_correct", $is_correct);
    $conn->execute();
}

// Calculate the student's score percentage
$score_percentage = ($total_questions > 0) ? ($correct_answers / $total_questions) * 100 : 0;

// Save the exam result to the cbt_results table
$conn->query("INSERT INTO cbt_results (student_id, exam_id, total_questions, correct_answers, score_percentage) 
              VALUES (:student_id, :exam_id, :total_questions, :correct_answers, :score_percentage)
              ON DUPLICATE KEY UPDATE correct_answers = :correct_answers, score_percentage = :score_percentage");

$conn->bind(":student_id", $student_id);
$conn->bind(":exam_id", $exam_id);
$conn->bind(":total_questions", $total_questions);
$conn->bind(":correct_answers", $correct_answers);
$conn->bind(":score_percentage", $score_percentage);
$conn->execute();

// Redirect to the exam results page
header("Location: exam_result.php?exam_id=$exam_id");
exit();

