<?php

use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\KupShopBundle\Util\Functional\Mapping;
use KupShop\SellerBundle\Context\SellerContext;

function smarty_function_get_grouped_stores($params, &$smarty)
{
    $stores = $params['stores'] ?? [];

    $sellerContext = ServiceContainer::getService(SellerContext::class);
    $sellers = $sellerContext->getSupported();

    $sellersByStoreId = Mapping::mapKeys($sellers, fn ($k, $v) => [$v['id_store'], (int) $v['id']]);

    $result = [];
    foreach ($stores as $id => $store) {
        $link = null;
        if ($sellerId = ($sellersByStoreId[$id] ?? false)) {
            $link = path('shop_seller_seller_detail', ['id_seller' => $sellerId]);
        }

        $city = $sellers[$sellerId]['data']['city'] ?? 'Ostatní';

        $result[$city][$id] = array_merge($store, [
            'link' => $link,
        ]);
    }

    ksort($result);

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