<?php

namespace FiloBlu\Storelocator\Model\Plugin\Rma;

use Exception;
use FiloBlu\Storelocator\Model\StoresFactory;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Framework\Translate\Inline\StateInterface;
use Magento\Payment\Helper\Data;
use Magento\Rma\Model\Rma as MagentoRma;
use Magento\Rma\Model\RmaFactory;
use Magento\Sales\Model\Order\Address\Renderer;
use Magento\Store\Model\Store;
use Magento\Sales\Model\Order\Address;
use Magento\Framework\Api\AttributeValueFactory;
use Magento\Rma\Api\RmaAttributesManagementInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Store\Model\StoreManagerInterface;
use Psr\Log\LoggerInterface;
use Magento\Framework\App\State;
use Throwable;

/**
 *
 */
class Rma
{
    /**
     * @var \FiloBlu\Storelocator\Helper\Data
     */
    protected $_helper;

    /**
     * @var StoresFactory
     */
    protected $_storesFactory;
    /**
     * @var \Magento\Rma\Helper\Data
     */
    protected $_rmaHelper;
    /**
     * @var TransportBuilder
     */
    protected $_transportBuilder;
    /**
     * @var StoreManagerInterface
     */
    protected $_storeManager;
    /**
     * @var StateInterface
     */
    protected $_inlineTranslation;
    /**
     * @var Data
     */
    protected $_paymentHelper;
    /**
     * @var Renderer
     */
    protected $_addressRenderer;
    /**
     * @var State
     */
    protected $state;
    protected $isReturnInStoreEnabled;
    /**
     * @var RequestInterface
     */
    private $request;
    /**
     * @var RmaFactory
     */
    private $rmaFactory;
    /**
     * @var \Magento\Rma\Model\ResourceModel\Rma
     */
    private $rma;
    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * Rma constructor.
     * @param \FiloBlu\Storelocator\Helper\Data $helper
     * @param StoresFactory $storesFactory
     * @param \Magento\Rma\Helper\Data $rmaHelper
     * @param TransportBuilder $transportBuilder
     * @param StoreManagerInterface $storeManager
     * @param StateInterface $inlineTranslation
     * @param Data $paymentHelper
     * @param Renderer $addressRenderer
     * @param RequestInterface $request
     * @param RmaFactory $rmaFactory
     * @param \Magento\Rma\Model\ResourceModel\Rma $rma
     * @param LoggerInterface $logger
     * @param State $state
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function __construct(
        \FiloBlu\Storelocator\Helper\Data $helper,
        StoresFactory $storesFactory,
        \Magento\Rma\Helper\Data $rmaHelper,
        TransportBuilder $transportBuilder,
        StoreManagerInterface $storeManager,
        StateInterface $inlineTranslation,
        Data $paymentHelper,
        Renderer $addressRenderer,
        RequestInterface $request,
        RmaFactory $rmaFactory,
        \Magento\Rma\Model\ResourceModel\Rma $rma,
        LoggerInterface $logger,
        State $state
    ) {
        $this->_helper = $helper;
        $this->_storesFactory = $storesFactory;
        $this->_rmaHelper = $rmaHelper;
        $this->_transportBuilder = $transportBuilder;
        $this->_storeManager = $storeManager;
        $this->_inlineTranslation = $inlineTranslation;
        $this->_paymentHelper = $paymentHelper;
        $this->_addressRenderer = $addressRenderer;
        $this->request = $request;
        $this->rmaFactory = $rmaFactory;
        $this->rma = $rma;
        $this->logger = $logger;
        $this->state = $state;

        $storeId = $this->_storeManager->getStore()->getId();

        $this->isReturnInStoreEnabled = $this->_helper->getReturnToStoreEnabled($storeId);
    }

    /**
     * @param \Magento\Rma\Model\Rma $subject
     * @param $data
     * @return array
     */
    public function beforeSaveRma(MagentoRma $subject, $data)
    {
        if (!$this->isReturnInStoreEnabled) {
            return [$data];
        }

        if ($subject->getStatus() !== 'pending') {
            return [$data];
        }

        if ($subject->getReturnToStoreId()) {
            return [$data];
        }

        if (isset($data['rma_returntostore_store_id']) && $data['rma_returntostore_store_id'] > 0) {
            $subject->setData('return_to_store_id', $data['rma_returntostore_store_id']);
            $subject->setData('return_to_store_email', $data['rma_returntostore_email']);
            $subject->setData('return_to_store_hash', (md5(time())));
        }

        return [$data];
    }

    /**
     * @param MagentoRma $subject
     * @param $result
     * @return array|null
     */

    public function afterSaveRma(MagentoRma $subject, $result)
    {
        if (!$this->isReturnInStoreEnabled) {
            return $result;
        }

        if (!$result) {
            return $result;
        }

        try {
            $this->sendEmails($subject);
            return $result;
        } catch (Exception $exception) {
            $this->logger->error($exception->getMessage(), ['exception' => $exception]);
        }  catch (Throwable $throwable) {
            $this->logger->error($throwable->getMessage(), ['exception' => $throwable]);
        }
    }

    /**
     * @param $rma
     * @return mixed|void
     * @throws LocalizedException
     */
    public function sendEmails($rma)
    {
        $returnToStoreId = (int)$rma->getReturnToStoreId();

        if (!$returnToStoreId) {
            return $rma;
        }

        if ($rma->getStatus() == 'pending') {
            try {
                if ($rma->getData('return_to_store_received_date') == null) {
                    $this->_helper->sendRmaMail($rma);
                }
            } catch (Exception $exception) {
                $this->logger->error($exception->getMessage(), ['exception' => $exception]);
            } catch (Throwable $throwable) {
                $this->logger->error($throwable->getMessage(), ['exception' => $throwable]);
            }
        }

        if ($this->state->getAreaCode() == 'adminhtml') {
            if ($rma->getStatus() == 'authorized') {
                try {
                    if ($rma->getData('return_to_store_received_date') == null) {
                        $this->_helper->sendRmaMail($rma);
                    }
                } catch (Exception $exception) {
                    $this->logger->error($exception->getMessage(), ['exception' => $exception]);
                } catch (Throwable $throwable) {
                    $this->logger->error($throwable->getMessage(), ['exception' => $throwable]);
                }
            }
        }
    }
}
