<?php

declare(strict_types=1);

namespace BadamSoft\WooProductExporter\Helpers;

/**
 * Generates timezone select dropdown with proper selection support.
 * Based on WP All Import/Export implementation.
 */
class TimezoneSelect {

    /**
     * @var array<string, int>
     */
    private static $regions = [
        'Africa'     => \DateTimeZone::AFRICA,
        'America'    => \DateTimeZone::AMERICA,
        'Antarctica' => \DateTimeZone::ANTARCTICA,
        'Arctic'     => \DateTimeZone::ARCTIC,
        'Asia'       => \DateTimeZone::ASIA,
        'Atlantic'   => \DateTimeZone::ATLANTIC,
        'Australia'  => \DateTimeZone::AUSTRALIA,
        'Europe'     => \DateTimeZone::EUROPE,
        'Indian'     => \DateTimeZone::INDIAN,
        'Pacific'    => \DateTimeZone::PACIFIC,
    ];

    /**
     * Generate timezone select options HTML.
     *
     * @param string|false $selected_value Currently selected timezone identifier.
     * @return string HTML options for select element.
     */
    public static function render( $selected_value = false ): string {
        $timezones = [];

        foreach ( self::$regions as $region_name => $region_mask ) {
            $zones = \DateTimeZone::listIdentifiers( $region_mask );

            foreach ( $zones as $timezone ) {
                $tz_object = new \DateTimeZone( $timezone );
                $time      = new \DateTime( 'now', $tz_object );
                $offset    = $tz_object->getOffset( $time ) / 3600;

                // Format offset for display
                if ( $offset < 10 && $offset > 0 && is_int( $offset ) ) {
                    $offset_name = '0' . $offset;
                } elseif ( $offset < 0 && $offset > -10 && is_int( $offset ) ) {
                    $offset_name = str_replace( '- ', '-0', (string) $offset );
                } else {
                    $offset_name = str_replace( '-', '-', (string) $offset );
                }

                if ( $offset > 0 ) {
                    $offset_name = '+' . $offset_name;
                    $offset      = '+' . $offset;
                }

                $tz_abbrev = $time->format( 'T' );
                $city_name = substr( $timezone, strlen( $region_name ) + 1 );

                $timezones[ $region_name ][ $timezone ] = [
                    'offset'   => $offset,
                    'abbrev'   => $tz_abbrev,
                    'name'     => 'UTC ' . $offset_name . ' - ' . $city_name . ' (' . $tz_abbrev . ')',
                ];
            }
        }

        $result = '';

        foreach ( $timezones as $region => $list ) {
            $result .= '<optgroup label="' . esc_attr( $region ) . '">' . "\n";

            foreach ( $list as $timezone => $data ) {
                $selected = '';

                if ( $selected_value && $selected_value === $timezone ) {
                    $selected = ' selected="selected"';
                }

                $keywords = [
                    'UTC' . $data['offset'],
                    'UTC ' . $data['offset'],
                    $data['offset'],
                    str_replace( '+', '+ ', (string) $data['offset'] ),
                    $data['abbrev'],
                ];

                $keywords_str = implode( ',', $keywords );
                $display_name = str_replace( '_', ' ', $data['name'] );

                $result .= '<option value="' . esc_attr( $timezone ) . '"' . $selected . ' data-keywords="' . esc_attr( $keywords_str ) . '">' . esc_html( $display_name ) . '</option>' . "\n";
            }

            $result .= '</optgroup>' . "\n";
        }

        return $result;
    }
}
