<?php

namespace App\EventListener;

use App\Entity\Flux;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class RequestListener
{
    private $em;
    private $tokenStorage;
    private $router;

    public function __construct(EntityManagerInterface $em, TokenStorageInterface $tokenStorage, RouterInterface $router)
    {
        $this->em = $em;
        $this->tokenStorage = $tokenStorage;
        $this->router = $router;
    }

    public function onKernelRequest(RequestEvent $event)
    {
        if (!$event->isMasterRequest()) {
            // don't do anything if it's not the master request
            return;
        }

        $user = $this->tokenStorage->getToken()->getUser();
        $route  = $event->getRequest()->attributes->get('_route');
        if (null != $user &&
            (
                ($user->isGranted('ROLE_ADHERENT')  &&
                null != $user->getAdherent()) || 
                ($user->isGranted('ROLE_PRESTATAIRE')  &&
                null != $this->session->get('_prestagere'))
            )  &&
            !$this->isCotisationValid($user) && 
            $route != 'cotisation_invalid'
        ) {
            $event->setResponse(new RedirectResponse($this->router->generate('cotisation_invalid')));
        }
    }

    private function isCotisationValid(User $user): bool
    {
        $query = null;
        if ($user->isGranted('ROLE_ADHERENT') && null != $user->getAdherent()) {
            $query = $this->em->getRepository(Flux::class)->getQueryByAdherent($user->getAdherent(), 'cotisation');
        } elseif ($user->isGranted('ROLE_PRESTATAIRE') && null != $this->session->get('_prestagere')) {
            $query = $this->em->getRepository(Flux::class)->getQueryByPrestataire($this->session->get('_prestagere'));
        }
        if (null !== $query) {
            $cotisations = $query->getResult();
            foreach ($cotisations as $cotisation) {
                if ($cotisation->isRecu() && $cotisation->getCotisationInfos()->getFin() > new \DateTime('now')) {
                    return true;
                }
            }
        }
        return false;
    }
}