<?php

namespace PrestaShop\Module\PolarisPrestaTheme\Forms;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use PrestaShopBundle\Form\Admin\Type\CategoryChoiceTreeType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use PrestaShopBundle\Form\Admin\Type\SwitchType;


class MenuChildType extends AbstractType{

    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        
        $parentId = $options['parent_id'];

        
        
        $isCustomParent = $this->isCustomParent($parentId);

        $builder
 
        ->add('parent_id', HiddenType::class, [
            'data' => (int) $options['parent_id'],// valeur injectée depuis le contrôleur via options
        ])

        ->add('isVisible',SwitchType::class, [
            'label' => 'Activer la visibilité',
            'required' => false,
        ]);

        
        
        if ($isCustomParent) {
            
            $builder->add('menu_type', ChoiceType::class, [
                    'label'    => 'Type de menu',
                    'choices'  => [
                        'Lien personnalisé'    => 'custom',
                    ],
                    'multiple' => false,
                    'empty_data' => 'custom',
                    'attr'     => ['class' => 'menu-type-toggle','style' => 'display:none'],     
            ])

            ->add('parent_name_custom', TextType::class,[
                'label'    => 'ajouter le titre du sous menu',
            ])
            // Parent custom → uniquement les custom links
            ->add('custom_links', CollectionType::class, [
                'label'         => 'Liens personnalisés',
                'entry_type'    => MenuCustomType::class,
                'allow_add'     => true,
                'allow_delete'  => true,
                'by_reference'  => false,
                'prototype'     => true,
                'entry_options' => ['label' => false],
            ]);
        } else {
            
            // Parent category → les deux
            $builder

                ->add('menu_type', ChoiceType::class, [
                    'label'    => 'Type de menu',
                    'choices'  => [
                        'Catégorie PrestaShop' => 'category',
                        'Lien personnalisé'    => 'custom',
                    ],
                    'multiple' => false,
                    'attr'     => ['class' => 'menu-type-toggle'],     
                ])
                ->add('child', CategoryChoiceTreeType::class, [
                    'label'           => 'Sélectionner les catégories pour créer votre menu déroulant',
                    'multiple'        => true,
                    'required'        => false,
                    'choices_tree'    => $this->getCategoryTree($options['parent_id']),
                    'choice_value'    => 'id',
                    'choice_label'    => 'name',
                    'choice_children' => 'children',
                    'disabled'        => false,
                    'empty_data' => [],
                ])
                ->add('custom_links', CollectionType::class, [
                    'label'         => 'Liens personnalisés',
                    'entry_type'    => MenuCustomType::class,
                    'allow_add'     => true,
                    'allow_delete'  => true,
                    'by_reference'  => false,
                    'prototype'     => true,
                    'entry_options' => ['label' => false],
                    'attr'     => ['class' => 'menu-field-custom', 'style' => 'display:none'],
                ]);
        }

       
        $builder->add('save', SubmitType::class , [
                'label' => 'Enregistrer',
                'attr' => [
                    'class' => 'btn btn-primary',
                ],
            ]);
    }


    public function configureOptions(\Symfony\Component\OptionsResolver\OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'parent_id' => null, // attendue depuis CreateConfigurationForm() via options
        ]);
    }
  

    private function getCategoryTree($parentId)
    {
        $languageId = \Context::getContext()->language->id;

        $categories = \Category::getChildren($parentId, $languageId);
        $tree = [];

        foreach ($categories as $category) {
            $tree[] = $this->buildCategoryBranch($category['id_category'], $languageId, 2); // profondeur : 2 niveaux
        }

        return $tree;
    }

    private function buildCategoryBranch($categoryId, $languageId, $depth = 2)
    {
        $category = new \Category($categoryId, $languageId);
        $children = [];

        if ($depth > 0) {
            $childCategories = \Category::getChildren($categoryId, $languageId);
            foreach ($childCategories as $child) {
                $children[] = $this->buildCategoryBranch($child['id_category'], $languageId, $depth - 1);
            }
        }

        return [
            'id' => (int) $categoryId,
            'name' => $category->name,
            'children' => $children,
        ];
    }

    private function isCustomParent(?int $parentId): bool
    {
     
        if (!$parentId) return false;

        $config = \PrestaShop\Module\PolarisPrestaTheme\Config\ConfigTheme::load();

        foreach ($config->configMenuParent as $menuParent) {
        
            
            if ((int)($menuParent->menu['id']) === (int)$parentId) {
                
                if ($menuParent->menu['type'] === "custom"){
                    return true;
                }
                
            }
        }

        return false;
    }



    public static function getIntro(): ?string
    {
        return 'Cette page vous permet de créer un menu déroulant personnalisé en sélectionnant les sous-catégories associées à une catégorie parente.</br>
        - Cochez les sous-catégories que vous souhaitez inclure dans votre menu déroulant</br>
        - Une fois la sélection terminée, cliquez sur "Enregistrer" pour valider votre configuration.</br>
        ';
    }

}