<?php
/**
 * Mirasvit
 *
 * This source file is subject to the Mirasvit Software License, which is available at https://mirasvit.com/license/.
 * Do not edit or add to this file if you wish to upgrade the to newer versions in the future.
 * If you wish to customize this module for your needs.
 * Please refer to http://www.magentocommerce.com for more information.
 *
 * @category  Mirasvit
 * @package   mirasvit/module-cache-warmer
 * @version   1.11.13
 * @copyright Copyright (C) 2026 Mirasvit (https://mirasvit.com/)
 */


declare(strict_types=1);

namespace Mirasvit\CacheWarmer\Service;

use Mirasvit\CacheWarmer\Api\Data\PageInterface;
use Mirasvit\CacheWarmer\Api\Data\WarmRuleInterface;
use Mirasvit\CacheWarmer\Api\Repository\PageRepositoryInterface;
use Mirasvit\CacheWarmer\Model\Config;

class CookieService
{
    private const IGNORED_COOKIES_DEFAULT = [
        '_ga',
        '_gcl_au',
        '__utmz',
        '__zlcmid',
        '__utmc',
        '_gid',
        '_fbp',
        'PHPSESSID',
        'mst-cache-warmer-track',
        'mst-cache-warmer-toolbar',
    ];

    /**
     * @var Config
     */
    private $config;

    /**
     * @var PageRepositoryInterface
     */
    private $pageRepository;

    public function __construct(
        Config $config,
        PageRepositoryInterface $pageRepository
    ) {
        $this->config = $config;
        $this->pageRepository = $pageRepository;
    }

    /**
     * @param string|null $cookie
     * @return string
     */
    public function prepareCookie($cookie)
    {
        if (!$cookie) {
            return '';
        }

        $ignoredCookies = array_merge(self::IGNORED_COOKIES_DEFAULT, $this->config->getIgnoredCookies());

        $cookies = [];
        $ccc     = explode(";", $cookie);

        foreach ($ccc as $c) {
            $cc = explode("=", $c);
            if (count($cc) != 2) {
                continue;
            }

            $k = trim($cc[0]);

            if (in_array($k, $ignoredCookies)) {
                continue;
            }

            $v         = $cc[1];
            $cookies[] = "$k=$v";
        }

        return implode(";", $cookies);
    }

    /**
     * @return void
     */
    public function refreshPagesByCookies()
    {
        $pageCollection  = $this->pageRepository->getCollection();
        $conditions = [];

        foreach ($this->config->getIgnoredCookies() as $cookie) {
            $conditions[] = $pageCollection->getSelect()->getAdapter()->quoteInto(
                PageInterface::COOKIE . ' LIKE ? ', '%' . $cookie . '%'
            );
        }

        if (empty($conditions)) {
            return;
        }

        $pageCollection->getSelect()->where(implode(' OR ', $conditions));
        $pageCollection->getSelect()->limit(10000);
        $pageCollection->setOrder(PageInterface::POPULARITY);

        while ($page = $pageCollection->fetchItem()) {
            $page->setCookie($this->prepareCookie($page->getCookie()));
            $this->pageRepository->save($page);
        }
    }
}
