<?php

namespace App\Form\Type;

use App\Entity\Comptoir;
use App\Entity\Adherent;
use App\Entity\VenteEmlcComptoirAdherent;
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 EncaisserCotisationAdherentFormType extends VenteEmlcAdherentFormType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if (empty($this->security) || empty($this->security->getUser())) {
            throw new \Exception('[FORM VENTE EMLC] Opération impossible !');
        }

        // Get the cotisation amount for each adherent. Used for display purposes on the front end.
        $adherents = $this->em->getRepository(Adherent::class)->findOrderByName();
        $adherentsCotisationAmounts = [];
        foreach ($adherents as $adh) {
            $montant = null;

            if ($this->container->getParameter('household_based_allowance') && !is_null($adh->getCotisationAmount())) {
                $montant = $adh->getCotisationAmount();
            } else if (!$this->container->getParameter('household_based_allowance') && !is_null($adh->getProfilDeCotisation())) {
                $montant = $adh->getProfilDeCotisation()->getMontant();
            }

            $adherentsCotisationAmounts[strval($adh->getId())] = $montant;
        }

        $builder
            ->add('reference', HiddenType::class, [
                'data' => 'Encaissement cotisation adhérent'
            ])
            ->add('montant', HiddenType::class, [
                'data' => 0  
            ])
            ->add('cotisationMontants', HiddenType::class, [
                'data' =>  json_encode($adherentsCotisationAmounts),
                'mapped' => false
            ])
        ;
    }

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

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

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