<?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\DataTransformer\ObjectToIdTransformer;
use Chill\MainBundle\Form\Type\Select2ChoiceType;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Chill\PersonBundle\Entity\MaritalStatus;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * A type to select the marital status.
 */
class Select2MaritalStatusType extends AbstractType
{
    public function __construct(private readonly TranslatableStringHelper $translatableStringHelper, private readonly EntityManagerInterface $em) {}

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $transformer = new ObjectToIdTransformer($this->em, MaritalStatus::class);
        $builder->addModelTransformer($transformer);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $maritalStatuses = $this->em->getRepository(MaritalStatus::class)->findAll();
        $choices = [];

        foreach ($maritalStatuses as $ms) {
            $choices[$ms->getId()] = $this->translatableStringHelper->localize($ms->getName());
        }

        asort($choices, \SORT_STRING | \SORT_FLAG_CASE);

        $resolver->setDefaults([
            'class' => MaritalStatus::class,
            'choices' => array_combine(array_values($choices), array_keys($choices)),
        ]);
    }

    public function getBlockPrefix()
    {
        return 'select2_chill_marital_status';
    }

    public function getParent()
    {
        return Select2ChoiceType::class;
    }
}
