<?php

use KupShop\KupShopBundle\Util\ArrayUtil;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\KupShopBundle\Util\Contexts;
use KupShop\SellerBundle\Context\SellerContext;
use KupShop\SellerBundle\Utils\SellerMultiFetch;
use KupShop\SellerBundle\Utils\SellerUtil;

function smarty_function_get_sellers($params, &$smarty)
{
    $sellerContext = Contexts::get(SellerContext::class);
    $sellers = $sellerContext->getSupported();

    $sellerUtil = ServiceContainer::getService(SellerUtil::class);
    $multiFetch = ServiceContainer::getService(SellerMultiFetch::class);

    if (($params['products'] ?? false) || ($params['cart'] ?? false)) {
        if (empty($params['with_disabled'])) {
            // odeberu prodejny, na ktere nejde objednavat
            $sellers = array_filter($sellers, fn ($x) => !$x['is_ordering_disabled']);
        }

        if ($params['cart'] ?? false) {
            $cart = ServiceContainer::getService(\KupShop\OrderingBundle\Cart::class);
            $sellerUtil->loadSellersDeliveryInfoByPurchaseState($cart->getPurchaseState(), $sellers);
        } else {
            $multiFetch->fetchSellersInStore($sellers, $params['products']);
            $sellerUtil->loadSellersDeliveryDate($sellers, []);
        }
    }

    if ($params['orderBy'] ?? false) {
        foreach ($sellers as &$seller) {
            $seller['orderByIndex'] = ArrayUtil::searchInArray($seller, explode('/', $params['orderBy']), null) ?: (1000 + $seller['id']);
        }

        usort($sellers, fn ($a, $b) => $a['orderByIndex'] <=> $b['orderByIndex']);
    }

    if ($params['groupBy'] ?? false) {
        $sellers = $sellerUtil->sellersGroupBy($sellers, $params['groupBy']);
    }

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