<?php
/**
 * GET /api/v1/candidate_lookup.php?barcode=C000008
 *
 * Resolve a scanned barcode to a candidate (online path). Offline, the app
 * resolves against its cached bootstrap data; this endpoint is the
 * authoritative online lookup and enforces facility scoping.
 */

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

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

$barcode = v_clean_string($_GET['barcode'] ?? '', 50);
if ($barcode === '' || !v_barcode($barcode)) {
    api_error('invalid_barcode', 422);
}

$st = $pdo->prepare('
    SELECT c.id, c.facility_id, c.candidate_number, c.name, c.section,
           c.circuit_type, c.cohort_year, c.barcode, f.name AS facility_name
    FROM candidates c
    JOIN facilities f ON c.facility_id = f.id
    WHERE c.barcode = ? AND c.deleted_at IS NULL
    LIMIT 1
');
$st->execute([$barcode]);
$c = $st->fetch();

if (!$c) {
    api_error('candidate_not_found', 404);
}
if (!perms_owns_facility($user, $c['facility_id'])) {
    api_error('forbidden_facility', 403);
}

api_ok([
    'candidate' => [
        'id'               => (int) $c['id'],
        'facility_id'      => (int) $c['facility_id'],
        'facility_name'    => $c['facility_name'],
        'candidate_number' => $c['candidate_number'],
        'name'             => $c['name'],
        'section'          => $c['section'],
        'circuit_type'     => $c['circuit_type'],
        'cohort_year'      => $c['cohort_year'],
        'barcode'          => $c['barcode'],
    ],
]);
