<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Serenity\CoreBundle\Shared\Form\Type\Common;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\OptionsResolver\OptionsResolver;

class TimezoneCustomType extends AbstractType
{
    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'choices' => self::buildChoices(),
            'preferred_choices' => fn (\DateTimeZone $tz) => 'Europe/Paris' === $tz->getName(),
            'choice_value' => fn (?\DateTimeZone $timezone) => $timezone?->getName(), // convertit l'objet en string
            'label' => 'Fuseau horaire',
        ]);
    }

    public function getParent(): string
    {
        return ChoiceType::class;
    }

    /**
     * @return array<string, \DateTimeZone>
     */
    public static function buildChoices(): array
    {
        $now = new \DateTime('now');
        $timezones = \DateTimeZone::listIdentifiers();
        $offsets = [];

        foreach ($timezones as $tzId) {
            $tz = new \DateTimeZone($tzId);
            $offset = $tz->getOffset($now);

            $hours = (int) floor($offset / 3600);
            $minutes = (int) abs(($offset % 3600) / 60);
            $sign = $offset >= 0 ? '+' : '-';
            $formattedOffset = \sprintf('(GMT %s%02d:%02d)', $sign, abs($hours), $minutes);

            $city = str_replace('_', ' ', basename($tzId));
            $label = \sprintf('%s %s', $formattedOffset, $city);

            $offsets[] = [
                'label' => $label,
                'id' => $tzId,
                'offset' => $offset,
            ];
        }

        usort($offsets, fn ($a, $b) => $a['offset'] <=> $b['offset']);

        $choices = [];
        foreach ($offsets as $entry) {
            $choices[$entry['label']] = new \DateTimeZone($entry['id']); // retourne directement l'objet
        }

        return $choices;
    }
}
