<?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\CustomFieldsBundle\Form\Type;

use Chill\CustomFieldsBundle\Service\CustomFieldProvider;
use Doctrine\Persistence\ObjectManager;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class CustomFieldType extends AbstractType
{
    /**
     * @var CustomFieldCompiler
     */
    private $customFieldCompiler;

    public function __construct(private readonly ObjectManager $om, CustomFieldProvider $compiler)
    {
        $this->customFieldCompiler = $compiler;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        foreach ($options['group']->getActiveCustomFields() as $cf) {
            $this->customFieldCompiler
                ->getCustomFieldByType($cf->getType())
                ->buildForm($builder, $cf);
            $builder->get($cf->getSlug())->setRequired($cf->isRequired());
        }
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver
            ->setRequired(['group'])
            ->addAllowedTypes('group', [\Chill\CustomFieldsBundle\Entity\CustomFieldsGroup::class]);
    }
}
