<?php

namespace KupShop\MarketingBundle\EventListener;

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

class ResponseListener implements EventSubscriberInterface
{
    public const CJSessionKey = 'cjevent';

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

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

        try {
            $session = $request->getSession();
        } catch (SessionNotFoundException $e) {
            return;
        }

        $cookie_bar = $request->cookies->get('cookie-bar');
        $consents = array_flip(explode(',', $cookie_bar ?? ''));
        $isAnalyticsStorage = isset($consents['analytics_storage']);

        if ($requestData = $request->get(self::CJSessionKey)) {
            $session->set(self::CJSessionKey, $requestData);
        }

        if ($dmAfill = $request->get('transaction_id')) {
            if (isset($consents['analytics_storage'])) {
                $response = $event->getResponse();
                $response->headers->setCookie(new Cookie('AP_tracker_TID', $dmAfill, time() + 120 * 24 * 60 * 60));
            } else {
                $session->set('AP_tracker_TID', $dmAfill);
            }
        }
    }
}
