<?php

declare(strict_types=1);

namespace App\Services\Install;

use IntlTimeZone;

final class InstallWizardTimezoneOptions
{
    /**
     * @return list<array{value: string, label: string}>
     */
    public static function sortedForSelect(string $locale = 'zh_CN'): array
    {
        $rows = [];
        foreach (timezone_identifiers_list() as $id) {
            $rows[] = [
                'value' => $id,
                'label' => self::labelForIdentifier($id, $locale),
            ];
        }

        usort($rows, static function (array $a, array $b): int {
            $byLabel = strcmp($a['label'], $b['label']);
            if ($byLabel !== 0) {
                return $byLabel;
            }

            return strcmp($a['value'], $b['value']);
        });

        return $rows;
    }

    public static function labelForIdentifier(string $timezoneId, string $locale = 'zh_CN'): string
    {
        if ($timezoneId === '') {
            return $timezoneId;
        }

        if (! extension_loaded('intl')) {
            return $timezoneId;
        }

        $intl = IntlTimeZone::createTimeZone($timezoneId);
        $display = $intl->getDisplayName(false, IntlTimeZone::DISPLAY_LONG_GENERIC, $locale);
        if ($display === false || $display === '') {
            return $timezoneId;
        }

        if ($display === $timezoneId) {
            return $timezoneId;
        }

        return sprintf('%s（%s）', $display, $timezoneId);
    }
}
