<?php
require_once "config.php";
session_start();

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

$student_id = $_SESSION['student_id'];
$exam_id = $_POST['exam_id'];
$attempt_id = $_POST['attempt_id'];
$answers = $_POST['answers'] ?? [];

// Fetch exam questions
$stmt = $dbh->prepare("SELECT q.id,q.type,q.correct_answer FROM exam_questions eq 
    JOIN questions q ON eq.question_id=q.id 
    WHERE eq.exam_id=?");
$stmt->execute([$exam_id]);
$questions = $stmt->fetchAll(PDO::FETCH_ASSOC);

$score = 0;
$total = count($questions);

// Save answers + auto-mark
foreach ($questions as $q) {
    $qid = $q['id'];
    $given = $answers[$qid] ?? null;
    $mark = 0;

    if ($q['type'] == 'objective' && $given !== null) {
        if (strtolower(trim($given)) == strtolower(trim($q['correct_answer']))) {
            $mark = 1;
            $score++;
        }
    }

    $stmt = $dbh->prepare("INSERT INTO student_answers (student_id,question_id,answer_text,marked_score,marked_at) 
        VALUES (?,?,?,?,NOW())");
    $stmt->execute([$student_id,$qid,$given,$mark]);
}

// Save attempt
$stmt = $dbh->prepare("UPDATE exam_attempts SET submitted_at=NOW(), status='submitted', score=?, time_taken_seconds=?, last_saved_at=NOW() WHERE id=?");
$stmt->execute([$score,$total*60,$attempt_id]);

// Save in student_scores
$stmt = $dbh->prepare("INSERT INTO student_scores (student_id,subject_id,term_id,score,total_questions) 
    VALUES (?,?,?,?,?)");
$stmt->execute([$student_id,$exam['subject_id'],$exam['term_id'],$score,$total]);

header("Location: view_result.php?exam_id=$exam_id");
exit;
