<?php

namespace KupShop\ProductsChargesBundle\EventListener;

use KupShop\KupShopBundle\Util\Price\Price;
use KupShop\OrderingBundle\Entity\Purchase\ChargePurchaseItem;
use KupShop\OrderingBundle\Entity\Purchase\ProductPurchaseItem;
use KupShop\OrderingBundle\Event\PurchaseStateCreatedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class PurchaseStateListener implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [
            PurchaseStateCreatedEvent::class => [
                ['addProductCharges', 200],
            ],
        ];
    }

    public function addProductCharges(PurchaseStateCreatedEvent $event): void
    {
        foreach ($event->getPurchaseState()->getProducts() as $purchaseItem) {
            $this->addProductChargesToPurchaseItem(
                $purchaseItem,
                $purchaseItem->getProduct()->fetchCharges(
                    $purchaseItem->getNote()['charges'] ?? []
                )
            );
        }
    }

    private function addProductChargesToPurchaseItem(ProductPurchaseItem $purchaseItem, array $charges): void
    {
        foreach ($charges as $charge) {
            if (!($charge['included'] == 'N' && $charge['active'])) {
                continue;
            }

            /** @var Price $price */
            $price = $charge['price'];

            if (($charge['data']['onetime'] ?? 'N') === 'Y') {
                $chargePieces = \DecimalConstants::one();
            } else {
                $chargePieces = toDecimal($purchaseItem->getPieces());
            }

            $totalPrice = new Price($price->getPriceWithoutVat()->mul($chargePieces), $price->getCurrency(), $price->getVat());

            $purchaseItem->addAdditionalItem(
                new ChargePurchaseItem($charge['title'], $totalPrice, $charge['id'])
            );
        }
    }
}
