<?php

use KupShop\ContentBundle\Util\Block;
use KupShop\ContentBundle\Util\InlineEdit;
use KupShop\I18nBundle\Translations\ProducersTranslation;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

function smarty_function_get_producer($params, &$smarty)
{
    if (empty($params['id_producer'])) {
        throw new InvalidArgumentException('Parameter \'id_producer\' is missing');
    }

    $producer = sqlQueryBuilder()->select('pr.*')
        ->from('producers', 'pr')
        ->where(\Query\Operator::equals(['pr.id' => $params['id_producer']]))
        ->andWhere(\Query\Translation::coalesceTranslatedFields(ProducersTranslation::class, ['data' => 'data_translated']))
        ->execute()->fetch();

    $producer['data'] = array_replace_recursive(json_decode($producer['data'], true) ?: [], json_decode($producer['data_translated'], true) ?: []);

    if ($producer['id_block'] ?? false) {
        $blockUtils = ServiceContainer::getService(Block::class);
        $inlineEdit = ServiceContainer::getService(InlineEdit::class);
        $blockList = $blockUtils->getBlocks($producer['id_block']);
        $object_info = json_encode([
            'type' => 'producer',
            'id' => $params['id_producer'],
            'name' => (translate('objects', 'blocks', false, true)['producer'] ?? 'producer').': '.$producer['name'],
        ]);

        $producer['blocks'] = [];
        foreach ($blockList as $block) {
            $block['object_info'] = $object_info;
            $producer['blocks'][] = $inlineEdit->wrapBlock($block);
        }

        $producer['descr'] = join('', array_column($producer['blocks'], 'content'));
    } else {
        $row['blocks'] = [];
        $producer['descr'] = '';
    }

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