<?php
// Debugging (Remove in production)
ini_set('display_errors', 1);
error_reporting(E_ALL);

session_start();
require_once 'db_connect.php';

// 1. Security Check: Redirect if student is not logged in
if (!isset($_SESSION['student_id'])) {
    header("Location: login.php");
    exit;
}

// Ensure the code only runs if the form was submitted via POST
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['exam_id'])) {
    $exam_id = (int)$_POST['exam_id'];
    $student_id = $_SESSION['student_id'];
    
    // Receive the submitted answers from take_exam.php
    $student_answers = isset($_POST['answers']) ? $_POST['answers'] : [];

    try {
        // 🛡️ Start Database Transaction (Prevents partial data saving on failure)
        $pdo->beginTransaction();

        // 2. Fetch Exam Information (including negative marking)
        $exam_stmt = $pdo->prepare("SELECT total_questions, negative_marks FROM exams WHERE id = ?");
        $exam_stmt->execute([$exam_id]);
        $exam = $exam_stmt->fetch(PDO::FETCH_ASSOC);

        if (!$exam) { throw new Exception("The exam could not be found in the database."); }

        // Set negative marks (default to 0 if not set in DB)
        $negative_marks = isset($exam['negative_marks']) ? (float)$exam['negative_marks'] : 0;

        // 3. Fetch all correct answers for this exam from the database at once
        $q_stmt = $pdo->prepare("SELECT id, correct_option FROM questions WHERE exam_id = ?");
        $q_stmt->execute([$exam_id]);
        
        // FETCH_KEY_PAIR creates an array in the format: [question_id => correct_option]
        $questions = $q_stmt->fetchAll(PDO::FETCH_KEY_PAIR); 

        $correct_count = 0;
        $wrong_count = 0;
        $not_attempted = 0;

        // 4. Compare Student's Answers with the Correct Answers
        foreach ($questions as $q_id => $correct_opt) {
            if (isset($student_answers[$q_id]) && trim($student_answers[$q_id]) !== '') {
                // Case-insensitive check (e.g., treats 'A' and 'a' as identical)
                $given_ans = strtolower(trim($student_answers[$q_id]));
                $actual_ans = strtolower(trim($correct_opt));

                if ($given_ans === $actual_ans) {
                    $correct_count++; // Correct Answer
                } else {
                    $wrong_count++;   // Wrong Answer
                }
            } else {
                $not_attempted++;     // Not Attempted (Skipped)
            }
        }

        // 5. Score Calculation (Correct Answers - (Wrong Answers * Negative Marks))
        $total_q = count($questions);
        $score = $correct_count - ($wrong_count * $negative_marks);
        
        // Prevent negative total scores (Score should not drop below 0)
        $score = max(0, $score); 
        
        // Percentage Calculation
        $percentage = ($total_q > 0) ? ($score / $total_q) * 100 : 0;
        $percentage = max(0, round($percentage, 2));

        // 6. Save the final result into the 'exam_result' table
        $res_stmt = $pdo->prepare("INSERT INTO exam_result (student_id, exam_id, total_questions, correct_answers, wrong_answers, not_attempted, score, percentage) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        $res_stmt->execute([
            $student_id, 
            $exam_id, 
            $total_q, 
            $correct_count, 
            $wrong_count, 
            $not_attempted,
            $score, 
            $percentage
        ]);

        // Get the ID of the newly inserted result
        $result_id = $pdo->lastInsertId();

        // 7. Save individual responses into 'student_responses' table for the Review System
        $resp_stmt = $pdo->prepare("INSERT INTO student_responses (result_id, question_id, selected_option) VALUES (?, ?, ?)");
        
        foreach ($questions as $q_id => $correct_opt) {
            $selected = (isset($student_answers[$q_id]) && trim($student_answers[$q_id]) !== '') ? trim($student_answers[$q_id]) : null;
            $resp_stmt->execute([$result_id, $q_id, $selected]);
        }

        // 8. Commit the transaction (Permanently save all data)
        $pdo->commit();

        // 9. Redirect the student to their detailed Result Page
        header("Location: exam_result.php?id=" . $result_id);
        exit;

    } catch (Exception $e) {
        // Rollback (undo) the transaction if any error occurs during the process
        $pdo->rollBack();
        die("Submission Error: " . $e->getMessage());
    }
} else {
    // Redirect direct URL accesses back to the Live Exams page
    header("Location: exams.php");
    exit;
}
?>