<?php

use KupShop\ContentBundle\Util\Block;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use Query\Operator;

function smarty_function_insert_product_descr_plus($params, &$smarty)
{
    if (!isset($params['id_product'])) {
        throw new InvalidArgumentException('Missing parameter \'id_product\'');
    }

    $param_defaults = [
        'template' => 'block.product.descr_plus.tpl',
    ];

    $params = array_merge($param_defaults, $params);

    $product = sqlQueryBuilder()->select('id_block, id, title')->from('products')->where(Operator::equals(['id' => $params['id_product']]))->execute()->fetch();
    $blockID = $product['id_block'] ?? null;
    if ($blockID) {
        $block = ServiceContainer::getService(Block::class);
        $blocks = $block->getBlocks($blockID);
        $object_info = json_encode([
            'type' => 'products',
            'id' => $product['id'],
            'name' => (translate('objects', 'blocks', false, true)['product'] ?? 'product').': '.$product['title'],
        ]);
        $params['blocks'] = array_map(function ($block) use ($object_info) {
            $block['object_info'] = $object_info;

            return $block;
        }, $blocks);
    } else {
        $params['blocks'] = [[
            'id_object' => $params['id_product'],
            'type' => 'products',
        ]];
    }

    $inlineEdit = ServiceContainer::getService(\KupShop\ContentBundle\Util\InlineEdit::class);
    $has_content = false;
    $params['blocks'] = array_map(function ($block) use ($inlineEdit, &$has_content) {
        $block = $inlineEdit->wrapBlock($block);

        if (!empty($block['unwrapped_content'] ?? $block['content'])) {
            $has_content = true;
        }

        return $block;
    }, $params['blocks']);

    $params['has_content'] = $has_content;

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

        return $params;
    }

    $_smarty_tpl_vars = $smarty->tpl_vars;
    echo $smarty->_subTemplateRender($params['template'], $smarty->cache_id, $smarty->compile_id, 0, null, $params, 0, false);
    $smarty->tpl_vars = $_smarty_tpl_vars;

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

    return null;
}
