<?php
session_start();
require_once "config.php";
if (!isset($_SESSION['student_id'])) exit;

$student_id = $_SESSION['student_id'];
$exam_id = intval($_GET['exam_id'] ?? 0);
$answers = $_POST['answers'] ?? [];

// Update attempt last_saved_at
$stmt = $dbh->prepare("INSERT INTO exam_attempts (exam_id, student_id, started_at, status) 
    VALUES (?, ?, NOW(), 'in-progress')
    ON DUPLICATE KEY UPDATE last_saved_at=NOW()");
$stmt->execute([$exam_id, $student_id]);

// Save answers
foreach ($answers as $qid=>$ans) {
    $stmt = $dbh->prepare("INSERT INTO student_answers (student_id, question_id, answer_text) 
        VALUES (?, ?, ?) 
        ON DUPLICATE KEY UPDATE answer_text=VALUES(answer_text)");
    $stmt->execute([$student_id, $qid, $ans]);
}
echo "saved";
