<?php
// scan_barcode.php – tiny endpoint used by external scanner hardware.
// JSON in: { "barcode": "C000001", "station": "cvs" }
// Returns JSON. Requires login (super_admin or facility examiner).
require_once __DIR__ . '/auth.php';
require_login();

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'method_not_allowed']);
    exit;
}
if (!csrf_check()) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'csrf']);
    exit;
}

$user = current_user();
// Allowed roles: super_admin or facility (legacy "examiner" role does NOT exist in this schema)
if (!in_array($user['role'], ['super_admin','facility'], true)) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'forbidden']);
    exit;
}

$body = json_decode(file_get_contents('php://input') ?: '[]', true) ?: [];
$barcode = v_clean_string($body['barcode'] ?? $_POST['barcode'] ?? '', 50);
$station = v_clean_string($body['station'] ?? $_POST['station'] ?? '', 100);
$duration = v_int($body['duration_minutes'] ?? $_POST['duration_minutes'] ?? 8, 0, 30, 8);

if ($barcode === '' || $station === '' || !v_barcode($barcode)) {
    http_response_code(422);
    echo json_encode(['ok' => false, 'error' => 'invalid_input']);
    exit;
}

$stmt = $pdo->prepare("SELECT id, facility_id FROM candidates WHERE barcode = ? AND deleted_at IS NULL");
$stmt->execute([$barcode]);
$candidate = $stmt->fetch();
if (!$candidate) {
    http_response_code(404);
    echo json_encode(['ok' => false, 'error' => 'candidate_not_found']);
    exit;
}
if ($user['role'] !== 'super_admin' && $user['facility_id'] && (int)$candidate['facility_id'] !== (int)$user['facility_id']) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'forbidden_facility']);
    exit;
}

try {
    $pdo->beginTransaction();
    $check = $pdo->prepare("SELECT id FROM osce_sessions WHERE candidate_id = ? AND station = ?");
    $check->execute([$candidate['id'], $station]);
    $existing = $check->fetch();

    if ($existing) {
        $pdo->prepare("
            UPDATE osce_sessions
            SET status='checked_in', start_time=NOW(), examiner_id=?, duration_minutes=?, last_action='Candidate checked in (barcode scanned)'
            WHERE id = ?
        ")->execute([$user['id'], $duration, $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 (barcode scanned)')
        ")->execute([$candidate['id'], $station, $user['id'], $duration]);
    }
    $pdo->commit();

    audit_log($pdo, 'station_check_in_api', [
        'candidate_id' => (int)$candidate['id'],
        'station'      => $station,
        'duration_min' => $duration,
    ]);

    echo json_encode(['ok' => true, 'candidate_id' => (int)$candidate['id']]);
} catch (Throwable $e) {
    $pdo->rollBack();
    error_log('scan_barcode: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'server_error']);
}
