<?php

declare(strict_types=1);

namespace External\PompoBundle\EventSubscriber\Ordering;

use External\PompoBundle\Util\Configuration;
use External\PompoBundle\Util\Ordering\OrderingUtil;
use KupShop\OrderingBundle\Cart;
use KupShop\OrderingBundle\Event\PurchaseStateCreatedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class PurchaseStateSubscriber implements EventSubscriberInterface
{
    private Configuration $configuration;
    private OrderingUtil $orderingUtil;
    private Cart $cart;

    public function __construct(Configuration $configuration, OrderingUtil $orderingUtil, Cart $cart)
    {
        $this->configuration = $configuration;
        $this->orderingUtil = $orderingUtil;
        $this->cart = $cart;
    }

    public static function getSubscribedEvents(): array
    {
        return [
            PurchaseStateCreatedEvent::class => [
                ['purchaseStateCreated', 200],
            ],
        ];
    }

    public function purchaseStateCreated(PurchaseStateCreatedEvent $event): void
    {
        if (!$this->configuration->isPompo()) {
            return;
        }

        // Tohle je kvuli tomu, ze se nasobek bodu za neakcni lego nesmi pocitat, kdyz je aplikovana nejaka jina sleva
        // potrebujeme to ale nejak rict zakaznikovi, ze ztratil narok na ten nasobek, takze se to tady odetekuje, kdyz je pridanej poukaz
        // a vrati se hlaska, ze ztratil narok
        if (!empty($event->getPurchaseState()->getActiveCoupons()) && $event->getPurchaseState()->getDiscountsTotalPrice()->getPriceWithVat()->isNegative()) {
            if ($productCollection = $event->getPurchaseState()->createProductCollection()) {
                $productCollection->fetchProducers();
                $hasNotDiscountedLegoProductInCart = (bool) array_filter($event->getPurchaseState()->getProducts(), fn ($item) => !$item->getProduct()->discount->isPositive() && strpos(mb_strtolower($item->getProduct()->producer['name'] ?? ''), 'lego') !== false);
                if ($hasNotDiscountedLegoProductInCart) {
                    addUserMessage(translate('cart_pointMultiplicationLost', 'pompo'));
                }
            }
        }

        // Zpusob vyzvednuti je ulozenej v deliveryData - pokud se jedna o osobni odber
        $pickType = $this->cart->deliveryData['pickType'] ?? null;
        $sellerId = $this->cart->transport ? ($this->cart->deliveryData['seller_id'] ?? null) : null;

        // Nafetchuju dostupnosti produktu do kosiku, abych mohl zobrazovat, co je potreba zavest, co je skladem na prodejne atd...
        $this->orderingUtil->fetchPurchaseStateProductsAvailability(
            $event->getPurchaseState(),
            $sellerId ? (int) $sellerId : null,
            $pickType ? (string) $pickType : null
        );
    }
}
