<?php

namespace App\Form\Type;

use App\Entity\AchatMonnaieAdherent;
use App\Entity\Adherent;
use App\Entity\DonAdherent;
use App\Entity\GlobalParameter;
use App\Entity\Prestataire;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class AchatMonnaieAdherentFormType extends AchatMonnaieFormType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if (empty($this->security) || empty($this->security->getUser())) {
            throw new \Exception('[FORM ACHAT MONNAIE ADHERENT] Opération impossible !');
        }
        $don = null;
        if ('true' == $this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::ACCEPT_DON_ADHERENT_ACHAT)) {
            $don = new DonAdherent();
            $don->setExpediteur($this->security->getUser()->getAdherent());
            $don->setDestinataire($this->em->getRepository(Prestataire::class)->findOneBy(['mlc' => true]));
        }
        $builder
            ->add('destinataire', HiddenType::class, [
                'data' => $this->security->getUser()->getAdherent(),
                'data_class' => null,
                'entity_class' => Adherent::class,
                'em' => $this->em,
            ])
            ->add('reference', HiddenType::class, [
                'data' => AchatMonnaieAdherent::REFERENCE_ACHAT_MONNAIE_ADHERENT_EN_CB,
            ])
        ;
        if (null != $don) {
            $builder
                ->add('don', DonAdherentFormType::class, [
                    'label' => false,
                    'required' => false,
                    'data' => $don,
                ])
            ;
        }
        if ('true' === $this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::USE_HELLOASSO) &&
            !empty($this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::HELLOASSO_URL_EMLC_ADHERENT))) {
            $builder
                ->add('saveHelloAsso', SubmitType::class, [
                    'label' => 'Payer via HelloAsso',
                    'translation_domain' => 'messages',
                    'attr' => [
                        'class' => 'btn-primary btn achatHelloAssoSubmit',
                    ],
                ])
            ;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'class' => AchatMonnaieAdherent::class,
        ]);
    }

    public function getParent()
    {
        return AchatMonnaieFormType::class;
    }

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