<?php

namespace PrestaShop\Module\LCVPrestaTheme\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' => $options['parent_id'], // valeur injectée depuis le contrôleur via options
            ])

        ->add('isVisible',SwitchType::class, [
            'label' => 'Activer la visibilité',
            'required' => false,
        ]);
        
        if ($isCustomParent) {
        // Parent custom → uniquement les champs texte/url
            $builder->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 {
           $builder->add('child', CategoryChoiceTreeType::class, [
                        'label' => 'Sélectionner les catégories pour creer 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,
                        'attr' => ['class' => 'menu-field-category']
                    ]);
        }

       
        $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\LCVPrestaTheme\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>
        ';
    }

}