<?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('simplified_household_based_allowance')) {
                if (!is_null($adh->getCotisationAmount())) {
                    $montant = $adh->getCotisationAmount();
                } else if (!is_null($adh->getProfilDeCotisation())) {
                    // For transition purposes, if adherent doesn't have a cotisation amount set but has a ProfilDeCotisation, use ProfilDeCotisation amount
                    $montant = $adh->getProfilDeCotisation()->getMontant();
                }
            } 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';
    }
}
