<?php

namespace App\Form;

use App\Entity\Action;
use App\Entity\Ministry;
use App\Entity\Commune;
use App\Entity\Programm;
use App\Repository\MinistryRepository;
use App\Repository\CommuneRepository;
use App\Repository\ProgrammRepository;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Validator\Constraints\File;

class FormatType extends AbstractType
{
    private $year;
    private $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $this->year = $options['sessionYear']; 
       $builder->add('attachment', FileType::class, [
                'label' => false,
                'attr' => [
                    'class' => 'form-control-file',
                    'accept' => '.xls,.xlsx'
                ],
                'constraints' => [
                    new File([
                        'maxSize' => '2048k',
                        'mimeTypes' => [
                            'application/vnd.ms-excel', // .xls
                            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
                            'application/excel', // Alternative pour .xls
                            'application/x-excel', // Alternative pour .xls
                        ],
                        'mimeTypesMessage' => 'Veuillez choisir un fichier Excel (.xls ou .xlsx)',
                        'maxSizeMessage' => 'Le fichier ne peut pas dépasser {{ limit }} {{ suffix }}',
                    ])
                ],
            ])

        ->add('start', ChoiceType::class, [
            'choices' => [
                    1 => 1, 
                    2 => 2,
                    3 => 3,
                    4 => 4,
                    5 => 5,
                    6 => 6,
                    7 => 7,
                    8 => 8,
                    9 => 9,
                    10 => 10,
                    11 => 11,
                    12 => 12,
                    13 => 13,
                    14 => 14,
                    15 => 15,
                    16 => 16,
                    17 => 17,
                    18 => 18,
                    19 => 19,
                    20 => 20,
            ],
            'placeholder' => "Sélectionner la ligne où commence les données",
            'label' => false,
            'data' => '13'
        ])

        ->add('code', ChoiceType::class, [
            'choices' => [
                'A' => 'A',
                'B' => 'B',
                'C' => 'C',
                'D' => 'D',
                'E' => 'E',
                'F' => 'F',
                'G' => 'G',
                'H' => 'H',
                'I' => 'I',
                'J' => 'J',
                'K' => 'K',
                'L' => 'L',
                'M' => 'M',
                'N' => 'N',
                'O' => 'O',
                'P' => 'P',
                'Q' => 'Q',
                'R' => 'R',
                'S' => 'S',
                'T' => 'T',
                'U' => 'U',
                'V' => 'V',
                'W' => 'W',
                'X' => 'X',
                'Y' => 'Y',
                'Z' => 'Z',
            ],
            'placeholder' => "Sélectionner la colonne des codes",
            'label' => false,
            'data' => 'A'
        ])

        ->add('libelle', ChoiceType::class, [
            'choices' => [
                'A' => 'A',
                'B' => 'B',
                'C' => 'C',
                'D' => 'D',
                'E' => 'E',
                'F' => 'F',
                'G' => 'G',
                'H' => 'H',
                'I' => 'I',
                'J' => 'J',
                'K' => 'K',
                'L' => 'L',
                'M' => 'M',
                'N' => 'N',
                'O' => 'O',
                'P' => 'P',
                'Q' => 'Q',
                'R' => 'R',
                'S' => 'S',
                'T' => 'T',
                'U' => 'U',
                'V' => 'V',
                'W' => 'W',
                'X' => 'X',
                'Y' => 'Y',
                'Z' => 'Z',
            ],
            'placeholder' => "Sélectionner la colonne des libellés",
            'label' => false,
            'data' => 'B'
        ])

        ->add('direction', ChoiceType::class, [
            'choices' => [
                'A' => 'A',
                'B' => 'B',
                'C' => 'C',
                'D' => 'D',
                'E' => 'E',
                'F' => 'F',
                'G' => 'G',
                'H' => 'H',
                'I' => 'I',
                'J' => 'J',
                'K' => 'K',
                'L' => 'L',
                'M' => 'M',
                'N' => 'N',
                'O' => 'O',
                'P' => 'P',
                'Q' => 'Q',
                'R' => 'R',
                'S' => 'S',
                'T' => 'T',
                'U' => 'U',
                'V' => 'V',
                'W' => 'W',
                'X' => 'X',
                'Y' => 'Y',
                'Z' => 'Z',
            ],
            'placeholder' => "Sélectionner la colonne des directions",
            'label' => false,
            'data' => 'N'
        ])

        ->add('cout', ChoiceType::class, [
            'choices' => [
                'A' => 'A',
                'B' => 'B',
                'C' => 'C',
                'D' => 'D',
                'E' => 'E',
                'F' => 'F',
                'G' => 'G',
                'H' => 'H',
                'I' => 'I',
                'J' => 'J',
                'K' => 'K',
                'L' => 'L',
                'M' => 'M',
                'N' => 'N',
                'O' => 'O',
                'P' => 'P',
                'Q' => 'Q',
                'R' => 'R',
                'S' => 'S',
                'T' => 'T',
                'U' => 'U',
                'V' => 'V',
                'W' => 'W',
                'X' => 'X',
                'Y' => 'Y',
                'Z' => 'Z',
            ],
            'placeholder' => "Sélectionner la colonne des coûts",
            'label' => false,
            'data' => 'F'
        ])
        ;

