<?php

use CodeIgniter\I18n\Time;

if (! function_exists('user_timezone')) {
    function user_timezone(): string
    {
        return service('timeService')->userTimezone();
    }
}

if (! function_exists('server_timezone')) {
    function server_timezone(): string
    {
        return service('timeService')->serverTimezone();
    }
}

if (! function_exists('utc_now')) {
    function utc_now(string $format = 'Y-m-d H:i:s'): string
    {
        return service('timeService')->nowUTC()->format($format);
    }
}

if (! function_exists('local_now')) {
    function local_now(string $format = 'Y-m-d H:i:s', ?string $tz = null): string
    {
        return service('timeService')->nowLocal($tz)->format($format);
    }
}

if (! function_exists('to_utc')) {
    /**
     * Convert a time to UTC with optional source TZ and format.
     *
     * @param string|Time|\DateTimeInterface|null $value
     */
    function to_utc($value, ?string $fromTz = null, string $format = 'Y-m-d H:i:s'): ?string
    {
        return service('timeService')->toUTC($value, $fromTz, $format);
    }
}

if (! function_exists('to_local')) {
    /**
     * Convert a time to user-local with optional source TZ and format.
     *
     * @param string|Time|\DateTimeInterface|null $value
     */
    function to_local($value, ?string $sourceTz = null, ?string $targetTz = null, string $format = 'Y-m-d H:i:s'): ?string
    {
        return service('timeService')->toLocal($value, $sourceTz, $targetTz, $format);
    }
}

if (! function_exists('local_date')) {
    /**
     * Format to user-local date (Y-m-d by default). Assumes input is UTC unless source TZ provided.
     */
    function local_date($value, string $format = 'Y-m-d', ?string $sourceTz = null): string
    {
        return service('timeService')->formatLocal($value, $format, $sourceTz);
    }
}

if (! function_exists('local_datetime')) {
    /**
     * Format to user-local datetime (Y-m-d H:i by default). Assumes input is UTC unless source TZ provided.
     */
    function local_datetime($value, string $format = 'Y-m-d H:i', ?string $sourceTz = null): string
    {
        return service('timeService')->formatLocal($value, $format, $sourceTz);
    }
}
