<?php

use Core\App\Models\Settings;

if (!function_exists('app_timezone_name')) {
    function app_timezone_name(): string
    {
        static $resolved = null;
        if (is_string($resolved) && $resolved !== '') {
            return $resolved;
        }

        $candidates = [];

        try {
            $settings = new Settings();
            $named = trim((string)$settings->get('app_timezone', ''));
            if ($named !== '') {
                $candidates[] = $named;
            }

            $country = strtolower(trim((string)$settings->get('country', '')));
            if (in_array($country, ['algeria', 'algérie', 'algerie', 'dz'], true)) {
                $candidates[] = 'Africa/Algiers';
            }

            $offset = trim((string)$settings->get('timezone_offset', ''));
            if ($offset !== '' && is_numeric($offset)) {
                $hours = (int)$offset;
                if ($hours === 0) {
                    $candidates[] = 'UTC';
                } elseif ($hours > 0) {
                    $candidates[] = 'Etc/GMT-' . $hours;
                } else {
                    $candidates[] = 'Etc/GMT+' . abs($hours);
                }
            }
        } catch (\Throwable $e) {
            // Ignore and use fallback.
        }

        $candidates[] = 'Africa/Algiers';
        $candidates[] = 'UTC';

        foreach ($candidates as $candidate) {
            try {
                new DateTimeZone($candidate);
                $resolved = $candidate;
                return $resolved;
            } catch (\Throwable $e) {
                continue;
            }
        }

        $resolved = 'UTC';
        return $resolved;
    }
}

if (!function_exists('app_utc_timezone')) {
    function app_utc_timezone(): DateTimeZone
    {
        static $tz = null;
        if (!$tz instanceof DateTimeZone) {
            $tz = new DateTimeZone('UTC');
        }
        return $tz;
    }
}

if (!function_exists('app_local_timezone')) {
    function app_local_timezone(): DateTimeZone
    {
        static $tz = null;
        if (!$tz instanceof DateTimeZone) {
            $tz = new DateTimeZone(app_timezone_name());
        }
        return $tz;
    }
}

if (!function_exists('app_local_to_utc')) {
    function app_local_to_utc(?string $value): ?string
    {
        $value = trim((string)$value);
        if ($value === '') {
            return null;
        }

        try {
            $dt = new DateTime($value, app_local_timezone());
            $dt->setTimezone(app_utc_timezone());
            return $dt->format('Y-m-d H:i:s');
        } catch (\Throwable $e) {
            return null;
        }
    }
}

if (!function_exists('app_utc_to_local')) {
    function app_utc_to_local(?string $value): ?DateTimeImmutable
    {
        $value = trim((string)$value);
        if ($value === '') {
            return null;
        }

        try {
            $dt = new DateTimeImmutable($value, app_utc_timezone());
            return $dt->setTimezone(app_local_timezone());
        } catch (\Throwable $e) {
            return null;
        }
    }
}

if (!function_exists('app_format_datetime')) {
    function app_format_datetime(?string $value, string $format = 'd M Y H:i', string $fallback = ''): string
    {
        $dt = app_utc_to_local($value);
        if (!$dt instanceof DateTimeImmutable) {
            return $fallback;
        }

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

if (!function_exists('app_format_datetime_input')) {
    function app_format_datetime_input(?string $value): string
    {
        return app_format_datetime($value, 'Y-m-d\\TH:i', '');
    }
}
