<?php

declare(strict_types=1);

namespace KupShop\KupShopBundle\PriceType;

use KupShop\ContentBundle\Entity\ProductUnified;
use KupShop\KupShopBundle\DiscountFieldDefinition\DiscountFieldDefinitionInterface;
use KupShop\KupShopBundle\DiscountFieldDefinition\ExplicitDiscountFieldDefinition;
use KupShop\KupShopBundle\DiscountFieldDefinition\PriceForDiscountFieldDefinition;
use KupShop\KupShopBundle\Util\Price\Price;

class PriceForDiscountPriceType extends AbstractPriceType
{
    public function __construct()
    {
        $this->setFallback(new PriceWithoutDiscountPriceType());
    }

    public function getPrice(ProductUnified $product): ?Price
    {
        $price = $product->getPriceForDiscount();
        if (!$this->isProductDiscountActive($product) || ($price && $price->getValue()->isNegative())) {
            // na produktu neni nastavena sleva a v takovou chvili nechci zobrazovat CPS (nastaveni v adminu: Cena po slevě aktivuje zobrazení slevy)
            // nebo CPS deaktivovana (price_for_discount = -1)
            $price = $this->applyFallback($product);
        }

        return $price;
    }

    public function getDiscountFieldDefinition(): DiscountFieldDefinitionInterface
    {
        if ((\Settings::getDefault()['prod_display_discount'] ?? 'N') === 'Y') {
            return new ExplicitDiscountFieldDefinition(
                new PriceForDiscountFieldDefinition()
            );
        }

        return new PriceForDiscountFieldDefinition();
    }

    /**
     * Checks for prod_display_discount (Cena po slevě aktivuje zobrazení slevy) setting.
     */
    private function isProductDiscountActive(ProductUnified $product): bool
    {
        if ((\Settings::getDefault()['prod_display_discount'] ?? 'N') === 'Y') {
            return $product->getDiscount()->isPositive();
        }

        return true;
    }
}
