<?php
namespace EasyChat\Library\Messenger\Marketplace;








final class ProviderTimestamp {
    private const MIN_UNIX = 946684800;  
    private const MAX_UNIX = 4102444799;  

    public static function unix($value): int {
        if (is_int($value) || is_float($value) || (is_string($value) && preg_match('/^\d{1,19}$/', trim($value)))) {
            return self::numericUnix((string)$value);
        }
        if (!is_string($value)) {
            return 0;
        }

        $value = trim($value);
        if ($value === '') {
            return 0;
        }

         
         
        if (preg_match(
            '/^(\d{4}-\d{2}-\d{2})[Tt](\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?([Zz]|[+\-]\d{2}:\d{2})$/',
            $value,
            $parts
        ) === 1) {
            $fraction = isset($parts[3]) && $parts[3] !== ''
                ? '.' . substr(str_pad($parts[3], 6, '0'), 0, 6)
                : '.000000';
            $timezone = strtoupper($parts[4]) === 'Z' ? '+00:00' : $parts[4];
            $date = \DateTimeImmutable::createFromFormat(
                '!Y-m-d H:i:s.uP',
                $parts[1] . ' ' . $parts[2] . $fraction . $timezone
            );
            $errors = \DateTimeImmutable::getLastErrors();
            if ($date === false || (is_array($errors) && ((int)$errors['warning_count'] > 0 || (int)$errors['error_count'] > 0))) {
                return 0;
            }
            return self::withinBounds((int)$date->format('U'));
        }

         
        if (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $value) === 1) {
            $date = \DateTimeImmutable::createFromFormat('!Y-m-d H:i:s', $value, new \DateTimeZone('UTC'));
            $errors = \DateTimeImmutable::getLastErrors();
            if ($date === false || (is_array($errors) && ((int)$errors['warning_count'] > 0 || (int)$errors['error_count'] > 0))) {
                return 0;
            }
            return self::withinBounds((int)$date->format('U'));
        }

        return 0;
    }

    public static function sqlUtc($value): string {
        $unix = self::unix($value);
        return $unix > 0 ? gmdate('Y-m-d H:i:s', $unix) : '';
    }

    public static function isoUtc($value): string {
        $unix = self::unix($value);
        return $unix > 0 ? gmdate('Y-m-d\TH:i:s\Z', $unix) : '';
    }

    private static function numericUnix(string $value): int {
        $value = ltrim(trim($value), '0');
        if ($value === '') {
            return 0;
        }

        $length = strlen($value);
        $fraction_digits = $length <= 10 ? 0 : ($length <= 13 ? 3 : ($length <= 16 ? 6 : 9));
         
         
        $seconds = (int)($fraction_digits > 0 ? substr($value, 0, -$fraction_digits) : $value);
        return self::withinBounds($seconds);
    }

    private static function withinBounds(int $seconds): int {
        return $seconds >= self::MIN_UNIX && $seconds <= self::MAX_UNIX ? $seconds : 0;
    }
}
