<?php

use External\HannahBundle\Util\ProductUtil;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

function smarty_function_get_store_delivery_time($params, &$smarty)
{
    if (empty($params['id_store'])) {
        throw new InvalidArgumentException('Invalid use of \'get_store_delivery_time\' - parameter \'id_store\' is missing');
    }

    if (empty($params['id_product']) && empty($params['cart'])) {
        throw new InvalidArgumentException('Invalid use of \'get_store_delivery_time\' - parameter \'id_product\' or \'cart\' is missing');
    }

    $productUtil = ServiceContainer::getService(ProductUtil::class);

    if (!empty($params['id_product'])) {
        $productId = (int) $params['id_product'];
        $variationId = null;
        if (!empty($params['id_variation'])) {
            $variationId = (int) $params['id_variation'];
        }

        $deliveryTime = $productUtil->getStoreDeliveryTime([$productId => $variationId], (int) $params['id_store']);
    } else {
        /** @var \KupShop\OrderingBundle\Cart $cart */
        $cart = $params['cart'];

        static $products;

        if (!$products) {
            foreach ($cart['products'] ?? [] as $item) {
                $products[$item['id_product']] = $products[$item['id_product']] ?? null;
                if ($item['id_variation']) {
                    $products[$item['id_product']][] = $item['id_variation'];
                }
            }
        }

        $deliveryTime = $productUtil->getStoreDeliveryTime((array) $products, (int) $params['id_store']);
    }

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