<?php

namespace App\Support;

use Illuminate\Support\Carbon;

/**
 * Expiry helpers for passport / permit / FOMEMA dates.
 *
 * Lives here rather than as a function declared inside a Blade view, because a
 * view-declared function fatals ("cannot redeclare") if the view renders twice
 * in one PHP process.
 */
class Expiry
{
    /** Days until $date (negative = already expired). Null when no date. */
    public static function days($date): ?int
    {
        if (! $date) {
            return null;
        }

        return (int) now()->startOfDay()->diffInDays(Carbon::parse($date)->startOfDay(), false);
    }

    /** Bootstrap contextual colour for an expiry date. */
    public static function color($date): string
    {
        $d = self::days($date);

        return match (true) {
            $d === null => 'secondary',
            $d < 0      => 'danger',
            $d <= 30    => 'danger',
            $d <= 60    => 'warning',
            default     => 'success',
        };
    }

    /** Short human label, e.g. "in 42d" / "Expired 7d". */
    public static function label($date): string
    {
        $d = self::days($date);

        return match (true) {
            $d === null => '—',
            $d < 0      => 'Expired '.abs($d).'d',
            default     => $d.'d',
        };
    }

    /** Rendered badge markup (safe: no user input interpolated). */
    public static function chip($date): string
    {
        if (! $date) {
            return '<span class="text-muted text-xs">—</span>';
        }

        return '<span class="expiry-chip bg-'.self::color($date).' text-white">'.e(self::label($date)).'</span>';
    }
}
