<?php

declare(strict_types=1);

namespace KupShop\ComponentsBundle\Twig\Components\Utils\GTM;

use KupShop\ComponentsBundle\Attributes\Component;
use KupShop\ComponentsBundle\Attributes\Version;
use KupShop\ComponentsBundle\GTM\Utils\DataLoaders\Products;
use KupShop\ComponentsBundle\Twig\BaseComponent;
use KupShop\GTMBundle\Utils\Providers\ProductDataProvider;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent(template: '@Components/components/Utils/GTM/ProductDataPrinter.1.html.twig')]
#[Component(1, [
    new Version(1, newCss: null),
])]
class ProductDataPrinter extends BaseComponent
{
    public function __construct(
        private readonly ProductDataProvider $productDataProvider,
        protected readonly Products $productsDataLoader,
    ) {
    }

    public function hasProducts(): bool
    {
        if (!$this->isGTM()) {
            return false;
        }

        return !empty($this->productDataProvider->getProducts());
    }

    public function getProducts(): string
    {
        $products = $this->productDataProvider->getProducts();

        $gtmProductsObjects = $this->productsDataLoader->getGTMProductsObjects($products);

        /*
          Aby se nestalo, ze to bude na strance vickrat.
          JS to na FE stejne merguje, takze je jedno kde se to vypise.
        */
        $this->productDataProvider->clear();

        // TODO: dát pryč, jen pro debug
        $string = json_encode($gtmProductsObjects, JSON_NUMERIC_CHECK | JSON_HEX_APOS);

        return $string;
    }

    public function isGTM()
    {
        $dbcfg = \Settings::getDefault();

        if (isDevelopment() && ($dbcfg->analytics['google_tag_manager']['reallyRun'] ?? 'N') != 'Y') {
            $gtmId = 'GTM-PFLLL74';
        } else {
            $gtmId = $dbcfg->analytics['google_tag_manager']['ID'];
        }

        if (getVal('skip_gtm')) {
            return null;
        }

        return $gtmId;
    }
}
