<?php

/*
 * Smarty plugin
 * -------------------------------------------------------------
 * Type:     function
 * Name:     get_contexts
 * Purpose:  get given contexts
 * -------------------------------------------------------------
 */

use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

/**
 * @param array  $params
 * @param Smarty $smarty
 *
 * @return string
 *
 * @throws Exception
 */
function smarty_function_get_gtm_data($params, &$smarty)
{
    $dbcfg = Settings::getDefault();

    // Tohle se volá z X šablon při FE eventách, proto je potřeba to kontrolovat i tady.
    // Aby se nespouštěly nový eventy s novejma datama, i když shop běží na starý verzi.
    if ($dbcfg['analytics']['google_tag_manager']['gtm_dl_version'] == 2
        || (getAdminUser() && $dbcfg['analytics']['google_tag_manager']['gtm_dl_version'] == 1)
        || findModule(Modules::COMPONENTS)
    ) {
        $GTMService = ServiceContainer::getService(\KupShop\GTMBundle\Utils\GTMLoader::class);
        $view = $smarty->getTemplateVars('view');
        $data = '';
        if (!empty($params['type']) && $params['type'] == 'ecommerce') {
            if (!empty($params['method'])) {
                $data = $GTMService->getEcommerceData($params['method'], $params['data'], $view);
            }
        } else {
            if (!empty($view) && $view instanceof \KupShop\KupShopBundle\Views\View) {
                $data = $GTMService->getData($view);
            }
        }
    } else {
        $data = [];
    }

    if ($params['method'] == 'Purchase') {
        $logger = ServiceContainer::getService('logger');
        $logger->notice('GTM Purchase object', [
            'data' => $data,
        ]);
    }

    if (is_array($data)) {
        $data['once'] = $params['once'] ?? false;
    }

    if ($params['encode'] ?? false) {
        $data = json_encode($data, JSON_NUMERIC_CHECK | JSON_HEX_APOS);
    }

    if (!empty($params['assign'])) {
        $smarty->assign($params['assign'], $data);
    } else {
        return $data;
    }
}
