<?php
// =============================================================
//  GET /api/v1/profile/credentials
//
//  The authenticated account's own professional credentials (license
//  number, expiry, etc.) — read-only from mobile; issuing/revoking a
//  credential stays an admin action on the desktop app
//  (app/manage_credentials.php).
// =============================================================

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

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

$account = api_authenticate();

$stmt = $conn->prepare("
    SELECT id, credential_type, credential_number, issued_date, expiry_date, notes, status
    FROM credentials
    WHERE owner_table = ? AND owner_id = ? AND status = 'Active'
    ORDER BY expiry_date
");
$table = $account->getTable();
$id    = $account->getId();
$stmt->bind_param('si', $table, $id);
$stmt->execute();
$credentials = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// Same three-way classification (and the same 14-day warning window)
// credentials/list.php's admin view uses — one place defines "expiring
// soon" (include/CredentialHelpers.php), not a threshold re-guessed here.
foreach ($credentials as &$c) {
    $c['status_computed']    = credentialStatus($c['expiry_date']);
    $c['days_until_expiry']  = daysUntilExpiry($c['expiry_date']);
}
unset($c);

Api::success(['credentials' => $credentials]);
