<?php

declare(strict_types=1);

namespace FiloBlu\Refilo\Model;

use Magento\Directory\Model\CurrencyFactory;
use Magento\Directory\Model\PriceCurrency as ModelPriceCurrency;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Pricing\PriceCurrencyInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\Store\Model\StoreManagerInterface;
use Psr\Log\LoggerInterface as Logger;

class PriceCurrency extends ModelPriceCurrency
{

    /** @var string */
    public const XML_REFILO_SALES_ENABLE_SALES_ORDER_PRICE_ROUNDING = 'refilo_sales/sales_order_price_rounding/enable_sales_order_price_rounding';
    /** @var string */
    public const XML_REFILO_SALES_RULE_PRICE_ROUNDING_DECIMAL = 'refilo_sales/sales_order_price_rounding/sales_order_price_rouding_decimal';
    /** @var string */
    public const XML_REFILO_SALES_RULE_PRICE_ROUNDING_STRATEGY = 'refilo_sales/sales_order_price_rounding/sales_order_price_rouding_strategy';

    /**
     * @var ScopeConfigInterface
     */
    private $scopeConfig;

    /**
     * @var \FiloBlu\Refilo\Model\RoundingStrategyProvider
     */
    private $roundingStrategyProvider;

    /**
     * @param StoreManagerInterface $storeManager
     * @param CurrencyFactory $currencyFactory
     * @param Logger $logger
     * @param ScopeConfigInterface $scopeConfig
     */
    public function __construct(
        StoreManagerInterface $storeManager,
        CurrencyFactory $currencyFactory,
        Logger $logger,
        ScopeConfigInterface $scopeConfig,
        RoundingStrategyProvider $roundingStrategyProvider
    )
    {
        $this->scopeConfig = $scopeConfig;
        $this->roundingStrategyProvider = $roundingStrategyProvider;
        parent::__construct(
            $storeManager,
            $currencyFactory,
            $logger
        );
    }

    public function round($price)
    {
        if(!$this->scopeConfig->isSetFlag(self::XML_REFILO_SALES_ENABLE_SALES_ORDER_PRICE_ROUNDING, ScopeInterface::SCOPE_WEBSITE)) {
            return $this->roundingStrategyProvider->getDefault()
                ->round($price, PriceCurrencyInterface::DEFAULT_PRECISION);
        }

        $strategy = $this->scopeConfig
            ->getValue(self::XML_REFILO_SALES_RULE_PRICE_ROUNDING_STRATEGY, ScopeInterface::SCOPE_WEBSITE);
        $decimals = (int)$this->scopeConfig
            ->getValue(self::XML_REFILO_SALES_RULE_PRICE_ROUNDING_DECIMAL, ScopeInterface::SCOPE_WEBSITE);

        return $this->roundingStrategyProvider->get($strategy)->round($price, $decimals);
    }
}
