<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin;

use A2lix\TranslationFormBundle\Form\Type\TranslatedEntityType;
use A2lix\TranslationFormBundle\Form\Type\TranslationsType;
use CpCreation\VitiCore\Product\Model\ProductPriceGroup;
use CpCreation\VitiCore\Product\Model\ProductVariant;
use CpCreation\VitiCore\Product\Repository\ProductPriceGroupRepository;
use CpCreation\VitiCore\Shop\Model\DeliveryMethod;
use CpCreation\VitiCore\Shop\Model\DeliveryMethodCategory;
use CpCreation\VitiCore\Shop\Model\ShippingCounty;
use CpCreation\VitiCore\Shop\Repository\ShippingCountyRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

final class DeliveryMethodType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('publishedAt', DateTimeType::class, [
                'required' => false,
                'label' => 'Publier automatiquement ce mode de livraison',
                'input' => 'datetime',
                'format' => 'yyyy-MM-dd HH:mm',
                'html5' => false,
                'widget' => 'single_text',
                'attr' => ['class' => 'datetimepicker'],
            ])
            ->add('unPublishedAt', DateTimeType::class, [
                'required' => false,
                'label' => 'Dépublier automatiquement ce mode de livraison',
                'input' => 'datetime',
                'format' => 'yyyy-MM-dd HH:mm',
                'html5' => false,
                'widget' => 'single_text',
                'attr' => ['class' => 'datetimepicker'],
            ])
            ->add('packagePrice', MoneyType::class, [
                'divisor' => 100,
                'label' => 'Forfait (HT ou TTC)',
                'required' => false,
            ])
            ->add('bottlePrice', MoneyType::class, [
                'divisor' => 100,
                'label' => 'Par bouteille (HT ou TTC)',
                'required' => false,
            ])
            ->add('disabledEquivalence', CheckboxType::class, [
                'label' => 'Désactiver l\'équivalence pour le calcul des frais de port',
                'required' => false,
            ])

            // ⚠️ Label négatif vs nom "enabled…" : si possible renommer côté entity ou inverser la logique
            ->add('enabledShippingPrice', CheckboxType::class, [
                'label' => 'Ne pas afficher sur la boutique les frais de port ci-dessous et ne pas prendre en compte les montants ci-dessous',
                'help' => 'Le calcul se fera via les frais de port manuels configures pour cette methode de livraison.',
                'required' => false,
            ])
            ->add('multipleVariant', CheckboxType::class, [
                'label' => 'Désactiver la vérification des multiples par variant',
                'required' => false,
            ])
            ->add('category', TranslatedEntityType::class, [
                'label' => 'Type',
                'class' => DeliveryMethodCategory::class,
                'translation_property' => 'name',
                'required' => true,
                'multiple' => false,
            ])
            ->add('qtyAt', IntegerType::class, [
                'label' => 'Quantité minimum d\'équivalence pour valider cette méthode de livraison',
                'required' => false,
            ])
            ->add('translations', TranslationsType::class, [
                'label' => false,
                'fields' => [
                    'name' => [
                        'field_type' => TextType::class,
                        'label' => 'Nom de la méthode de livraison',
                        'required' => false,
                    ],
                    'description' => [
                        'field_type' => TrumbowygType::class,
                        'label' => 'Description de la livraison',
                        'required' => false,
                    ],
                    'otherText' => [
                        'field_type' => TrumbowygType::class,
                        'label' => 'Autre texte',
                        'required' => false,
                    ],
                ],
                'excluded_fields' => ['slug'],
            ])
            ->add('groups', EntityType::class, [
                'class' => ProductPriceGroup::class,
                'query_builder' => static function (ProductPriceGroupRepository $repo) {
                    return $repo->findByNameOrderAdminQuery();
                },
                'choice_label' => 'name',
                'label' => 'Groupes de prix',
                'multiple' => true,
                'required' => true,
                'attr' => ['class' => 'select2'],
            ])
            ->add('viewCounties', CheckboxType::class, [
                'label' => 'Afficher les départements dans l\'intitulé',
                'required' => false,
            ])
            ->add('counties', EntityType::class, [
                'class' => ShippingCounty::class,
                'query_builder' => static function (ShippingCountyRepository $repo) {
                    return $repo->findWithZoneNotNullQuery();
                },
                'label' => 'Département (2 chiffres)',
                'multiple' => true,
                'required' => false,
                'choice_label' => static function (?ShippingCounty $county): string {
                    return $county?->getCode() ?? '';
                },
                // Symfony 7: préfère un callable (stable)
                'choice_value' => static function (?ShippingCounty $county): string {
                    return $county?->getCode() ?? '';
                },
                'attr' => ['class' => 'select2-tag'],
            ])
            ->add('productVariants', EntityType::class, [
                'label' => 'Variant(s) disponible(s) pour ce mode de livraison',
                'class' => ProductVariant::class,
                'choice_label' => 'name',
                'required' => false,
                'multiple' => true,
                'help' => 'Laisser vide pour prendre en compte tous les variants',
                'attr' => ['class' => 'select2'],
            ])
            ->add('viewProduct', CheckboxType::class, [
                'label' => 'Afficher dans la boutique les produits disponibles pour ce mode de livraison',
                'required' => false,
            ])
            ->add('depot', CheckboxType::class, [
                'label' => 'Remplace la phrase "Afficher nos produits disponibles pour ce mode de livraison" par "Afficher nos produits disponibles dans ce dépôt"',
                'required' => false,
            ]);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => DeliveryMethod::class,
            'translation_domain' => 'form',
        ]);
    }
}
