<?php

use External\PompoBundle\Util\Ordering\OrderingUtil;
use External\PompoBundle\Util\ProductUtil;
use KupShop\CatalogBundle\ProductList\ProductCollection;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\OrderingBundle\Entity\Purchase\ProductPurchaseItem;
use KupShop\OrderingBundle\Entity\Purchase\PurchaseState;
use KupShop\OrderingBundle\Util\Purchase\PurchaseUtil;

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

    /** @var Product $product */
    $product = $params['product']->getProduct();

    $productCollection = $product->_pompoProductCollection ?? new ProductCollection([$product->id => $product]);

    $productUtil = ServiceContainer::getService(ProductUtil::class);
    $productUtil->fetchStoreInfo($productCollection);
    $productUtil->fetchAdditionalPrices($productCollection);

    $orderingUtil = ServiceContainer::getService(OrderingUtil::class);

    $result = [
        'inStoreMain' => $product->inStoreMain ?? 0,
        'inStoreSupplier' => $product->inStoreSupplier ?? 0,
        'inStoreSeller' => $product->inStoreSeller ?? 0,
        'inStoreSellerOther' => $product->inStoreSellerOther ?? 0,
        'userVipPrice' => $product->userVipPrice ?? null,
        'dmocPrice' => $product->dmocPrice ?? null,
        'dmocDiscount' => $product->dmocDiscount ?? null,
        'vipOriginalPrice' => $product->vipOriginalPrice ?? null,
        'vipSavingsPrice' => $product->vipSavingsPrice ?? null,
        'sellerWithTransferDeliveryExists' => $orderingUtil->hasProductWithInPersonTransferDelivery(createProductInfoPurchaseState($product)),
    ];

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

function createProductInfoPurchaseState(Product $product): PurchaseState
{
    $purchaseState = new PurchaseState([
        new ProductPurchaseItem($product->id, null, 1, $product->getProductPrice(), null),
    ]);

    return ServiceContainer::getService(PurchaseUtil::class)->recalculateTotalPrices($purchaseState);
}
