<?php

declare(strict_types=1);

namespace External\PompoBundle\Ordering\Triggers;

use External\PompoBundle\Util\Configuration;
use External\PompoBundle\Util\Ordering\OrderingUtil;
use External\PompoBundle\Util\Ordering\OrderType;
use KupShop\OrderDiscountBundle\Entity\OrderDiscount;
use KupShop\OrderDiscountBundle\Triggers\AbstractTrigger;
use KupShop\OrderingBundle\Cart;
use KupShop\OrderingBundle\Entity\Purchase\PurchaseState;
use KupShop\SellerBundle\Utils\SellerUtil;
use Symfony\Contracts\Service\Attribute\Required;

class TransportChargeTrigger extends AbstractTrigger
{
    #[Required]
    public Cart $cart;
    #[Required]
    public OrderingUtil $orderingUtil;
    #[Required]
    public Configuration $configuration;

    public ?SellerUtil $sellerUtil = null;

    protected static $type = 'pompo_transport_charge';
    protected $adminTemplate = 'triggers/pompo_transport_charge.tpl';

    #[Required]
    public function setSellerUtil(?SellerUtil $sellerUtil): void
    {
        $this->sellerUtil = $sellerUtil;
    }

    public function getName()
    {
        return 'Manipulační poplatek';
    }

    public function getDescription()
    {
        return 'Pokud splňuje podmínky pro manipulační poplatek';
    }

    public function isApplicable(PurchaseState $purchaseState, OrderDiscount $orderDiscount, array $data, ?array $persistentData = null): bool
    {
        if (!getVal('OrderNext') && ($this->cart->actualStep === 'cart' || !$this->cart->delivery_id)) {
            return false;
        }

        // pokud je nasetovany sellerId
        if ($sellerId = ($this->cart->deliveryData['seller_id'] ?? false)) {
            $type = $this->orderingUtil->getPurchaseStateOrderType($purchaseState, (int) $sellerId);
            // pokud se jedna o rezervaci s prevozem, tak splnuju podminku pro manipulacni poplatek
            if ($type === OrderType::ORDER_TRANSPORT_RESERVATION) {
                $seller = $this->sellerUtil->getSeller((int) $sellerId);
                // pokud se jedna o prodejnu s hlavnim skladem, tak tam neni manipulacni poplatek
                if ($seller['id_store'] === $this->configuration->getMainStoreId()) {
                    return false;
                }

                return true;
            }
        }

        return false;
    }
}
