<?php
/**
 * Small view/formatting helpers shared by every template. Kept as plain
 * functions (not a class) since they are called constantly inside .php
 * view templates and a static-method prefix would only add noise there.
 */

use App\Core\Request;

function e(?string $value): string
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function url(string $path = ''): string
{
    return Request::basePath() . '/' . ltrim($path, '/');
}

function asset(string $path): string
{
    return Request::basePath() . '/assets/' . ltrim($path, '/');
}

function fmt_dt(?string $dt): string
{
    if (!$dt) return '—';
    return date('d M Y, H:i', strtotime($dt));
}

function fmt_d(?string $dt): string
{
    if (!$dt) return '—';
    return date('d M Y', strtotime($dt));
}

/** Human "3h 12m" style duration from a total minutes figure. */
function fmt_minutes(?int $minutes): string
{
    if ($minutes === null) return '—';
    $minutes = (int)$minutes;
    $days = intdiv($minutes, 1440);
    $minutes %= 1440;
    $hours = intdiv($minutes, 60);
    $mins = $minutes % 60;
    $parts = [];
    if ($days > 0) $parts[] = $days . 'd';
    if ($hours > 0) $parts[] = $hours . 'h';
    if ($mins > 0 || empty($parts)) $parts[] = $mins . 'm';
    return implode(' ', $parts);
}

/** Countdown / overdue text against a due datetime, e.g. "1h 12m left" or "6h 18m over". */
function fmt_remaining(?string $dueAt, bool $breached): string
{
    if (!$dueAt) return '—';
    $diffMinutes = (int)round((strtotime($dueAt) - time()) / 60);
    if ($diffMinutes >= 0) {
        return fmt_minutes($diffMinutes) . ' left';
    }
    return fmt_minutes(abs($diffMinutes)) . ' over';
}

function status_label(string $status): string
{
    return ucwords(strtolower(str_replace('_', ' ', $status)));
}

function status_badge_class(string $status): string
{
    return match ($status) {
        'NEW' => 'badge badge-new',
        'ASSIGNED' => 'badge badge-assigned',
        'IN_PROGRESS' => 'badge badge-progress',
        'PENDING_CUSTOMER', 'PENDING_THIRD_PARTY' => 'badge badge-pending',
        'ESCALATED' => 'badge badge-escalated',
        'RESOLVED' => 'badge badge-resolved',
        'CLOSED' => 'badge badge-closed',
        'REOPENED' => 'badge badge-reopened',
        'REJECTED' => 'badge badge-rejected',
        default => 'badge',
    };
}

function priority_badge(array $priority): string
{
    $color = e($priority['color'] ?? '#64748b');
    $code = e($priority['code'] ?? '');
    return '<span class="badge badge-priority" style="background:' . $color . '22;color:' . $color . ';border-color:' . $color . '55">' . $code . '</span>';
}

function csrf_field(): string
{
    return \App\Core\Csrf::field();
}

function flash_get(string $key): ?string
{
    return \App\Core\Session::flash($key);
}

function old(string $key, $default = '')
{
    return $_SESSION['_old'][$key] ?? $default;
}
