<?php

/**
 * @param array                    $params
 * @param Smarty_Internal_Template $smarty
 */
function smarty_function_insert_recommender($params, $smarty)
{
    /*
    Examples
    category bestsellers:
    {insert_recommender label='bestsellers' data=[section => $body.category.id] template='block.products.related.tpl'}
    cart also bought:
    {insert_recommender label='cart-alsobought' data=[products => $body.products]}
    Luigi's Box Recommenders:
    category recommended:
    {insert_recommender label='luigisbox-trends' data=[category => $body.category.id] template='block.products.related.tpl'}
    cart cross-sell:
    {insert_recommender label='luigisbox-basket' data=[products => $body.products]}
    last visited:
    {insert_recommender label='luigisbox-last-visited' data=['count' => 10, 'image' => 'product_gallery']}
    */

    if (empty($params['label'])) {
        throw new InvalidArgumentException('Missing required parameter \'label\'');
    }

    $default = [
        'image' => 'product_catalog',
    ];

    $data = $params['data'] ?? [];
    if (!empty($data['products'])) {
        if ($data['products'] instanceof \KupShop\CatalogBundle\ProductList\ProductCollection) {
            $data['products'] = $data['products']->toArray();
        }
        $id_products = array_map(function ($x) {
            return $x['id'] ?? $x;
        }, $data['products']);
        $data['products'] = $id_products;
    }

    $params['data'] = array_replace_recursive($default, $data);

    $smarty->assign(['data' => json_encode($params)]);

    echo $smarty->fetch('block.recommender.tpl');
}
