<?php

/*
 * This file is part of the VITICORE2 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 CpCreation\VitiCore\Product\Model\Product;
use CpCreation\VitiCore\Product\Model\ProductCollectionItem;
use CpCreation\VitiCore\Product\Repository\ProductRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

final class ProductCollectionItemType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('product', EntityType::class, [
                'class' => Product::class,
                'query_builder' => static function (ProductRepository $repository) {
                    return $repository->createQueryBuilder('product')
                        ->leftJoin('product.category', 'category')
                        ->andWhere('product.deletedAt IS NULL')
                        ->addOrderBy('category.position', 'ASC')
                        ->addOrderBy('product.position', 'ASC');
                },
                'choice_label' => static function (Product $product): string {
                    $category = $product->getCategory();
                    $prefix = null !== $category ? (string) $category->getName().' - ' : '';

                    return $prefix.(string) ($product->getFullName() ?: $product->getName());
                },
                'label' => false,
                'required' => true,
                'attr' => [
                    'class' => 'select2',
                    'style' => 'width: 100%;',
                ],
            ])
            ->add('position', IntegerType::class, [
                'label' => 'Position',
                'required' => false,
                'attr' => [
                    'min' => 0,
                    'class' => 'position-form',
                ],
            ]);
    }

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