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

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

use CpCreation\VitiCore\Cart\Model\CartCheckout;
use CpCreation\VitiCore\Cart\Model\PaymentMethod;
use CpCreation\VitiCore\Cart\Repository\PaymentMethodRepository;
use CpCreation\VitiCore\Contact\Repository\ContactRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class CartCheckoutType extends AbstractType
{

    private $cgvPath;

    /**
     * CartCheckoutType constructor.
     * @param ContactRepository $contactRepository
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function __construct(ContactRepository $contactRepository)
    {
        $this->cgvPath = '';
        $contact       = $contactRepository->findOne();
        if ($contact->getFile()) {
            $this->cgvPath = $contact->getFile()->getPath();
        }
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add(
                'paymentMethod', EntityType::class, [
                    'class'         => PaymentMethod::class,
                    'query_builder' => function (PaymentMethodRepository $er) {
                        return $er->findByPositionOrderQuery();
                    },
                    'expanded'      => true,
                    'label'         => false,
                    'required'      => true,
                    'choice_label'  => function ($method) {
                        return $method->getConfiguration()['name'];
                    },
                ]
            )
            ->add(
                'cgv', CgvType::class, [
                    'label'    => 'shop.accept_cgv',
                    'required' => true,
                    'path'     => $this->cgvPath,
                ]
            );

    }

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