<?php
// autosave_answer.php
require 'config.php';
session_start();
if (!isset($_SESSION['student_id'])) { echo "Unauthorized"; exit; }
$student_id = $_SESSION['student_id'];
$attempt_id = (int)($_POST['attempt_id'] ?? 0);
if (!$attempt_id) { echo "No attempt"; exit; }

// short helper to upsert answer for attempt+question
try {
    $dbh->beginTransaction();
    // save answers
    $answers = $_POST['answer'] ?? [];
    foreach ($answers as $qid => $val) {
        $q = trim($val);
        // check existing
        $sel = $dbh->prepare("SELECT id FROM attempt_answers WHERE attempt_id = :att AND question_id = :qid LIMIT 1");
        $sel->execute([':att'=>$attempt_id, ':qid'=>$qid]);
        $row = $sel->fetch(PDO::FETCH_ASSOC);
        if ($row) {
            $upd = $dbh->prepare("UPDATE attempt_answers SET answer_text = :a, last_saved_at = NOW() WHERE id = :id");
            $upd->execute([':a'=>$q, ':id'=>$row['id']]);
        } else {
            $ins = $dbh->prepare("INSERT INTO attempt_answers (attempt_id, question_id, answer_text, last_saved_at) VALUES (:att,:qid,:a,NOW())");
            $ins->execute([':att'=>$attempt_id, ':qid'=>$qid, ':a'=>$q]);
        }
    }
    // update attempt last_saved_at
    $dbh->prepare("UPDATE exam_attempts SET last_saved_at = NOW() WHERE id = :id")->execute([':id'=>$attempt_id]);

    $dbh->commit();
    echo "saved";
} catch (Exception $e) {
    $dbh->rollBack();
    echo "error: ".$e->getMessage();
}
