<?php
/**
 * WinRacing timezone guard (V50.3a).
 *
 * Important: never call date_default_timezone_get() while php.ini may contain an
 * invalid timezone. PHP emits a warning before an application error handler can
 * safely normalise the value. Read php.ini with ini_get(), validate it locally,
 * then set a known-good timezone.
 */
if (!function_exists('wr_timezone_fallback_timestamp')) {
    function wr_timezone_fallback_timestamp()
    {
        try {
            return (new DateTimeImmutable('now', new DateTimeZone('UTC')))
                ->format('Y-m-d\\TH:i:s.u\\Z');
        } catch (Throwable $e) {
            return sprintf('unix:%.6f', microtime(true));
        }
    }
}

if (!function_exists('wr_timezone_is_valid')) {
    function wr_timezone_is_valid($timezone)
    {
        if (!is_string($timezone) || trim($timezone) === '') {
            return false;
        }

        try {
            new DateTimeZone(trim($timezone));
            return true;
        } catch (Throwable $e) {
            return false;
        }
    }
}

if (!function_exists('wr_timezone_guard_init')) {
    function wr_timezone_guard_init()
    {
        static $running = false;
        if ($running) {
            return false;
        }

        $running = true;
        $wanted = 'Asia/Hong_Kong';
        $configured = trim((string) ini_get('date.timezone'));
        $configuredValid = wr_timezone_is_valid($configured);
        $corrected = false;
        $reason = '';

        if ($configured === 'Asia/HongKong') {
            $effective = $wanted;
            $corrected = true;
            $reason = 'invalid_alias_corrected';
        } elseif ($configured === '') {
            $effective = $wanted;
            $corrected = true;
            $reason = 'empty_configuration_fallback';
        } elseif (!$configuredValid) {
            $effective = $wanted;
            $corrected = true;
            $reason = 'invalid_configuration_fallback';
        } else {
            $effective = $configured;
        }

        /* WinRacing production standard is always Hong Kong time. */
        if ($effective !== $wanted) {
            $effective = $wanted;
            $corrected = true;
            $reason = 'project_timezone_enforced';
        }

        $setOk = date_default_timezone_set($effective);
        if (!$setOk) {
            $effective = $wanted;
            $setOk = date_default_timezone_set($wanted);
            $corrected = true;
            $reason = 'set_failed_fallback';
        }

        $GLOBALS['WR_TIMEZONE_STATUS'] = array(
            'configured' => $configured,
            'configured_valid' => $configuredValid,
            'effective' => $effective,
            'valid' => (bool) $setOk,
            'corrected' => $corrected,
            'reason' => $reason
        );

        $running = false;
        return (bool) $setOk;
    }
}
