<?php

/*
 * Smarty plugin
 * -------------------------------------------------------------
 * Type:     function
 * Name:     eval
 * Purpose:  evaluate a template variable as a template
 * -------------------------------------------------------------
 */

use Query\Operator;
use Query\QueryBuilder;

function smarty_function_insert_products_sets_cart($params, &$smarty)
{
    if (empty($params['note']['sets'])) {
        trigger_error('products sets: missing note in cart!');

        return;
    }
    $product_ids = [];
    $variations_id = [];
    foreach ($params['note']['sets'] as $product) {
        $product_ids[] = $product['id_product'];
        if ($product['id_variation']) {
            $variations_id[] = $product['id_variation'];
        }
    }

    $productList = new ProductList(true);
    $productList->andSpec(function (QueryBuilder $qb) use ($product_ids, $variations_id) {
        $qb->andWhere(\Query\Product::productsIds($product_ids))
            ->andWhere(Operator::orX('pv.id IS NULL', Operator::inIntArray($variations_id, 'pv.id')));
    });

    if (findModule('products_variations_photos')) {
        $productList->fetchImages(3, null, true);
    } else {
        $productList->fetchImages(3);
    }

    $data = [
        'set_products' => $productList->getProducts(),
    ];

    $_smarty_tpl_vars = $smarty->tpl_vars;

    echo $smarty->_subTemplateRender('product.sets.cart.tpl', $smarty->cache_id, $smarty->compile_id, 0, null, $data, 0, false);

    $smarty->tpl_vars = $_smarty_tpl_vars;
}
