<?php
/**
 * Mageplaza
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Mageplaza.com license that is
 * available through the world-wide-web at this URL:
 * https://www.mageplaza.com/LICENSE.txt
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade this extension to newer
 * version in the future.
 *
 * @category    Mageplaza
 * @package     Mageplaza_EditOrder
 * @copyright   Copyright (c) Mageplaza (https://www.mageplaza.com/)
 * @license     https://www.mageplaza.com/LICENSE.txt
 */

namespace Mageplaza\EditOrder\Block\Adminhtml\Order\Edit;

use Magento\Backend\Block\Template\Context;
use Magento\Backend\Model\Session\Quote;
use Magento\Checkout\Model\Session as checkoutSession;
use Magento\Directory\Model\CurrencyFactory;
use Magento\Framework\Pricing\PriceCurrencyInterface;
use Magento\Quote\Model\Quote\Address\Rate;
use Magento\Quote\Model\QuoteFactory;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Block\Adminhtml\Order\Create\Shipping\Method\Form;
use Magento\Sales\Model\AdminOrder\Create;
use Magento\Store\Model\ScopeInterface;
use Magento\Tax\Helper\Data;

class ShippingMethod extends Form
{
    /**
     * @var OrderRepositoryInterface
     */
    protected $orderRepository;

    /**
     * @var QuoteFactory
     */
    protected $quoteFactory;

    /**
     * @var checkoutSession
     */
    protected $checkoutSession;

    /**
     * @var CurrencyFactory
     */
    protected $currencyFactory;

    /**
     * ShippingMethod constructor.
     *
     * @param Context $context
     * @param Quote $sessionQuote
     * @param Create $orderCreate
     * @param PriceCurrencyInterface $priceCurrency
     * @param Data $taxData
     * @param OrderRepositoryInterface $orderRepository
     * @param QuoteFactory $quoteFactory
     * @param checkoutSession $checkoutSession
     * @param CurrencyFactory $currencyFactory
     * @param array $data
     */
    public function __construct(
        Context $context,
        Quote $sessionQuote,
        Create $orderCreate,
        PriceCurrencyInterface $priceCurrency,
        Data $taxData,
        OrderRepositoryInterface $orderRepository,
        QuoteFactory $quoteFactory,
        checkoutSession $checkoutSession,
        CurrencyFactory $currencyFactory,
        array $data = []
    ) {
        $this->checkoutSession = $checkoutSession;
        $this->orderRepository = $orderRepository;
        $this->quoteFactory    = $quoteFactory;
        $this->currencyFactory = $currencyFactory;

        parent::__construct($context, $sessionQuote, $orderCreate, $priceCurrency, $taxData, $data);
    }

    /**
     * @return string
     */
    public function getActionForm()
    {
        return $this->getUrl(
            'mpeditorder/shipping_method/save',
            [
                'form_key' => $this->getFormKey()
            ]
        );
    }

    /**
     * @return string
     */
    public function getEditShippingButtonUrl()
    {
        return $this->getUrl(
            'mpeditorder/shipping_method/listMethod',
            [
                'order_id'    => $this->getOrder()->getId(),
                'mpeditorder' => true,
                'form_key'    => $this->getFormKey()
            ]
        );
    }

    /**
     * @return string
     */
    public function getUrlOrder()
    {
        return $this->getUrl(
            'sales/order/view',
            [
                'order_id' => $this->getOrder()->getId(),
                'form_key' => $this->getFormKey()
            ]
        );
    }

    /**
     * @return OrderInterface
     */
    public function getOrder()
    {
        $orderId = $this->getRequest()->getParam('order_id') ?: $this->getOrderId();

        return $this->orderRepository->get($orderId);
    }

    /**
     * IsMethod Selected in Order
     *
     * @param string $code
     *
     * @return bool
     */
    public function isMethodActive($code)
    {
        return $code === $this->getOrder()->getShippingMethod();
    }

