<?php

declare(strict_types=1);

namespace External\HannahBundle\EventSubscriber;

use External\HannahBundle\Util\HannahRedirectUtil;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class ResponseSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::RESPONSE => [
                ['onResponseSetCookie', 200],
            ],
        ];
    }

    public function onResponseSetCookie(ResponseEvent $event): void
    {
        if (!($request = $event->getRequest())) {
            return;
        }

        // pokud neni na requestu nasetovany attribut redirectChecked, tak nepotrebuju nic nastavovat
        if (!$request->attributes->get(HannahRedirectUtil::COOKIE_NAME)) {
            return;
        }

        // nastavim cookie s redirectChecked na 1 rok
        $event->getResponse()->headers->setCookie(
            Cookie::create(HannahRedirectUtil::COOKIE_NAME, '1')
                ->withExpires(
                    (new \DateTime())->add(new \DateInterval('P1Y'))
                )
        );
    }
}
