<?php
declare(strict_types=1);

namespace App\Services;

use App\Core\Database;
use DateTimeImmutable;
use DateTimeZone;
use Throwable;

/** Uses the company time zone saved by Staff Portal admin. */
final class Timezone
{
    public static function apply(?string $tz): void
    {
        $iana = trim((string) $tz);
        if ($iana === '' || !in_array($iana, timezone_identifiers_list(), true)) {
            $iana = (string) config('app.timezone', 'America/New_York');
        }
        if (!in_array($iana, timezone_identifiers_list(), true)) {
            $iana = 'UTC';
        }
        date_default_timezone_set($iana);
        try {
            $offset = (new DateTimeImmutable('now', new DateTimeZone($iana)))->format('P');
            if (preg_match('/^[+-]\d{2}:\d{2}$/', $offset)) {
                Database::instance()->pdo()->exec("SET time_zone = '" . $offset . "'");
            }
        } catch (Throwable $e) {
            // PHP clock still applies if MySQL rejects the offset.
        }
    }
}
