<?php

namespace KupShop\GTMBundle\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class ResponseListener implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::RESPONSE => [
                ['onKernelResponse', 100],
            ],
        ];
    }

    public function onKernelResponse(ResponseEvent $event): void
    {
        $request = $event->getRequest();
        $response = $event->getResponse();

        foreach ($request->attributes->all() as $key => $value) {
            if (strpos($key, 'gtm_') !== false) {
                $response->headers->setCookie(new Cookie($key, json_encode($value), strtotime('now +1 minute'), null, null, true, false));
            }
        }
    }
}
