<?php

namespace App\Support\Locale;

use DateTime;
use DateTimeZone;

/**
 * Timezone Select options for the Master Control "Locale" tab, built from
 * PHP's own IANA tzdata (DateTimeZone::listIdentifiers()) rather than a
 * hand-seeded table: that data is already exactly as current and correct as
 * the PHP runtime it ships with, and copying it into a second, tenant-owned
 * table would just be a second place for it to go stale. This is the
 * industry-standard source for the same reason Laravel, MySQL and every
 * major OS use it rather than inventing their own.
 */
final class TimezoneOptions
{
    /**
     * Grouped by continent/region, exactly as a Select's option groups
     * expect: `['Asia' => ['Asia/Colombo' => 'Colombo (UTC+05:30)', ...], ...]`.
     *
     * @return array<string, array<string, string>>
     */
    public static function grouped(): array
    {
        $groups = [];

        foreach (DateTimeZone::listIdentifiers(DateTimeZone::ALL) as $id) {
            [$region, $place] = str_contains($id, '/')
                ? explode('/', $id, 2)
                : ['Other', $id];

            $groups[$region][$id] = str_replace('_', ' ', str_replace('/', ' — ', $place)).' ('.self::offsetLabel($id).')';
        }

        ksort($groups);

        foreach ($groups as $region => $zones) {
            asort($zones);
            $groups[$region] = $zones;
        }

        return $groups;
    }

    /** e.g. "UTC+05:30" — the timezone's CURRENT offset (DST-aware). */
    private static function offsetLabel(string $id): string
    {
        $seconds = (new DateTimeZone($id))->getOffset(new DateTime('now', new DateTimeZone('UTC')));
        $sign = $seconds < 0 ? '-' : '+';
        $minutes = (int) round(abs($seconds) / 60);

        return sprintf('UTC%s%02d:%02d', $sign, intdiv($minutes, 60), $minutes % 60);
    }
}
