<?php

/**
 * Translate the first argument and optionally run sprintf placeholders.
 */
function t()
{
    $arguments = func_get_args();
    $arguments[0] = \MintyPHP\I18n::translate($arguments[0]);
    if (count($arguments) === 1) {
        return $arguments[0];
    }
    return call_user_func_array('sprintf', $arguments);
}

/**
 * Format a UTC timestamp for display in the configured app timezone.
 */
function dt($value, ?string $format = null)
{
    $displayTz = null;
    try {
        $displayTz = new \DateTimeZone(defined('APP_TIMEZONE') ? APP_TIMEZONE : date_default_timezone_get());
    } catch (\Exception $e) {
        $displayTz = new \DateTimeZone(date_default_timezone_get());
    }

    if ($value instanceof \DateTimeInterface) {
        $date = (new \DateTimeImmutable('@' . $value->getTimestamp()))->setTimezone($displayTz);
    } elseif (is_string($value) && $value !== '') {
        try {
            // Treat DB timestamps as UTC and convert for display
            $date = new \DateTimeImmutable($value, new \DateTimeZone('UTC'));
            $date = $date->setTimezone($displayTz);
        } catch (\Exception $e) {
            return $value;
        }
    } else {
        return '';
    }

    if ($format === null) {
        $locale = \MintyPHP\I18n::$locale ?? '';
        $format = (strpos((string) $locale, 'de') === 0) ? 'd.m.Y H:i' : 'Y-m-d H:i';
    }

    return $date->format($format);
}
