<?php

namespace KupShop\OrderingBundle\Entity\Purchase;

use KupShop\KupShopBundle\Util\Price\Price;
use KupShop\OrderingBundle\Util\Order\OrderItemInfo;

class TextPurchaseItem extends AbstractPurchaseItem
{
    public $name;
    public $pieces;
    public $price;
    public ?array $note;
    public $vat;
    private $id_discount;
    public $discounts = [];
    protected $id;

    protected $type = OrderItemInfo::TYPE_TEXT;

    public function __construct($name, $pieces, Price $price, $vat, ?array $note = null, $id_discount = null)
    {
        $this->name = $name;
        $this->pieces = $pieces;
        $this->price = $price;
        $this->note = $note;
        $this->vat = $vat;
        $this->id_discount = $id_discount;
    }

    public function getIdProduct()
    {
        return null;
    }

    public function getIdVariation()
    {
        return null;
    }

    public function getPieces()
    {
        return $this->pieces;
    }

    public function getVat()
    {
        return $this->vat;
    }

    public function getName()
    {
        return $this->name;
    }

    public function getPriceWithVat(): \Decimal
    {
        return $this->price->getPriceWithVat();
    }

    public function getPriceWithoutVat(): \Decimal
    {
        return $this->getPriceWithVat()->removeVat($this->price->getVat());
    }

    public function getPiecePriceWithVat(): \Decimal
    {
        return $this->getPriceWithVat()->div(toDecimal($this->getPieces()));
    }

    public function getPiecePriceWithoutVat(): \Decimal
    {
        return $this->getPriceWithoutVat()->div(toDecimal($this->getPieces()));
    }

    public function getPriceWithDiscounts(): Price
    {
        if (!$this->getDiscounts()) {
            return $this->priceWithDiscounts = $this->price;
        }

        $price = $this->getPriceWithVat();

        foreach ($this->discounts as $discount) {
            $discountPrice = $discount['discountPrice']->addVat($this->price->getVat())->mul(toDecimal($this->pieces));
            $price = $price->sub($discountPrice, 2);
            // $price = roundPrice($price, null, null, null, $this->price->getCurrency());
        }

        $this->priceWithDiscounts = new Price(
            $price->removeVat($this->price->getVat()), $this->price->getCurrency(), $this->price->getVat()
        );

        return $this->priceWithDiscounts;
    }

    public function getPriceWithDiscountsWithVat(): \Decimal
    {
        // cenu po sleve vzdy zaokrouhlit na haléře
        return $this->getPriceWithDiscounts()->getPriceWithVat(false)->value(2);
    }

    public function getIdDiscount()
    {
        return $this->id_discount;
    }

    public function getDiscounts()
    {
        return $this->discounts;
    }

    public function addDiscount($discount)
    {
        $this->discounts[] = $discount;
    }

    public function addNote(string $key, $value): self
    {
        $this->note[$key] = $value;

        return $this;
    }
}