        if($options['sessionMinistry']==null && $options['sessionCommune']==null){
            $builder->add('type', ChoiceType::class, [
                'choices' => [
                    'Ministère' => 'ministere',
                    'Commune' => 'commune',
                ],
                'placeholder' => 'Sélectionnez une structure',
                'mapped' => false,
                'required' => true,
                'label' => false,
                'data' => $options['defaultType'],
                'disabled' => $options['defaultType'] ? true : false,
            ]);
            

            $builder->get('type')->addEventListener(
                FormEvents::POST_SUBMIT,
                function (FormEvent $event) use($options) {
                    $form = $event->getForm();
                    $this->addEntiteField($form->getParent(), $form->getData(),$options);
                }
            );
        }

        $builder->addEventListener(
            FormEvents::PRE_SUBMIT,
            function (FormEvent $event) use ($options) {
                $data = $event->getData();
                $form = $event->getForm();
                if($options['sessionMinistry']==null && $options['sessionCommune']==null){
                    if (isset($data['type']) && $data['type']!=""  && isset($data['entite']) && $data['entite']!="") {
                        if ($data['type'] === 'ministere') {
                            $ministry = $this->entityManager->getRepository(Ministry::class)->find($data['entite']);
                            $this->addProgrammField($form, $ministry, null);
                        }elseif ($data['type'] === 'commune') {
                            $commune = $this->entityManager->getRepository(Commune::class)->find($data['entite']);
                            $this->addProgrammField($form, null, $commune);
                        }
                    }
                }
            }
        );

        $builder->addEventListener(
            FormEvents::POST_SET_DATA,
            function (FormEvent $event) use($options) {
                $form = $event->getForm();
                $data = $event->getData();

                $programm = $data ? $data->getProgramm() : null;
                if ($programm) {
                    $ministry = $programm->getMinistry();
                    $commune = $programm->getCommune();
                    $this->addProgrammField($form, $ministry,$commune);

                    if($options['sessionMinistry']==null && $options['sessionCommune']==null){
                        $type = $form->has('type') ? $form->get('type')->getData() : null;
                        $this->addEntiteField($form, $type, $options);
                    }
                    $this->addProgrammField($form, $ministry,$commune);
                }else{
                    if($options['sessionMinistry']==null && $options['sessionCommune']==null){
                        $this->addEntiteField($form, null, $options);
                    }
                    if($options['sessionMinistry']){
                        $this->addProgrammField($form, $options['sessionMinistry'],null);
                    }else if($options['sessionCommune']){
                        $this->addProgrammField($form, null, $options['sessionCommune']);
                    }else{
                        $this->addProgrammField($form, null, null);
                    }
                }
                
            }
        );
    }
    
    private function addProgrammField(FormInterface $form, ?Ministry $ministry, ?Commune $commune)
    { 
        $form->add('programm', EntityType::class, [
            'label' => false,
            'class' => Programm::class,
            'choice_label' => 'name',
            'placeholder' => ($ministry || $commune) ? 'basics.programm.placeholder' : 'Sélectionnez d\'abord un ministère ou une commune',
            'query_builder' => function (ProgrammRepository $repository) use($ministry, $commune) {
                return $repository->findProgrammByYear('%'.$this->year.'%', $ministry, $commune);
            },
        ]);
    }

    private function addEntiteField(FormInterface $form,  $type, $options)
    {
        if($type){
            if($type=='commune'){
                $form->add('entite', EntityType::class, [
                    'class' => Commune::class,
                    'placeholder' => 'Sélectionnez une commune',
                    'required' => true,
                    'mapped' => false,
                    'choice_label' => 'name', 
                    'data' => $options['defaultEntite'],
                    'disabled' => $options['defaultEntite'] ? true : false,
                    'label' => false,
                    'query_builder' => function (CommuneRepository $er) {
                        return $er->createQueryBuilder('m')
                                ->orderBy('m.name', 'ASC'); // Tri par nom en ordre croissant
                    },
                    
                ]);
            }else if($type=='ministere'){
                $form->add('entite', EntityType::class, [
                    'class' => Ministry::class, // Classe par défaut, ajustée dynamiquement
                    'placeholder' => 'Sélectionnez un ministère',
                    'required' => true,
                    'mapped' => false,
                    'choice_label' => 'name', 
                    'data' => $options['defaultEntite'],
                    'disabled' => $options['defaultEntite'] ? true : false,
                    'label' => false,
                    'query_builder' => function(MinistryRepository $repository)  {
                        return $repository->findMinistryByYear(
                            '%'.$this->year.'%', null
                        );
                    },
                ]);
            }
        }else{
            $form->add('entite', EntityType::class, [
                'label' => false,
                'class' => Ministry::class,
                'required' => true,
                'mapped' => false,
                'placeholder' => 'Sélectionnez d\'abord un type d\'entité',
                'choices' => [],
            ]);
        }
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'sessionYear' => null,
            'sessionMinistry' => null,
            'sessionCommune' => null,
            'defaultType' => null,
            'defaultEntite' => null,
        ));
    }
}
