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

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

use A2lix\TranslationFormBundle\Form\Type\TranslationsType;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Manager\PaymentMethodManager;
use CpCreation\VitiCore\Cart\Model\PaymentMethod;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;

class PaymentMethodStep2Type extends AbstractType
{
    private $manager;

    public function __construct(PaymentMethodManager $manager)
    {
        $this->manager = $manager;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add(
            'paymentOnline', CheckboxType::class, [
            'label'    => 'Paiement utilisé pour le paiement en ligne d\'une facture',
            'required' => false,
        ]
        );
        $builder->addEventListener(
            FormEvents::PRE_SET_DATA,
            [$this, 'onPreSetData']
        );
    }

    /**
     * @param FormEvent $event
     * @throws \Exception
     * @throws \ReflectionException
     */
    public function onPreSetData(FormEvent $event)
    {
        $form    = $event->getForm();
        $payment = $event->getData();
        $method  = $payment->getMethod();
        $class   = $this->manager->createFormPaymentMethodManager($method);

        $form->add(
            'translations', TranslationsType::class, [
                'label'  => false,
                'fields' => [
                    'configuration' => [
                        'field_type' => $class->getName(),
                        'label'      => false,
                        'required'   => true,
                    ],
                ],
            ]
        );;
    }


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

    public function getBlockPrefix()
    {
        return 'paymentMethodStep2';
    }

}
