<?php
error_reporting(E_ALL); ini_set('display_errors', 1); session_start(); require_once 'db.php';

// Redirect if the session wasn't properly initialized or exam hasn't started
if (!isset($_SESSION['started']) || !isset($_SESSION['student_id']) || !isset($_SESSION['course_id'])) {
    header("Location: portal.php"); exit();
}

$student_id = $_SESSION['student_id'];
$course_id  = $_SESSION['course_id'];
$score      = 0;
$total_questions = count($_SESSION['questions']);

// Capture user selections from the POST submission
$submitted_answers = isset($_POST['answers']) ? $_POST['answers'] : [];

try {
    // 1. Fetch correct answers ONLY for the 30 questions allocated to this exam session
    $question_ids = array_column($_SESSION['questions'], 'id');
    
    if (!empty($question_ids)) {
        // Create an array of question marks (?) for the secure SQL IN clause
        $placeholders = implode(',', array_fill(0, count($question_ids), '?'));
        
        // Ensure your database questions table has a 'correct_option' column (storing A, B, C, or D)
        $stmt = $pdo->prepare("SELECT id, correct_option FROM questions WHERE id IN ($placeholders)");
        $stmt->execute($question_ids);
        $correct_answers = $stmt->fetchAll(PDO::FETCH_KEY_PAIR); // Formats as: [question_id => correct_letter]
        
        // 2. Loop through the allocated questions to calculate the score
        foreach ($question_ids as $q_id) {
            $student_choice = isset($submitted_answers[$q_id]) ? strtoupper(trim($submitted_answers[$q_id])) : '';
            $correct_choice = isset($correct_answers[$q_id]) ? strtoupper(trim($correct_answers[$q_id])) : '';
            
            if (!empty($student_choice) && $student_choice === $correct_choice) {
                $score++;
            }
        }
    }

    // 3. Save the score details to your central results table
    $insertResult = $pdo->prepare("INSERT INTO results (student_id, course_id, total_questions, score_obtained, date_taken) VALUES (?, ?, ?, ?, NOW())");
    $insertResult->execute([$student_id, $course_id, $total_questions, $score]);

    // 4. Clean up the session details so the student can't re-enter the test
    unset($_SESSION['questions']);
    unset($_SESSION['total_questions']);
    unset($_SESSION['end_time']);
    unset($_SESSION['started']);

} catch (\PDOException $e) {
    die("An error occurred while saving your scores. Please contact the administrator.");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"><title>Exam Submitted Successfully</title>
    <style>
        body { font-family: Arial, sans-serif; background: #f4f6f9; text-align: center; padding: 50px; }
        .result-box { max-width: 500px; margin: 0 auto; background: white; padding: 40px; border-radius: 8px; box-shadow: 0 4px 15px rgba(0,0,0,0.1); border-top: 5px solid #28a745; }
        .score { font-size: 48px; font-weight: bold; color: #28a745; margin: 20px 0; }
        .btn { display: inline-block; padding: 12px 24px; background: #007bff; color: white; text-decoration: none; font-weight: bold; border-radius: 4px; margin-top: 20px; }
    </style>
</head>
<body>
<div class="result-box">
    <h2>Submission Received</h2>
    <p>Thank you, <strong><?php echo htmlspecialchars($_SESSION['student_name']); ?></strong>. Your exam configuration session is complete.</p>
    
    <div class="score">
        <?php echo $score; ?> / <?php echo $total_questions; ?>
    </div>
    
    <p>Score Percentage: <strong><?php echo round(($score / $total_questions) * 100, 2); ?>%</strong></p>
    
    <a href="portal.php" class="btn">Return to Gate</a>
</div>
</body>
</html>
