<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\PersonBundle\Form\Type;

use Chill\MainBundle\Form\Type\ChillPhoneNumberType;
use Chill\MainBundle\Phonenumber\PhonenumberHelper;
use Chill\PersonBundle\Entity\PersonPhone;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;

class PersonPhoneType extends AbstractType
{
    public function __construct(private readonly PhonenumberHelper $phonenumberHelper, private readonly EntityManagerInterface $em) {}

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('phonenumber', ChillPhoneNumberType::class, [
            'label' => 'Other phonenumber',
            'required' => true,
        ]);

        $builder->add('description', TextType::class, [
            'required' => false,
        ]);

        $builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
            if (null === $event->getData()) {
                return;
            }

            $oldPersonPhone = $this->em->getUnitOfWork()
                ->getOriginalEntityData($event->getData());

            if ($oldPersonPhone['phonenumber'] ?? null !== $event->getForm()->getData()->getPhonenumber()) {
                $type = $this->phonenumberHelper->getType($event->getData()->getPhonenumber());
                $event->getData()->setType($type);
            }
        });
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver
            ->setDefaults([
                'data_class' => PersonPhone::class,
                'validation_groups' => ['general', 'creation'],
            ]);
    }
}
