<?php
// =============================================================
//  GET /api/v1/credentials/list
//
//  Mirrors app/manage_credentials.php's own list build — every row in
//  the `credentials` table (certifications/licenses with expiry dates:
//  CPR, BLS, nursing license, immunizations, etc.), each enriched with
//  the owner's resolved name and a computed expiry status ('expired' |
//  'expiring_soon' | 'valid') via the same include/CredentialHelpers.php
//  logic scripts/check_credential_expiry.php's reminder cron also uses,
//  so "what counts as expiring soon" can't drift between surfaces.
//
//  Gated on 'edit_user' — matching the desktop page exactly (no
//  dedicated credentials permission exists in the catalog yet).
// =============================================================

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

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

api_authenticate();
api_require_permission('edit_user');

if (!$conn->query("SHOW TABLES LIKE 'credentials'")->num_rows) {
    Api::success(['credentials' => [], 'table_ready' => false]);
}

$OWNER_LABELS = [
    'users'             => 'Staff',
    'rotation_nurses'   => 'Rotation Nurse',
    'clinical_students' => 'Clinical Student',
];

$rows = $conn->query("SELECT * FROM credentials ORDER BY expiry_date ASC")->fetch_all(MYSQLI_ASSOC);

$accountRepo = new AccountRepository($conn);
foreach ($rows as &$c) {
    $account = $accountRepo->findById($c['owner_table'], (int)$c['owner_id']);
    $c['owner_name'] = $account ? $account->getFullName() : '(deleted account)';
    $c['owner_table_label'] = $OWNER_LABELS[$c['owner_table']] ?? $c['owner_table'];
    $c['status_computed'] = credentialStatus($c['expiry_date']);
}
unset($c);

Api::success(['credentials' => $rows, 'table_ready' => true]);
