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

use Chill\BudgetBundle\Entity\Resource;
use Chill\BudgetBundle\Entity\ResourceKind;
use Chill\BudgetBundle\Repository\ResourceKindRepository;
use Chill\MainBundle\Form\Type\ChillDateType;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Contracts\Translation\TranslatorInterface;

class ResourceType extends AbstractType
{
    public function __construct(protected TranslatableStringHelperInterface $translatableStringHelper, private readonly ResourceKindRepository $repository, private readonly TranslatorInterface $translator) {}

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('resource', EntityType::class, [
                'class' => ResourceKind::class,
                'choices' => $this->repository->findAllActive(),
                'label' => 'Resource type',
                'required' => true,
                'placeholder' => $this->translator->trans('admin.form.Choose the type of resource'),
                'choice_label' => fn (ResourceKind $resource) => $this->translatableStringHelper->localize($resource->getName()),
                'attr' => ['class' => 'select2'],
            ])
            ->add('amount', MoneyType::class)
            ->add('comment', TextareaType::class, [
                'required' => false,
            ]);

        if ($options['show_start_date']) {
            $builder->add('startDate', ChillDateType::class, [
                'label' => 'Start of validity period',
            ]);
        }

        if ($options['show_end_date']) {
            $builder->add('endDate', ChillDateType::class, [
                'required' => false,
                'label' => 'End of validity period',
            ]);
        }
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Resource::class,
            'show_start_date' => true,
            'show_end_date' => true,
        ]);

        $resolver
            ->setAllowedTypes('show_start_date', 'boolean')
            ->setAllowedTypes('show_end_date', 'boolean');
    }

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