<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

use Shopware\Models\Shop\Shop;
use Shopware\Plugins\ViisonCommon\Classes\Util\Util as ViisonCommonUtil;

/**
 * Function to get access to the Enlight2 Config system.
 *
 * The params array knows the key
 * - name    : Name of the config parameter which should be requested
 * - default : Default value if the queried config key does not exists
 */
// phpcs:ignore
class Smarty_Compiler_Config extends Smarty_Internal_CompileBase
{
    /**
     * Array of names of required attribute required by tag
     *
     * @var array
     */
    public $required_attributes = ['name'];

    /**
     * Attribute definition: Overwrites base class.
     *
     * @var array
     * @see Smarty_Internal_CompileBase
     */
    public $optional_attributes = [
        'default',
        'namespace',
    ];

    /**
     * Shopwares original config compiler uses the "current" shop of the context. That is - when called via shopware
     * backend - the main shop, even if you create a document for an order of a sub-shop. (bad)
     *
     * This config compiler uses the config of a shop that can be passed via the template context variable
     * ('viisonConfigShop'). This way we can use the "correct" shop config when handling sub-shop templates in the
     * backend. (good)
     *
     * @param $args
     * @param $compiler
     * @return string
     */
    public function compile($args, $compiler)
    {
        $attributes = $this->getAttributes($compiler, $args);

        if (!Shopware()->Container()->has('config')) {
            if (!isset($attributes['default'])) {
                $attributes['default'] = 'null';
            }

            return '<?php echo ' . $attributes['default'] . '; ?>';
        }

        // Fetch correct sub-shop config if the variable 'viisonConfigShop' was provided in the template context.
        $configShopVariable = $compiler->template->getVariable('viisonConfigShop');
        $configShop = $configShopVariable ? $configShopVariable->value : null;
        $config = ($configShop instanceof Shop) ? ViisonCommonUtil::getShopConfig($configShop) : Shopware()->Container()->get('config');

        /**
         * We are not sure why you would ever step into this block. But since we overwrite the Shopware compiler
         * globally, we keep this original code block to not break anything.
         */
        if (!preg_match('/^([\'"]?)[a-zA-Z0-9]+(\\1)$/', $attributes['name'], $match)) {
            $return = $attributes['name'];
            if (isset($attributes['default'])) {
                $return .= ', ' . $attributes['default'];
            }
            if (isset($attributes['namespace'])) {
                return '<?php echo Shopware()->Config()->getByNamespace(' . $attributes['namespace'] . ', ' . $return . '); ?>';
            }

            return '<?php echo Shopware()->Config()->get(' . $return . '); ?>';
        }

        // Remove single quotes ('shopName' to shopName)
        $name = mb_substr($attributes['name'], 1, -1);
        if (isset($attributes['namespace'])) {
            $namespace = mb_substr($attributes['namespace'], 1, -1);
            $value = $config->getByNamespace($namespace, $name);
        } else {
            $value = $config->get($name);
        }

        if ($value !== null) {
            return '<?php echo ' .  var_export($value, true) . ';?>';
        }
        if (isset($attributes['default'])) {
            return '<?php echo ' .  $attributes['default'] . ';?>';
        }

        return null;
    }
}
