<?php

namespace App\Form\Type;

use App\Entity\Adherent;
use App\Entity\DonAdherent;
use App\Entity\DonPrestataire;
use App\Entity\GlobalParameter;
use App\Entity\Prestataire;
use App\Entity\User;
use App\Enum\MoyenEnum;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Validator\Constraints\GreaterThanOrEqual;
use Symfony\Component\Validator\Constraints\NotBlank;

class CotiserFormType extends AbstractType
{
    protected $em;
    protected $security;
    protected $session;

    public function __construct(EntityManagerInterface $em, Security $security, SessionInterface $session)
    {
        $this->em = $em;
        $this->security = $security;
        $this->session = $session;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if (empty($this->security) || empty($this->security->getUser())) {
            throw new \Exception('Opération impossible ! Utilisateur non connecté !');
        }
        $now = new \DateTime();
        $montantMinimum = 0;
        $montantDefault = 0;
        $canPayWithMlc = false;
        $canPayWithHelloAsso = false;
        $don = null;
        if ($this->security->isGranted('ROLE_ADHERENT')) {
            $montantMinimum = floatval($this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::COTISATION_ADHERENT));
            $montantDefault = floatval($this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::COTISATION_ADHERENT_DEFAULT));
            $canPayWithMlc = ($this->security->getUser()->getAdherent()->getEmlcAccount()->getBalance() >= $montantMinimum);
            $canPayWithHelloAsso = ('true' === $this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::USE_HELLOASSO) && !empty($this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::HELLOASSO_URL_COTISATION_ADHERENT))) ? true : false;
            if ('true' == $this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::ACCEPT_DON_ADHERENT_COTISATION)) {
                $don = new DonAdherent();
                $don->setExpediteur($this->security->getUser()->getAdherent());
                $don->setDestinataire($this->em->getRepository(Prestataire::class)->findOneBy(['mlc' => true]));
            }
        } elseif ($this->security->isGranted('ROLE_PRESTATAIRE')) {
            $montantMinimum = floatval($this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::COTISATION_PRESTATAIRE));
            $montantDefault = $montantMinimum;
            $presta = $this->session->get('_prestagere');
            $presta = $this->em->getRepository(Prestataire::class)->findOneById($presta->getId());
            $canPayWithMlc = (($presta->getEmlcAccount())->getBalance() >= $montantMinimum);
            $canPayWithHelloAsso = ('true' === $this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::USE_HELLOASSO) && !empty($this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::HELLOASSO_URL_COTISATION_PRESTATAIRE))) ? true : false;
            if ('true' == $this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::ACCEPT_DON_PRESTATAIRE_COTISATION)) {
                $don = new DonPrestataire();
                $don->setExpediteur($presta);
                $don->setDestinataire($this->em->getRepository(Prestataire::class)->findOneBy(['mlc' => true]));
            }
        }

        $canPayWithCB = 'true' === $this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::USE_PAYZEN) ? true : false;

        $builder
            ->add('operateur', HiddenType::class, [
                'entity_class' => User::class,
                'em' => $this->em,
                'data_class' => null,
                'data' => $this->security->getUser(),
            ])
            ->add('role', HiddenType::class, [
                'data' => $this->security->getUser()->getGroups()[0]->__toString(),
            ])
            ->add('destinataire', HiddenType::class, [
                'data' => $this->em->getRepository(Prestataire::class)->findOneBy(['mlc' => true]),
                'data_class' => null,
                'entity_class' => Prestataire::class,
                'em' => $this->em,
            ])
            ->add('reference', HiddenType::class, [
                'label' => 'Reference :',
                'required' => true,
                'data' => 'Cotisation ' . $now->format('Y'),
            ])
            ->add('moyen', HiddenType::class, [
                'data' => MoyenEnum::MOYEN_MLC,
            ])
        ;
        $freeAmount = 'true' == $this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::COTISATION_FREE_AMOUNT);
        if ($freeAmount) {
            $builder
                ->add('montant', IntegerType::class, [
                    'label' => 'Montant en prix libre :',
                    'data' => 0,
                    'constraints' => [
                        new GreaterThanOrEqual(['value' => 0]),
                    ],
                ])
            ;
        } else {
            $builder
                ->add('montant', IntegerType::class, [
                    'label' => 'Montant de la cotisation :',
                    'data' => $montantDefault,
                    'constraints' => [
                        new NotBlank(),
                        new GreaterThanOrEqual(['value' => $montantMinimum]),
                    ],
                ])
            ;
        }
        if (null != $don) {
            $builder
                ->add('don', $options['don_class'], [
                    'label' => false,
                    'required' => false,
                    'data' => $don,
                ])
            ;
        }
        // @TODO : si on peut ni payer par CB ni par MLC => on propose d'acheter de la MLC via d'autres moyens
        if ($canPayWithMlc) {
            $builder->add('payMLC', SubmitType::class, [
                'label' => 'Payer en e' . $this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::MLC_SYMBOL),
                'attr' => [
                    'class' => 'btn-primary btn cotisationMLCSubmit',
                ],
            ]);
        }
        if ($canPayWithCB) {
            $builder->add('payCB', SubmitType::class, [
                'label' => 'Payer en CB',
                'attr' => [
                    'class' => 'btn-primary btn cotisationCBSubmit',
                ],
            ]);
        }
        if ($canPayWithHelloAsso) {
            $builder->add('payHelloAsso', SubmitType::class, [
                'label' => 'Payer via HelloAsso',
                'attr' => [
                    'class' => 'btn-primary btn cotisationHelloAssoSubmit',
                ],
            ]);
        }

        if ($this->security->isGranted('ROLE_ADHERENT')) {
            $builder
                  ->add('expediteur', HiddenType::class, [
                      'entity_class' => Adherent::class,
                      'em' => $this->em,
                      'data_class' => null,
                      'data' => $this->security->getUser()->getAdherent(),
                  ])
            ;
        } elseif ($this->security->isGranted('ROLE_PRESTATAIRE')) {
            $builder
                  ->add('expediteur', HiddenType::class, [
                      'entity_class' => Prestataire::class,
                      'em' => $this->em,
                      'data_class' => null,
                      'data' => $this->session->get('_prestagere'),
                  ])
            ;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'cascade_validation' => true,
            'don_class' => null,
            '_year' => null,
        ]);
    }

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