<?php

namespace App\Controller;

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;

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()])
        );
    }
}
