<?php

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

function smarty_function_get_cart_items_counts($params, &$smarty)
{
    $cart = ServiceContainer::getService(\KupShop\OrderingBundle\Cart::class);

    $qb = sqlQueryBuilder()
            ->select('id_product, id_variation, SUM(pieces) as pieces')
            ->from('cart')
            ->where(Operator::equals($cart->getSelectParams()))
            ->groupBy('id_product, id_variation');

    if ($params['id_product'] ?? false) {
        $qb->andWhere(Operator::equals(['id_product' => $params['id_product']]));
    }

    $result = [];
    foreach ($qb->execute() as $item) {
        $id = $item['id_product'];
        if ($item['id_variation']) {
            $id .= '_'.$item['id_variation'];

            if (($result[$item['id_product']] ?? false) === false) {
                $result[$item['id_product']] = 0;
            }

            // suma variant
            $result[$item['id_product']] += (float) $item['pieces'];
        }

        $result[$id] = (float) $item['pieces'];
    }

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