<?php
/**
 * @author Colinet Julien
 */

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

use CpCreation\VitiCore\Cart\Model\CartItem;
use CpCreation\VitiCore\Product\Model\ProductVariant;
use CpCreation\VitiCore\Product\Repository\ProductVariantRepository;
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;

class CartItemType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add(
                'quantity', IntegerType::class, [
                    'label' => 'Quantité',
                    'attr'  => [
                        "min"          => 1,
                        "data-item"    => "",
                        "class"        => "cart-item-quantity",
                        "autocomplete" => "nope",
                    ],
                ]
            )
            ->add(
                'variant', EntityType::class, [
                    'class'         => ProductVariant::class,
                    'query_builder' => function (ProductVariantRepository $er) {
                        return $er->findAllPublishQuery();
                    },
                    'attr'          => [
                        "data-item" => "",
                        "class"     => "cart-item-variant hidden",
                    ],
                    'choice_label'  => function (ProductVariant $variant) {
                        $quality = '';
                        $unity   = '';
                        if ($variant->getProduct()->getQuality()) {
                            $quality = strip_tags($variant->getProduct()->getQuality());
                        }
                        if ($variant->getType()->getUnity()) {
                            $unity = strip_tags($variant->getType()->getVolume()).' '.$variant->getType()->getUnity();
                        }
                        if ($variant->getType()->isGift()) {
                            return strip_tags($variant->getProduct()->getName()).' '.($variant->getPrice()/100)."€";
                        }

                        if ($variant->getProduct()->getName() == $variant->getType()->getName()) {
                            return strip_tags($variant->getProduct()->getName()).' '.$quality;
                        }



                        return strip_tags($variant->getProduct()->getName()).' '.$quality.' - '.strip_tags($variant->getType()->getName()).' '.$unity;
                    },
                ]
            );
    }

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