<?php

namespace App\Form\Type;

use App\Entity\AccountAdherent;
use App\Entity\AccountPrestataire;
use App\Entity\Adherent;
use App\Entity\GlobalParameter;
use App\Entity\Prestataire;
use App\Enum\CurrencyEnum;
use App\Enum\MoyenEnum;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\GreaterThanOrEqual;
use Symfony\Component\Validator\Constraints\LessThanOrEqual;

class TransactionFormType extends FluxFormType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $flux = $options['data'];
        if ($flux->getExpediteur() instanceof Prestataire) {
            $account = $this->em->getRepository(AccountPrestataire::class)->findOneBy(['prestataire' => $flux->getExpediteur(), 'currency' => CurrencyEnum::CURRENCY_EMLC]);
        } elseif ($flux->getExpediteur() instanceof Adherent) {
            $account = $this->em->getRepository(AccountAdherent::class)->findOneBy(['adherent' => $flux->getExpediteur(), 'currency' => CurrencyEnum::CURRENCY_EMLC]);
        }
        $currency = $this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::MLC_SYMBOL);
        $builder
            ->add('montant', MoneyType::class, [
                'label' => 'Montant :',
                'required' => true,
                'currency' => $currency ? $currency : 'MLC',
                'constraints' => [
                    new GreaterThanOrEqual([
                        'message' => 'Montant inférieur à zéro !',
                        'value' => 0,
                    ]),
                    new LessThanOrEqual([
                        'message' => 'Montant supérieur à votre solde !',
                        'value' => $account->getBalance(),
                    ]),
                ],
            ])
            ->add('moyen', HiddenType::class, [
                'data' => MoyenEnum::MOYEN_VIREMENT,
            ])
            ->add('save', SubmitType::class, [
                'label' => 'Valider',
                'attr' => [
                    'class' => 'btn-primary btn transactionSubmit',
                ],
            ])
        ;
    }

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

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