    /**
     * Get shipping amount
     *
     * @return float
     */
    public function getBaseTotalShippingFee()
    {
        $shipAmount   = $this->getBaseShippingAmount();
        $shipTax      = $this->getBaseShippingTaxPercent();
        $shipDiscount = $this->getBaseShippingDiscountAmount();
        $totalShipFee = $shipAmount + ($shipAmount * $shipTax) / 100 - $shipDiscount;

        return $totalShipFee;
    }

    /**
     * @return float|int
     */
    public function getBaseShippingAmount()
    {
        return $this->getOrder()->getBaseShippingAmount();
    }

    /**
     * @return float|int
     */
    public function getBaseShippingTaxPercent()
    {
        $baseShippingAmount = $this->getBaseShippingAmount();

        if ($baseShippingAmount != 0) { //prevent null and 0.0
            return $this->getOrder()->getBaseShippingTaxAmount() * 100 / $baseShippingAmount;
        }

        return 0;
    }

    /**
     * @return float|int|null
     */
    public function getBaseShippingDiscountAmount()
    {
        return $this->getOrder()->getBaseShippingDiscountAmount();
    }

    /**
     * @param Rate $rate
     *
     * @return array
     */
    public function getBaseShippingData($rate)
    {

        $isActiveInOrder = $this->isMethodActive($rate->getCode());
        $shippingExlTax  = $isActiveInOrder ? $this->getBaseShippingAmount()
            : $this->_taxData->getShippingPrice(
                $rate->getPrice(),
                false,
                $this->getQuote()->getShippingAddress()
            );
        $taxPercent      = $this->getTaxPercent($isActiveInOrder);
        $shippingInclTax = $shippingExlTax + $shippingExlTax * $taxPercent / 100;
        $discount        = $isActiveInOrder ? $this->getBaseShippingDiscountAmount() : 0;

        return [
            'ship_amount'          => $shippingExlTax,
            'ship_tax_percent'     => $taxPercent,
            'ship_discount_amount' => $discount,
            'total_fee'            => $shippingInclTax - $discount
        ];
    }

    /**
     * @param $isActiveInOrder
     *
     * @return float|int
     */
    public function getTaxPercent($isActiveInOrder)
    {
        if (!$this->isConfigApply()) {
            return 0;
        }
        if ($isActiveInOrder) {
            return $this->getBaseShippingTaxPercent();
        }

        $taxApplies = $this->getQuote()->getShippingAddress()->getAppliedTaxes();
        foreach ($taxApplies as $taxApply) {
            if (isset($taxApply['percent'])) {
                return (float) $taxApply['percent'];
            }
        }

        return 0;
    }

    /**
     * @return bool
     */
    private function isConfigApply()
    {
        $configPath = 'tax/classes/shipping_tax_class';

        return (bool) $this->_scopeConfig->getValue(
            $configPath,
            ScopeInterface::SCOPE_STORE
        );
    }

    /**
     * Get converted shipping data for multiple currencies
     *
     * @param Rate $rate
     *
     * @return array
     */
    public function getMultiCurrencyShippingData($rate)
    {
        $baseData      = $this->getBaseShippingData($rate);
        $baseRateOrder = $this->getOrder()->getBaseCurrencyCode();
        $currencyRate  = $this->getOrder()->getOrderCurrencyCode();
        $currencies    = [$currencyRate];
        $convertedData = [];

        foreach ($currencies as $currencyCode) {
            $currency = $this->currencyFactory->create()->load($baseRateOrder);
            $rate     = $currency->getAnyRate($currencyRate);

            $convertedData[$currencyCode] = [
                'ship_amount'          => $baseData['ship_amount'] * $rate,
                'ship_tax_percent'     => $baseData['ship_tax_percent'],
                'ship_discount_amount' => $baseData['ship_discount_amount'] * $rate,
                'total_fee'            => $baseData['total_fee'] * $rate
            ];
        }

        return $convertedData;
    }
}
