<?php
// =============================================================
//  GET /api/v1/attendance/checkin_token?unit_id=NN
//
//  Rotating QR check-in token for a unit's display screen — the mobile
//  replacement for the deleted app/checkin_display.php + the deleted
//  ajax/checkin_token.php pair, both removed when the desktop web app was
//  dropped from this repo. include/CheckinToken.php (the HMAC rotating-
//  token logic) never changed; only the thing that called it and rendered
//  it did. checkin_scan.php's own header comment already documents that
//  the Flutter camera side scans exactly this same rotating code — this
//  endpoint is what puts it on screen in the first place.
//
//  Access: anyone holding 'manage_units' (Admin and anyone else with that
//  permission — same gate as admin_reference/units_list.php), OR an
//  In_Charge showing their own assigned unit(s). hydrateRequestContext()
//  populates $_SESSION['unit_ids'] for In_Charge accounts (see
//  include/session_setup.php) — reused here rather than re-deriving it.
//
//  Read-only: no eligibility/attendance side effects. checkin_scan.php
//  still owns all of that, and re-verifies the token itself rather than
//  trusting anything from this endpoint.
// =============================================================

require_once __DIR__ . '/../_bootstrap.php';
require_once __DIR__ . '/../../../include/CheckinToken.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    Api::error(405, 'MethodNotAllowed', 'Use GET');
}

$account = api_authenticate();
if ($account->getTable() !== 'users') {
    Api::error(403, 'Forbidden', 'This action is for staff accounts only');
}

$unitId = (int)($_GET['unit_id'] ?? 0);
if (!$unitId) {
    Api::error(422, 'ValidationError', 'unit_id is required');
}

$ownUnitIds = $_SESSION['unit_ids'] ?? [];
if (!PermissionManager::sessionCan('manage_units') && !in_array($unitId, $ownUnitIds, true)) {
    Api::error(403, 'Forbidden', 'You can only display the check-in code for your own unit.');
}

$stmt = $conn->prepare("SELECT unit_name FROM units WHERE id = ? AND status = 'Active'");
$stmt->bind_param('i', $unitId);
$stmt->execute();
$unit = $stmt->get_result()->fetch_assoc();
$stmt->close();
if (!$unit) {
    Api::error(404, 'NotFound', 'Unit not found or inactive.');
}

Api::success([
    'unit_id'                => $unitId,
    'unit_name'               => $unit['unit_name'],
    'token'                   => CheckinToken::generate($unitId),
    'seconds_until_rotation'  => CheckinToken::secondsUntilRotation(),
]);

