<?php

namespace App\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Http\Event\LogoutEvent;

class LogoutSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            LogoutEvent::class => 'onLogout',
        ];
    }

    public function onLogout(LogoutEvent $event): void
    {
        // Récupérer l'URL referer
        $referer = $event->getRequest()->headers->get('referer');

        // Vérifier que le referer n'est pas une URL de logout ou login
        if ($referer && !str_contains($referer, '/logout') && !str_contains($referer, '/login')) {
            $event->setResponse(new RedirectResponse($referer));
        } else {
            // Sinon rediriger vers la page d'accueil
            $event->setResponse(new RedirectResponse('/'));
        }
    }
}

