<?php
// student/submit_exam.php - Handle Exam Submission with Multiple Question Types
require_once '../config/config.php';

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

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

// Get student exam
$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 || $student_exam->status === 'completed') {
    redirect('student/result.php');
}

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

// Calculate time taken with timezone offset
$TIMEZONE_OFFSET_HOURS = 10; // Same as exam.php
$timezone_offset_seconds = $TIMEZONE_OFFSET_HOURS * 3600;

$stmt = $pdo->prepare("SELECT UNIX_TIMESTAMP(start_time) as start_timestamp FROM student_exams WHERE id = ?");
$stmt->execute([$student_exam->id]);
$time_result = $stmt->fetch();
$start_timestamp = $time_result->start_timestamp;

$current_timestamp = time() + $timezone_offset_seconds;
$time_taken = $current_timestamp - $start_timestamp;

// Cap time_taken to exam duration (in case of timezone issues)
$max_time = $exam->duration * 60;
if ($time_taken > $max_time) {
    $time_taken = $max_time;
}
if ($time_taken < 0) {
    $time_taken = 0;
}

// Get all answers with question info
$stmt = $pdo->prepare("
    SELECT sa.*, q.question_type, q.correct_answer, q.marks, q.auto_grade, 
           q.case_sensitive, q.answer_hint
    FROM student_answers sa
    JOIN questions q ON sa.question_id = q.id
    WHERE sa.student_exam_id = ?
");
$stmt->execute([$student_exam->id]);
$answers = $stmt->fetchAll();

$correct_count = 0;
$wrong_count = 0;
$unanswered_count = 0;
$pending_manual = 0;
$obtained_marks = 0;
$total_auto_marks = 0;
$total_manual_marks = 0;

foreach ($answers as $answer) {
    $is_correct = 0;
    $student_answer = $answer->selected_answer ?? $answer->answer_text;
    
    // Check if answered
    if (empty($student_answer)) {
        $unanswered_count++;
        continue;
    }
    
    // Auto-gradable questions
    if ($answer->auto_grade) {
        $total_auto_marks += $answer->marks;
        
        switch ($answer->question_type) {
            case 'mcq_4':
            case 'mcq_3':
            case 'mcq_2':
            case 'true_false':
                // Direct comparison for MCQ and True/False
                $correct = strtolower(trim($answer->correct_answer));
                $given = strtolower(trim($answer->selected_answer));
                $is_correct = ($correct === $given) ? 1 : 0;
                break;
                
            case 'fill_blank':
                // Fill in the blank - check against correct answer and alternatives
                $correct_answers = [strtolower(trim($answer->correct_answer))];
                
                // Add alternative answers if provided
                if (!empty($answer->answer_hint)) {
                    $alternatives = explode(',', $answer->answer_hint);
                    foreach ($alternatives as $alt) {
                        $correct_answers[] = strtolower(trim($alt));
                    }
                }
                
                $given = $answer->case_sensitive 
                    ? trim($answer->selected_answer) 
                    : strtolower(trim($answer->selected_answer));
                
                if (!$answer->case_sensitive) {
                    $is_correct = in_array($given, $correct_answers) ? 1 : 0;
                } else {
                    // Case sensitive check
                    $correct_case = [trim($answer->correct_answer)];
                    if (!empty($answer->answer_hint)) {
                        foreach (explode(',', $answer->answer_hint) as $alt) {
                            $correct_case[] = trim($alt);
                        }
                    }
                    $is_correct = in_array(trim($answer->selected_answer), $correct_case) ? 1 : 0;
                }
                break;
        }
        
        // Update is_correct status
        $update_stmt = $pdo->prepare("UPDATE student_answers SET is_correct = ? WHERE id = ?");
        $update_stmt->execute([$is_correct, $answer->id]);
        
        if ($is_correct) {
            $correct_count++;
            $obtained_marks += $answer->marks;
        } else {
            $wrong_count++;
        }
        
    } else {
        // Manual grading required (essay, short_answer)
        $total_manual_marks += $answer->marks;
        $pending_manual++;
        
        // Mark as pending manual review
        $update_stmt = $pdo->prepare("UPDATE student_answers SET is_correct = NULL WHERE id = ?");
        $update_stmt->execute([$answer->id]);
    }
}

// Calculate percentage based on total exam marks
$total_marks = $exam->total_marks;
$percentage = ($total_marks > 0) ? ($obtained_marks / $total_marks) * 100 : 0;

// Determine pass/fail (only if no manual grading pending)
$result = null;
if ($pending_manual === 0 && $total_marks > 0) {
    $pass_percentage = ($exam->passing_marks / $total_marks) * 100;
    $result = ($percentage >= $pass_percentage) ? 'pass' : 'fail';
}

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

// Store pending manual count in session for result page
$_SESSION['pending_manual_grading'] = $pending_manual;
$_SESSION['total_manual_marks'] = $total_manual_marks;

redirect('student/result.php');