<?php

declare(strict_types=1);

namespace External\PompoBundle\Overrides\ProductList;

use External\PompoBundle\Util\Configuration;
use KupShop\CatalogBundle\ProductList\ProductCollection;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use Query\QueryBuilder;
use Symfony\Contracts\Service\Attribute\Required;

class MultiFetch extends \KupShop\CatalogBundle\ProductList\MultiFetch
{
    #[Required]
    public Configuration $configuration;

    public function fetchGifts(ProductCollection $products, $showOutOfStock = null): void
    {
        // darky k produktum chceme brat pouze z hlavniho skladu
        parent::fetchGifts($products, function (QueryBuilder $qb) {
            $qb->join('p', 'stores_items', 'si_gifts', 'si_gifts.id_product = p.id AND si_gifts.id_store = :mainStoreId')
                ->andWhere('si_gifts.quantity > 0')
                ->setParameter('mainStoreId', $this->configuration->getMainStoreId());
        });
    }

    public function fetchActiveSellerInStore(ProductCollection $products)
    {
        $productUtil = ServiceContainer::getService(\External\PompoBundle\Util\ProductUtil::class);

        $productUtil->fetchStoreInfo($products);

        $mergeData = [];

        foreach ($products as $product) {
            $mergeData[$product['id']] = [
                'in_store' => $product->inStoreSeller,
                'in_store_other' => $product->inStoreSellerOther,
                'in_store_main' => $product->inStoreMain,
            ];
        }

        $this->mergeToProductsCollection($products, 'activeSellerInStore', $mergeData);
    }
}
