<?php
// =============================================================
//  include/CredentialHelpers.php
//
//  Pure logic for credential expiry status — shared by
//  app/manage_credentials.php, the nurse/student self-service views, and
//  scripts/check_credential_expiry.php, so "what counts as expiring
//  soon" is defined in exactly one place.
// =============================================================

if (!function_exists('credentialStatus')) {
    /**
     * @return string 'expired' | 'expiring_soon' | 'valid'
     */
    function credentialStatus(string $expiryDate, int $warningDays = 14): string
    {
        $today  = new DateTimeImmutable('today');
        $expiry = parseDateAtMidnight($expiryDate);
        if (!$expiry) return 'valid'; // malformed date — fail toward not alarming, caller should validate on entry

        if ($expiry < $today) return 'expired';

        $warningCutoff = $today->modify("+{$warningDays} days");
        if ($expiry <= $warningCutoff) return 'expiring_soon';

        return 'valid';
    }

    /** Days remaining until expiry — negative if already expired. */
    function daysUntilExpiry(string $expiryDate): int
    {
        $today  = new DateTimeImmutable('today');
        $expiry = parseDateAtMidnight($expiryDate);
        if (!$expiry) return 0;
        return (int)$today->diff($expiry)->format('%r%a');
    }

    /**
     * DateTimeImmutable::createFromFormat('Y-m-d', ...) inherits the CURRENT
     * time-of-day for the unspecified time portion, not midnight — comparing
     * that against a real midnight DateTimeImmutable ('today') is off by a
     * fractional day right at boundaries. Zero the time explicitly instead.
     */
    function parseDateAtMidnight(string $date): ?DateTimeImmutable
    {
        $parsed = DateTimeImmutable::createFromFormat('Y-m-d', $date);
        return $parsed ? $parsed->setTime(0, 0, 0) : null;
    }

    function credentialStatusBadge(string $status): array
    {
        return match ($status) {
            'expired'       => ['label' => 'Expired',       'class' => 'bg-danger'],
            'expiring_soon' => ['label' => 'Expiring Soon',  'class' => 'bg-warning text-dark'],
            default         => ['label' => 'Valid',          'class' => 'bg-success'],
        };
    }

    /**
     * Strict Y-m-d validation via round-trip, not just regex — DateTime::createFromFormat
     * silently overflows out-of-range values (e.g. "2026-13-45" rolls into some other real
     * date) rather than rejecting them, so a regex match alone isn't enough to guarantee
     * the string is actually a valid calendar date.
     */
    function isValidDate(string $value): bool
    {
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $value)) return false;
        $d = DateTime::createFromFormat('Y-m-d', $value);
        return $d !== false && $d->format('Y-m-d') === $value;
    }
}
