<?php

/**
 * Created by PhpStorm.
 * User: ondra
 * Date: 28.11.17
 * Time: 15:45.
 */

namespace KupShop\QuantityDiscountBundle\EventListener;

use KupShop\I18nBundle\Util\PriceConverter;
use KupShop\KupShopBundle\Context\CurrencyContext;
use KupShop\KupShopBundle\Util\Contexts;
use KupShop\OrderingBundle\Event\OrderItemEvent;
use KupShop\QuantityDiscountBundle\Util\QuantityDiscountPrice;
use KupShop\QuantityDiscountBundle\Util\QuantityDiscountUtil;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class OrderItemListener implements EventSubscriberInterface
{
    public function __construct(
        private QuantityDiscountPrice $quantityDiscountPrice,
        private ?PriceConverter $priceConverter,
    ) {
    }

    public static function getSubscribedEvents(): array
    {
        return [
            OrderItemEvent::CALCULATE_PRICE => [
                ['setPrice', 200],
            ],
        ];
    }

    public function setPrice(OrderItemEvent $event)
    {
        $value = $event->getPrice();

        if ($discount = $this->quantityDiscountPrice->getDiscount($event->getProduct()->id, toDecimal($event->getPieces()), $event->getVariationId())) {
            if ($discount['discount_type'] == QuantityDiscountUtil::DISCOUNT_TYPE_PERC) {
                $value = $value->addDiscount($discount['discount']);
            } else {
                // $value is always in default currency when CALCULATE_PRICE event is triggered, so convert discount value to default currency
                $discountValue = $this->priceConverter?->convert(
                    $discount['discount_type'],
                    Contexts::get(CurrencyContext::class)->getDefault(),
                    $discount['discount']
                ) ?: toDecimal($discount['discount']);

                $value = $value->sub($discountValue);
            }
        }

        $event->setPrice($value);
    }
}
