<?php

use External\PompoBundle\Util\Ordering\OrderingUtil;
use KupShop\KupShopBundle\Context\CurrencyContext;
use KupShop\KupShopBundle\Util\Contexts;
use KupShop\KupShopBundle\Util\Price\Price;

function smarty_function_get_pompo_delivery_charge($params, &$smarty)
{
    $cacheKey = 'pompo_handling_charges';
    $currencyContext = Contexts::get(CurrencyContext::class);

    if (!($data = getCache($cacheKey))) {
        $qb = sqlQueryBuilder()
            ->select('currency, price, vat')
            ->from('charges')
            ->where(\Query\Operator::inIntArray(OrderingUtil::CHARGES_HANDLING_FEE, 'id'));

        $data = [];
        foreach ($qb->execute() as $item) {
            $data[$item['currency']] = new Price(
                toDecimal($item['price']),
                $currencyContext->getAll()[$item['currency']] ?? $currencyContext->getDefault(),
                getVat($item['vat'])
            );
        }

        setCache($cacheKey, $data);
    }

    $result = $data[$currencyContext->getActiveId()] ?? null;

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