<?php
/**
 * undo_attempt.php – within 10 minutes of submitting, an examiner can
 * pull a submission back into draft state. After that window, use
 * edit_attempt.php (which keeps the row, just edits in place).
 */
require_once __DIR__ . '/auth.php';
require_login();

$user    = current_user();
$isSuper = is_super_admin();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo 'Method not allowed';
    exit;
}
csrf_require();

$attemptId = v_int($_POST['attempt_id'] ?? 0, 1);
if ($attemptId <= 0) {
    http_response_code(400);
    echo 'Bad request';
    exit;
}

$UNDO_WINDOW_MIN = 10;

$stmt = $pdo->prepare("
    SELECT a.*, c.barcode
    FROM attempts a
    JOIN candidates c ON c.id = a.candidate_id
    WHERE a.id = ? AND a.deleted_at IS NULL
");
$stmt->execute([$attemptId]);
$attempt = $stmt->fetch();

if (!$attempt) {
    header('Location: dashboard.php');
    exit;
}

// Permission: super_admin OR the original examiner
if (!$isSuper && (int)$attempt['examiner_id'] !== (int)$user['id']) {
    http_response_code(403);
    echo 'Forbidden';
    exit;
}

// Time check (super_admin bypass)
$ageSec = time() - strtotime($attempt['created_at']);
if (!$isSuper && $ageSec > $UNDO_WINDOW_MIN * 60) {
    header('Location: edit_attempt.php?id=' . $attemptId . '&reason=expired_undo');
    exit;
}

// Pull back: collect scores+comments into a fresh draft, soft-delete the
// attempt, re-open the session.
try {
    $pdo->beginTransaction();

    $items = $pdo->prepare("
        SELECT ai.form_item_id, ai.score, ai.comment
        FROM attempt_items ai
        WHERE ai.attempt_id = ?
    ");
    $items->execute([$attemptId]);
    $rows = $items->fetchAll();

    $payload = ['score' => [], 'item_comment' => [], 'global_comment' => (string)($attempt['global_comment'] ?? '')];
    foreach ($rows as $r) {
        $payload['score'][(string)(int)$r['form_item_id']]        = (string)(int)$r['score'];
        $payload['item_comment'][(string)(int)$r['form_item_id']] = (string)($r['comment'] ?? '');
    }

    $pdo->prepare("
        INSERT INTO grade_drafts (examiner_id, candidate_id, form_id, payload)
        VALUES (?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE payload = VALUES(payload), updated_at = CURRENT_TIMESTAMP
    ")->execute([
        $attempt['examiner_id'], $attempt['candidate_id'], $attempt['form_id'],
        json_encode($payload, JSON_UNESCAPED_UNICODE),
    ]);

    $pdo->prepare("UPDATE attempts SET deleted_at = NOW() WHERE id = ?")->execute([$attemptId]);

    $pdo->prepare("
        UPDATE osce_sessions
        SET status = 'in_progress',
            submitted_at = NULL,
            last_action  = 'Submission undone – returned to draft'
        WHERE candidate_id = ? AND station = ?
    ")->execute([$attempt['candidate_id'], $attempt['station_name']]);

    $pdo->commit();

    audit_log($pdo, 'grade_undo', [
        'attempt_id'   => $attemptId,
        'candidate_id' => (int)$attempt['candidate_id'],
        'form_id'      => (int)$attempt['form_id'],
        'age_seconds'  => $ageSec,
        'super_admin_bypass' => $isSuper && $ageSec > $UNDO_WINDOW_MIN * 60,
    ]);

    // send examiner back to grading flow for this candidate
    header('Location: grade.php?form_id=' . (int)$attempt['form_id'] . '&undone=1');
    exit;
} catch (Throwable $e) {
    $pdo->rollBack();
    error_log('grade_undo: ' . $e->getMessage());
    header('Location: edit_attempt.php?id=' . $attemptId . '&reason=undo_failed');
    exit;
}
