<?php

namespace App\Controller;

use App\Entity\GlobalParameter;
use App\Utils\CustomEntityManager;
use App\Utils\TAVCotisationUtils;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Sonata\AdminBundle\Controller\CRUDController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\Adherent;

class AdherentAdminController extends CRUDController
{
    protected $em;
    protected $security;
    protected $tavCotisationUtils;

    public function __construct(CustomEntityManager $em, Security $security, TAVCotisationUtils $tavCotisationUtils)
    {
        $this->em = $em;
        $this->security = $security;
        $this->tavCotisationUtils = $tavCotisationUtils;
    }

    /**
     * Prélèvement d'un adhérent pour ramener son solde sous son plafond.
     *
     * @param Request $request
     * @param Uuid    $id      Id du prestataire
     * @IsGranted({"ROLE_SUPER_ADMIN", "ROLE_ADMIN_SIEGE", "ROLE_TRESORIER"})
     * @return Response
     */
    public function withdrawDownToTheCeilingAction(Request $request, $id): Response
    {
        $adherent = $this->admin->getSubject();

        if (!$adherent) {
            throw new NotFoundHttpException(sprintf('Impossible de trouver l\'adhérent avec l\'id: %s', $id));
        }

        $amountDiff = $this->tavCotisationUtils->withdrawDownToTheCeiling($adherent);

        $this->em->flush();

        $this->addFlash(
            'sonata_flash_success',
            'Prélèvement de ' . -$amountDiff . ' MonA' . ' effectué.'
        );

        return new RedirectResponse(
            $this->admin->generateUrl('list', ['filter' => $this->admin->getFilterParameters()])
        );
    }

    /**
     * Recalculate household allocation in case of switching between household allocation methods.
     *
     * @param Request $request
     * @IsGranted({"ROLE_SUPER_ADMIN", "ROLE_ADMIN_SIEGE", "ROLE_TRESORIER"})
     * @return Response
     */
    public function recalculateHouseholdAllocationsAction(Request $request): Response
    {

        $qb = $this->em->getRepository(Adherent::class)->createQueryBuilder('a');

        $forcedAmount = (int) $this->em->getRepository(GlobalParameter::class)
            ->val(GlobalParameter::SSA_FORCE_ALLOCATION_AMOUNT);
        if($forcedAmount > 0) {
            $adherents = $qb->getQuery()->getResult();
            foreach ($adherents as $adherent)  {
                $adherent->setAllocationAmount($forcedAmount);
            }
        } else if ($this->getParameter('simplified_household_based_allowance')) {
            $adherents = $qb->where($qb->expr()->isNotNull("a.householdCount"))
                ->andWhere($qb->expr()->isNotNull("a.cotisationAmount"))
                ->getQuery()
                ->getResult();
            ;
    
            foreach ($adherents as $adherent)  {
                $this->tavCotisationUtils->calculateAllowanceAccordingToHouseholdSimplified($adherent);
                $this->em->persist($adherent);
            }
        } else if ($this->getParameter('household_based_allowance')) {
            $adherents = $qb->where($qb->expr()->isNotNull("a.householdAdultCount"))
                ->andWhere($qb->expr()->isNotNull("a.cotisationAmount"))
                ->getQuery()
                ->getResult();
            ;

            foreach ($adherents as $adherent)  {
                $this->tavCotisationUtils->calculateAllowanceAccordingToHousehold($adherent);
                $this->em->persist($adherent);
            }
        }

        $this->em->flush();

        $this->addFlash(
            'sonata_flash_success',
            'Allocation recalculées avec succès'
        );

        return new RedirectResponse(
            $this->admin->generateUrl('list', ['filter' => $this->admin->getFilterParameters()])
        );
    }
}
