<?php
// autosave_exam.php - saves theory answers in real-time
session_start();
require_once('../public/connection.php');

if (!isset($_SESSION['student_id'])) {
    http_response_code(401);
    echo "Unauthorized";
    exit;
}

$student_id = (int)$_SESSION['student_id'];
$exam_id = isset($_POST['exam_id']) ? (int)$_POST['exam_id'] : 0;
$answers = $_POST['answers'] ?? []; // associative array answers[qid] => text
$submitted_at = date("Y-m-d H:i:s");

if ($exam_id <= 0 || empty($answers)) {
    echo "Nothing to save";
    exit;
}

// Begin transaction
$conn->begin_transaction();

try {
    // Get or create exam_group_result row
    $stmt = $conn->prepare("SELECT id FROM exam_group_results WHERE student_id=? AND exam_group_id=(SELECT exam_group_id FROM exams WHERE id=?) LIMIT 1");
    $stmt->bind_param("ii", $student_id, $exam_id);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if ($row) {
        $exam_group_result_id = (int)$row['id'];
    } else {
        // Insert temporary exam_group_result with pending status
        $exam_group_id_stmt = $conn->prepare("SELECT exam_group_id, class, term, session, subject_id FROM exams WHERE id=? LIMIT 1");
        $exam_group_id_stmt->bind_param("i", $exam_id);
        $exam_group_id_stmt->execute();
        $exam_info = $exam_group_id_stmt->get_result()->fetch_assoc();
        $exam_group_id_stmt->close();

        $subject = '';
        if (!empty($exam_info['subject_id'])) {
            $subStmt = $conn->prepare("SELECT subjects FROM school_subjects WHERE id=? LIMIT 1");
            $subStmt->bind_param("i", $exam_info['subject_id']);
            $subStmt->execute();
            $subRow = $subStmt->get_result()->fetch_assoc();
            $subject = $subRow['subjects'] ?? '';
            $subStmt->close();
        }

        $insert = $conn->prepare("
            INSERT INTO exam_group_results (student_id, exam_group_id, class, term, session, subject, status, remarks, created_at, updated_at)
            VALUES (?, ?, ?, ?, ?, ?, 'pending', 'Auto-saved theory', NOW(), NOW())
        ");
        $insert->bind_param("iissss", $student_id, $exam_info['exam_group_id'], $exam_info['class'], $exam_info['term'], $exam_info['session'], $subject);
        $insert->execute();
        $exam_group_result_id = $insert->insert_id;
        $insert->close();
    }

    // Upsert theory answers
    foreach ($answers as $qid => $answerText) {
        $answerText = trim($answerText);
        if ($answerText === '') continue;

        $delStmt = $conn->prepare("DELETE FROM exam_answers WHERE student_id=? AND exam_group_result_id=? AND question_id=?");
        $delStmt->bind_param("iii", $student_id, $exam_group_result_id, $qid);
        $delStmt->execute();
        $delStmt->close();

        $insStmt = $conn->prepare("INSERT INTO exam_answers (student_id, exam_group_result_id, question_id, answer_text, created_at, updated_at) VALUES (?, ?, ?, ?, NOW(), NOW())");
        $insStmt->bind_param("iiis", $student_id, $exam_group_result_id, $qid, $answerText);
        $insStmt->execute();
        $insStmt->close();
    }

    $conn->commit();
    echo "Saved";

} catch (Exception $e) {
    $conn->rollback();
    http_response_code(500);
    echo "Error: " . $e->getMessage();
}
