<?php
/**
 * Copyright since 2025 InPost S.A.
 *
 * For the full license information, please view the LICENSE file bundled with the module.
 *
 * @author InPost S.A.
 * @copyright since 2025 InPost S.A.
 * @license MIT
 */

declare(strict_types=1);

namespace InPost\International\Form\TypeExtension;

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;

if (!defined('_PS_VERSION_')) {
    exit;
}

/**
 * Backports some of the options introduced in Symfony 4.x.
 *
 * @internal
 *
 * @deprecated to be removed when we drop support for PS 1.7
 */
final class CompatibilityTypeExtension extends AbstractTypeExtension
{
    /**
     * @var bool
     */
    private $addBlockPrefix = false;

    public static function getExtendedTypes(): iterable
    {
        return [FormType::class];
    }

    public function getExtendedType(): string
    {
        return FormType::class;
    }

    public function buildView(FormView $view, FormInterface $form, array $options): void
    {
        if (!isset($view->vars['help_html'])) {
            $view->vars['help_html'] = $options['help_html'];
            $view->vars['help_attr'] = $options['help_attr'];
        }

        if (!$this->addBlockPrefix || null === $options['block_prefix']) {
            return;
        }

        // add before the unique block prefix
        array_splice($view->vars['block_prefixes'], -1, 0, [$options['block_prefix']]);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        if (!$resolver->isDefined('block_prefix')) {
            $this->addBlockPrefix = true;

            $resolver
                ->setDefault('block_prefix', null)
                ->setAllowedTypes('block_prefix', ['null', 'string']);
        }

        if (!$resolver->isDefined('help_html')) {
            $resolver
                ->setDefaults([
                    'help_attr' => [],
                    'help_html' => false,
                ])
                ->setAllowedTypes('help_attr', 'array')
                ->setAllowedTypes('help_html', 'bool');
        }
    }
}
