<?php

declare(strict_types=1);

use FatBottom\Core\Security;

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

function money(int|string|null $cents): string
{
    return '$' . number_format(((int) $cents) / 100, 2);
}

function csrf_field(): string
{
    return '<input type="hidden" name="_token" value="' . e(Security::csrfToken()) . '">';
}

function active_path(string $path): string
{
    $current = \FatBottom\Core\Http::path();
    return $current === $path ? 'is-active' : '';
}

function url(string $path = '/'): string
{
    return \FatBottom\Core\Http::url($path);
}

function asset(string $path): string
{
    return \FatBottom\Core\Http::url('/' . ltrim($path, '/'));
}

function selected(mixed $value, mixed $expected): string
{
    return (string) $value === (string) $expected ? 'selected' : '';
}

function checked(mixed $value): string
{
    return (bool) $value ? 'checked' : '';
}

function order_status_label(string $status): string
{
    return [
        'pending' => 'Awaiting acceptance',
        'paid' => 'Awaiting acceptance',
        'accepted' => 'Accepted',
        'declined' => 'Declined',
        'processing' => 'Processing / Active',
        'preparing' => 'Processing / Active',
        'ready' => 'Ready for pickup',
        'completed' => 'Complete',
        'cancelled' => 'Declined',
    ][$status] ?? ucwords(str_replace('_', ' ', $status));
}

function store_datetime(?string $value, string $format = 'M j, Y g:i A'): string
{
    if ($value === null || $value === '') {
        return '';
    }

    $date = new DateTimeImmutable($value, new DateTimeZone('UTC'));
    return $date->setTimezone(new DateTimeZone(date_default_timezone_get()))->format($format);
}

function utc_datetime(?string $value): ?string
{
    if ($value === null || trim($value) === '') {
        return null;
    }

    $date = new DateTimeImmutable($value, new DateTimeZone(date_default_timezone_get()));
    return $date->setTimezone(new DateTimeZone('UTC'))->format('Y-m-d H:i:s');
}
