<?php

declare(strict_types=1);

namespace KupShop\ComponentsBundle\GTM\PostMount;

use KupShop\ComponentsBundle\Twig\Components\Utils\GTM\Script;
use Symfony\UX\TwigComponent\Attribute\PostMount;

trait GTMDefaultData
{
    use GTMPlaceholdersData;

    #[PostMount]
    public function addGTMDataAttribute(array $componentsData): array
    {
        if (!Script::getGTMId()) {
            return $componentsData;
        }

        if (empty($this->gtmClass)) {
            throw new \Exception('GTM on component enabled, but GTM class is not defined!');
        }

        if ($gtmData = $this->fetchGTMData()) {
            $componentsData['data-tracking-default'] = htmlentities(json_encode($gtmData, JSON_NUMERIC_CHECK | JSON_HEX_APOS));
        }

        return $componentsData;
    }

    protected function fetchGTMData(): ?object
    {
        /* Pokud mame nejake push data (muze byt kterakoliv classa, tak je vytahnu */
        if (method_exists($this->gtmClass, 'getPushData')) {
            return $this->gtmClass->getPushData($this);
        }

        return null;
    }
}
