<?php

namespace Lc\ShopBundle\Form\Backend\Order;

use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Lc\ShopBundle\Context\MerchantUtilsInterface;
use Lc\ShopBundle\Context\ProductInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ButtonType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class AddPoductToOrderType extends AbstractType
{
        protected $em;
        protected $merchantUtils;

        public function __construct(EntityManagerInterface $em, MerchantUtilsInterface $merchantUtils)
        {
                $this->em = $em;
                $this->merchantUtils = $merchantUtils;
        }

        public function buildForm(FormBuilderInterface $builder, array $options)
        {
                //$data = $options['data'] ;
                $productClass = $this->em->getClassMetadata(ProductInterface::class);
                $currentMerchant = $this->merchantUtils->getMerchantUser();

                $builder
                        ->add('product', EntityType::class, array(
                                'class' => $productClass->name,
                                'placeholder' => '',
                                'mapped' => false,
                                'required' => false,
                                'query_builder' => function (EntityRepository $er) use ($currentMerchant) {
                                        return $er->createQueryBuilder('p')
                                                ->join('p.productFamily', 'pFamily')
                                                ->where('pFamily.merchant = :currentMerchant')
                                                ->andWhere('pFamily.status = 1')
                                                ->setParameter('currentMerchant', $currentMerchant);
                                },
                                'choice_label' => function ($product) {
                                        return $product->getProductFamily()->getTitle() . ' - ' . $product->getTitle();
                                }
                        ))
                        ->add('quantity', IntegerType::class, array(
                                'mapped' => false
                        ))
                        ->add('add', ButtonType::class, array(
                                'label'=> 'action.add'
                        ));
        }

        public function configureOptions(OptionsResolver $resolver)
        {
                $resolver->setDefaults([
                        'translation_domain'=>'lcshop'
                ]);
        }
}
