<?php

namespace KupShop\OrderDiscountBundle\Actions;

use KupShop\OrderDiscountBundle\Entity\OrderDiscount;
use KupShop\OrderDiscountBundle\Util\DiscountUtil;
use KupShop\OrderingBundle\Entity\Purchase\DiscountPurchaseItem;
use KupShop\OrderingBundle\Entity\Purchase\PurchaseState;

class GlobalDiscountAction extends AbstractAction
{
    protected static $type = 'global_discount';
    protected static $position = 1;
    protected $adminTemplate = 'actions/global_discount.tpl';

    protected $discountUtil;

    public function __construct(DiscountUtil $discountUtil)
    {
        $this->discountUtil = $discountUtil;
    }

    public function applyResult(PurchaseState &$purchaseState, OrderDiscount $orderDiscount, array $data)
    {
        $this->messages = [];
        $total_price = $purchaseState->getProductsTotalPrice();
        $data['id'] = $orderDiscount->getId();
        $name = $orderDiscount->getDisplayName();
        $note = $this->createItemNote($data, $name);

        if ($this->getDivideDiscountPrice($data)) {
            $discountPrice = $this->discountUtil->divideDiscountPrice($purchaseState->getProducts(), $data, $name);
        } else {
            $discountPrice = $this->discountUtil->calculateDiscountPrice($total_price->getPriceWithVat(), $data, $name);
        }

        $this->addDiscountItem($discountPrice, $name, $data, $orderDiscount, $note, $purchaseState);
    }

    protected function addDiscountItem(?\Decimal $discountPrice, $name, array $data, OrderDiscount $orderDiscount, array $note, PurchaseState $purchaseState): void
    {
        if ($discountPrice) {
            if (is_null($data['vat'] ?? null)) {
                // uplatnit sazbu DPH podle produktů v objednávce
                $vatId = null;
                $forceVatValue = $purchaseState->getDeliveryVat();
            } else {
                $vatId = $data['vat'] ?? null;
                $forceVatValue = null;
            }
            $discountPurchaseItem = new DiscountPurchaseItem($name,
                $this->discountUtil->createDiscountPrice($discountPrice, $vatId, $forceVatValue), $orderDiscount->getId(), $note);
            $purchaseState->addDiscount($discountPurchaseItem);
            if ($message = $data['messages']['success'] ?? '') {
                $this->messages['success'] = $message;
            }
        } else {
            if ($message = $data['messages']['warning'] ?? '') {
                $this->messages['warning'] = $message;
            }
        }
    }

    /**
     * @return bool
     *
     * @throws \Exception
     */
    public function checkValidity(&$data)
    {
        if (!empty($data['discount']) && !empty($data['unit'])) {
            $data['discount'] = toDecimal($data['discount'])->asFloat();
            if ($data['discount']) {
                return true;
            }
        }

        throw new \Exception($this->getName().' ['.$this->getType().'] - data is not valid.');
    }

    protected function getVars($vars): array
    {
        $vars = parent::getVars($vars);

        $vars['vats'] = \KupShop\KupShopBundle\Context\VatContext::getAdminVats();

        return $vars;
    }
}
