<?php

namespace FiloBlu\Rma\Helper;

use Exception;
use FiloBlu\Rma\Api\ChangeSizeRepositoryInterface;
use FiloBlu\Rma\Model\OrderLocator;
use FiloBlu\Rma\Model\ResourceModel\Carrier\RateFactory;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Quote\Model\Quote\Address\RateRequestFactory;
use Magento\Sales\Api\Data\OrderAddressInterface;
use Magento\Store\Api\Data\StoreInterface;
use Magento\Store\Model\ScopeInterface;
use Throwable;

/**
 *
 */
class ChangeSizeHelper extends AbstractHelper
{
    /**
     * @var ChangeSizeRepositoryInterface
     */
    protected $changeSizeRepository;
    /**
     * @var ChangeSizeAttributeHelper
     */
    protected $changeSizeAttributeHelper;
    /**
     * @var OrderLocator
     */
    protected $orderLocator;
    /**
     * @var Context
     */
    protected $context;

    /**
     * @var RateRequestFactory
     */
    private $rateRequestFactory;

    /**
     * @var \FiloBlu\Rma\Model\ResourceModel\Carrier\RateFactory
     */
    private $easyReturnRateFactory;

    /**
     * @param \Magento\Quote\Model\Quote\Address\RateRequestFactory $rateRequestFactory
     * @param \FiloBlu\Rma\Model\ResourceModel\Carrier\RateFactory $easyReturnRateFactory
     * @param \Magento\Framework\App\Helper\Context $context
     * @param \FiloBlu\Rma\Api\ChangeSizeRepositoryInterface $changeSizeRepository
     * @param \FiloBlu\Rma\Helper\ChangeSizeAttributeHelper $changeSizeAttributeHelper
     * @param \FiloBlu\Rma\Model\OrderLocator $orderLocator
     */
    public function __construct(
        RateRequestFactory $rateRequestFactory,
        RateFactory $easyReturnRateFactory,
        Context $context,
        ChangeSizeRepositoryInterface $changeSizeRepository,
        ChangeSizeAttributeHelper $changeSizeAttributeHelper,
        OrderLocator $orderLocator
    ) {
        parent::__construct($context);
        $this->rateRequestFactory = $rateRequestFactory;
        $this->easyReturnRateFactory = $easyReturnRateFactory;
        $this->changeSizeRepository = $changeSizeRepository;
        $this->changeSizeAttributeHelper = $changeSizeAttributeHelper;
        $this->orderLocator = $orderLocator;
        $this->context = $context;
    }

    /**
     * @param OrderAddressInterface $address
     * @param StoreInterface $store
     * @param float $weight
     * @param float $orderTotal
     * @param int $taxPercentage
     * @param string $type
     * @param string $returnType
     * @param null $orderId
     * @return mixed
     */
    public function simulateChangeSizeShippingCost(
        OrderAddressInterface $address,
        StoreInterface $store,
        float $weight,
        float $orderTotal = 0,
        $taxPercentage = 0,
        $type = 'price',
        $returnType = 'easy_return',
        $orderId = null//refilo only
    )
    {
        $shippingAmounts [] = 0.00;

        //MNTFOS-151
        $order = $this->orderLocator->getCurrentOrder();
        if ($order) {
            $countryId = $order->getShippingAddress()->getCountryId();
        } else {
            $countryId = $address->getCountryId();
        }

        $request = $this->rateRequestFactory->create();
        $request->setDestCountryId($countryId);
        $request->setDestRegionId($address->getRegionId());
        $request->setDestPostcode($address->getPostcode());
        $request->setDestCity($address->getCity());
        $request->setPackageWeight($weight);
        $request->setFreeMethodWeight($weight);
        $request->setPackageQty(1);
        $request->setStoreId($store->getId());
        $request->setWebsiteId($store->getWebsiteId());
        $request->setLimitCarrier(null);
        $request->setFreeShipping(null);

        //Set additional data that will be used for
        $request->setData('order_total', $orderTotal);
        $request->setData('tax_percentage', $taxPercentage);
        //get rates for the matrixrate request created
        $matrixRate = $this->easyReturnRateFactory->create();
        $result = $matrixRate->collectRates($request);
        if ($result) {
            $rates = $result->getAllRates();
            if (!empty($rates)) {
                foreach ($rates as $rate) {
                    $price = $rate->getData($type);
                    if (isset($price) && $price > 0) {
                        $shippingAmounts[] = $price;
                    }
                }
            }
        }
        return max($shippingAmounts);
    }

    /**
     * @param null $storeId
     * @return bool
     */
    public function isChangeSizeEnabled($storeId = null)
    {
        return $this->scopeConfig->isSetFlag(
            ChangeSizeAttributeHelper::CHANGE_SIZE_OPTION_ENABLE,
            ScopeInterface::SCOPE_STORE,
            $storeId
        );
    }

    /**
     * @param $rmaId
     * @return bool
     */
    public function isChangeSize($rmaId)
    {
        try {
            if ($rmaId) {
                return (bool)$this->changeSizeRepository->getByRmaId($rmaId)->getId();
            }

            return false;
        } catch (Exception $exception) {
            $this->_logger->critical($exception->getMessage(), ['exception' => $exception]);
            return false;
        } catch (Throwable $throwable) {
            $this->_logger->critical($throwable->getMessage(), ['exception' => $throwable]);
            return false;
        }
    }

}
