<?php
/**
 * POST /api/v1/checkin.php
 *
 * Mirrors the website's candidate lifecycle on the live dashboard for the
 * mobile app. Called best-effort (online only) when an examiner opens a
 * candidate to grade ('checked_in') and when they start scoring
 * ('in_progress'). Offline grading skips this; the final attempt still creates
 * a session via attempts.php.
 *
 * Body: { candidate_id, form_id, status }   status in {checked_in, in_progress}
 */

require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../lib/api.php';

api_require_method('POST');
$user = api_auth($pdo);

$body        = api_body();
$candidateId = v_int($body['candidate_id'] ?? 0, 0);
$formId      = v_int($body['form_id'] ?? 0, 0);
$status      = v_clean_string($body['status'] ?? '', 20);

if ($candidateId <= 0 || $formId <= 0) {
    api_error('invalid_input', 422);
}
if (!in_array($status, ['checked_in', 'in_progress'], true)) {
    api_error('invalid_status', 422);
}

$cs = $pdo->prepare('SELECT * FROM candidates WHERE id = ? AND deleted_at IS NULL');
$cs->execute([$candidateId]);
$candidate = $cs->fetch();

$fs = $pdo->prepare('SELECT * FROM forms WHERE id = ? AND deleted_at IS NULL');
$fs->execute([$formId]);
$form = $fs->fetch();

if (!$candidate || !$form) {
    api_error('invalid_submission', 422);
}
if (!perms_owns_facility($user, $candidate['facility_id'])) {
    api_error('forbidden_facility', 403);
}

$station  = (string) $form['name'];
$duration = (int) ($form['default_duration_minutes'] ?? 8);

$sess = $pdo->prepare('SELECT id FROM osce_sessions WHERE candidate_id = ? AND station = ? LIMIT 1');
$sess->execute([$candidateId, $station]);
$existing = $sess->fetch();

if ($status === 'checked_in') {
    if ($existing) {
        $pdo->prepare("
            UPDATE osce_sessions
            SET status = 'checked_in', examiner_id = ?, start_time = NOW(),
                duration_minutes = ?, grading_started_at = NULL, submitted_at = NULL,
                last_action = 'Candidate checked in (mobile)'
            WHERE id = ?
        ")->execute([$user['id'], $duration, (int) $existing['id']]);
    } else {
        $pdo->prepare("
            INSERT INTO osce_sessions
                (candidate_id, station, examiner_id, status, start_time, duration_minutes, last_action)
            VALUES (?, ?, ?, 'checked_in', NOW(), ?, 'Candidate checked in (mobile)')
        ")->execute([$candidateId, $station, $user['id'], $duration]);
    }
    audit_log($pdo, 'station_check_in', [
        'candidate_id' => $candidateId,
        'form_id'      => $formId,
        'duration_min' => $duration,
        'source'       => 'mobile',
    ]);
} else { // in_progress
    if ($existing) {
        $pdo->prepare("
            UPDATE osce_sessions
            SET status = 'in_progress', examiner_id = ?,
                grading_started_at = COALESCE(grading_started_at, NOW()),
                last_action = 'Grading in progress (mobile)'
            WHERE id = ?
        ")->execute([$user['id'], (int) $existing['id']]);
    } else {
        $pdo->prepare("
            INSERT INTO osce_sessions
                (candidate_id, station, examiner_id, status, start_time,
                 grading_started_at, duration_minutes, last_action)
            VALUES (?, ?, ?, 'in_progress', NOW(), NOW(), ?, 'Grading in progress (mobile)')
        ")->execute([$candidateId, $station, $user['id'], $duration]);
    }
}

api_ok();
