<?php

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

function smarty_function_get_incremented_delivery_date($params, &$smarty)
{
    if (empty($params['date'])) {
        throw new InvalidArgumentException('Missing \'date\' parameter');
    }

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

    $date = $params['date'];
    if (!($date instanceof DateTime)) {
        $date = new DateTime($date);
    }

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

    // najit increment podle id produktu a varianty
    if (!empty($params['id_product'])) {
        $productId = (int) $params['id_product'];
        $variationId = null;
        if (!empty($params['id_variation'])) {
            $variationId = (int) $params['id_variation'];
        }

        $increment = $productUtil->getDateIncrement([$productId => $variationId], min: true);
    } else {
        /** @var \KupShop\OrderingBundle\Cart $cart */
        $cart = $params['cart'];

        static $cartDateIncrement;

        if (!$cartDateIncrement) {
            $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'];
                }
            }

            $cartDateIncrement = $productUtil->getDateIncrement($products);
        }

        $increment = $cartDateIncrement;
    }

    $result = DateUtil::calcWorkingDays($increment, $date);

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