<?php

declare(strict_types=1);

namespace App\Form;

use App\Entity\Classe;
use App\Entity\Ecole;
use App\Entity\Inscription;
use App\Entity\Niveau;
use App\Entity\Section;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

final class InscriptionAffectationType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        /** @var Ecole $ecole */
        $ecole = $options['ecole'];
        $filter = fn (EntityRepository $er) => $er->createQueryBuilder('e')
            ->andWhere('e.ecole = :ecole')
            ->setParameter('ecole', $ecole)
            ->orderBy('e.nom', 'ASC');

        $builder
            ->add('sectionFinale', EntityType::class, ['class' => Section::class, 'choice_label' => 'nom', 'label' => 'Section finale', 'required' => false, 'placeholder' => 'Choisir', 'query_builder' => $filter])
            ->add('niveauFinal', EntityType::class, ['class' => Niveau::class, 'choice_label' => 'nom', 'label' => 'Niveau final', 'required' => false, 'placeholder' => 'Choisir', 'query_builder' => $filter])
            ->add('classeFinale', EntityType::class, ['class' => Classe::class, 'choice_label' => 'nom', 'label' => 'Classe finale', 'required' => false, 'placeholder' => 'Choisir', 'query_builder' => $filter])
            ->add('parcours', CollectionType::class, [
                'entry_type' => InscriptionParcoursAffectationType::class,
                'entry_options' => ['ecole' => $ecole],
                'allow_add' => true,
                'allow_delete' => true,
                'by_reference' => false,
                'delete_empty' => true,
                'prototype' => true,
                'label' => false,
            ])
            ->add('observationAdmin', TextareaType::class, ['label' => 'Observation administrative', 'required' => false, 'attr' => ['rows' => 4]]);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults(['data_class' => Inscription::class, 'ecole' => null]);
        $resolver->setRequired('ecole');
        $resolver->setAllowedTypes('ecole', [Ecole::class]);
    }
}
