<?php

declare(strict_types=1);

namespace External\PompoBundle\Overrides\Ordering;

use External\PompoBundle\Util\ProductUtil;
use KupShop\OrderingBundle\Entity\Purchase\ProductPurchaseItem;
use KupShop\OrderingBundle\Entity\Purchase\PurchaseState;
use Symfony\Contracts\Service\Attribute\Required;

class PurchaseUtil extends \KupShop\OrderingBundle\Util\Purchase\PurchaseUtil
{
    #[Required]
    public ProductUtil $pompoProductUtil;

    public function getProductsApplicableByProductsFilter(PurchaseState $purchaseState, $filter): array
    {
        $result = parent::getProductsApplicableByProductsFilter($purchaseState, $filter);

        if (($filter['only_not_discounted'] ?? 'N') === 'Y') {
            $products = $purchaseState->createProductCollection();
            $this->pompoProductUtil->fetchAdditionalPrices($products);

            // pokud filtruju pouze nezlevnene produkty, tak odfiltruju pryc i produkty, ktere maji
            // - dmocDiscount - sleva, ktera neni vyjadrena procenty a ma se brat jako sleva
            // - vipSavingsPrice - pokud mam aktivni cenik pro registrovane a neco mi to setri, tak se to bere jako sleva
            $result = array_filter(
                $result,
                fn (ProductPurchaseItem $item) => !($item->getProduct()->dmocDiscount ?? null)?->isPositive() && !($item->getProduct()->vipSavingsPrice ?? null)
            );
        }

        return $result;
    }
}
