<?php
// student/submit_exam.php
require_once '../config/config.php';

if (!isset($_SESSION['student_id'])) {
    redirect('student/register.php');
}

$student_id = $_SESSION['student_id'];
$exam_id = $_SESSION['exam_id'];

$stmt = $pdo->prepare("SELECT * FROM student_exams WHERE student_id = ? AND exam_id = ?");
$stmt->execute([$student_id, $exam_id]);
$student_exam = $stmt->fetch();

if ($student_exam->status !== 'in_progress') {
    redirect('student/result.php');
}

$stmt = $pdo->prepare("SELECT * FROM exams WHERE id = ?");
$stmt->execute([$exam_id]);
$exam = $stmt->fetch();

// Calculate results
$stmt = $pdo->prepare("
    UPDATE student_answers sa
    JOIN questions q ON sa.question_id = q.id
    SET sa.is_correct = (sa.selected_answer = q.correct_answer)
    WHERE sa.student_exam_id = ?
");
$stmt->execute([$student_exam->id]);

// Get stats
$stmt = $pdo->prepare("
    SELECT 
        COUNT(CASE WHEN is_correct = 1 THEN 1 END) as correct,
        COUNT(CASE WHEN is_correct = 0 AND selected_answer IS NOT NULL THEN 1 END) as wrong,
        COUNT(CASE WHEN selected_answer IS NULL THEN 1 END) as unanswered,
        SUM(CASE WHEN sa.is_correct = 1 THEN q.marks ELSE 0 END) as obtained_marks
    FROM student_answers sa
    JOIN questions q ON sa.question_id = q.id
    WHERE sa.student_exam_id = ?
");
$stmt->execute([$student_exam->id]);
$stats = $stmt->fetch();

$percentage = ($exam->total_marks > 0) ? ($stats->obtained_marks / $exam->total_marks) * 100 : 0;
$pass_percentage = ($exam->total_marks > 0) ? ($exam->passing_marks / $exam->total_marks) * 100 : 0;
$result = ($percentage >= $pass_percentage) ? 'pass' : 'fail';

$start_time = strtotime($student_exam->start_time);
$time_taken = time() - $start_time;

$stmt = $pdo->prepare("
    UPDATE student_exams 
    SET status = 'completed', end_time = NOW(), time_taken = ?, 
        obtained_marks = ?, percentage = ?, correct_answers = ?, 
        wrong_answers = ?, unanswered = ?, result = ?, submitted_at = NOW()
    WHERE id = ?
");
$stmt->execute([
    $time_taken, $stats->obtained_marks, round($percentage, 2),
    $stats->correct, $stats->wrong, $stats->unanswered, $result, $student_exam->id
]);

redirect('student/result.php');