<?php
/**
 * student/process_result.php
 * Handles Exam Grading and Result Storage
 */
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once '../config/database.php';

// 1. SECURITY CHECK
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'student') {
    header("Location: ../auth/login.php");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("Location: dashboard.php");
    exit();
}

$exam_id = (int)$_POST['exam_id'];
$student_id = (int)$_SESSION['user_id'];
$submitted_answers = $_POST['ans'] ?? []; 

try {
    // 2. FETCH EXAM MARKING SCHEME
    $exam_stmt = $pdo->prepare("SELECT mark_per_question, exam_title FROM exams WHERE id = ?");
    $exam_stmt->execute([$exam_id]);
    $exam = $exam_stmt->fetch(PDO::FETCH_ASSOC);

    if (!$exam) { die("Exam configuration error."); }

    $mark_per_q = (float)$exam['mark_per_question'];

    // 3. FETCH CORRECT ANSWERS
    $q_stmt = $pdo->prepare("SELECT id, correct_option FROM questions WHERE exam_id = ?");
    $q_stmt->execute([$exam_id]);
    $db_questions = $q_stmt->fetchAll(PDO::FETCH_ASSOC);

    $total_questions = count($db_questions);
    $correct_count = 0;

    // 4. GRADING LOGIC
    foreach ($db_questions as $q) {
        $qid = $q['id'];
        $correct_ans = strtoupper(trim($q['correct_option']));
        
        if (isset($submitted_answers[$qid])) {
            $student_ans = strtoupper(trim($submitted_answers[$qid]));
            if ($student_ans === $correct_ans) {
                $correct_count++;
            }
        }
    }

    // 5. CALCULATIONS
    // Final Score = Correct Answers * Mark Per Question
    $final_score = $correct_count * $mark_per_q;
    // Total Possible = Total Questions * Mark Per Question
    $total_possible = $total_questions * $mark_per_q;

    // 6. SAVE ATTEMPT (Matching your exact table columns)
    $insert_stmt = $pdo->prepare("
        INSERT INTO exam_results (
            exam_id, 
            total_questions, 
            correct_answers, 
            student_id, 
            score, 
            total_possible, 
            end_time
        ) VALUES (?, ?, ?, ?, ?, ?, NOW())
    ");

    $insert_stmt->execute([
        $exam_id,
        $total_questions,
        $correct_count,
        $student_id,
        $final_score,
        $total_possible
    ]);

    // 7. SUCCESS REDIRECT
    $_SESSION['last_score'] = $final_score;
    $_SESSION['last_exam_title'] = $exam['exam_title'];
    
    header("Location: exam_complete.php");
    exit();

} catch (PDOException $e) {
    // Detailed error output for debugging
    die("Database Error: " . $e->getMessage());
}