<?php

namespace FiloBlu\Storelocator\Model\Plugin\Rma;

use FiloBlu\Storelocator\Helper\Data;
use Magento\Framework\App\RequestInterface;
use Magento\Rma\Model\ResourceModel\Rma\CollectionFactory;
use Magento\Store\Model\StoreManagerInterface;

/**
 *
 */
class Config
{
    /**
     * @var Data
     */
    protected $helper;
    /**
     * @var RequestInterface
     */
    protected $request;
    /**
     * @var CollectionFactory
     */
    protected $rmaFactory;
    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;

    /**
     * @param \FiloBlu\Storelocator\Helper\Data $helper
     * @param \Magento\Framework\App\RequestInterface $request
     * @param \Magento\Rma\Model\ResourceModel\Rma\CollectionFactory $rmaFactory
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     */
    public function __construct(
        Data $helper,
        RequestInterface $request,
        CollectionFactory $rmaFactory,
        StoreManagerInterface $storeManager
    ) {
        $this->helper = $helper;
        $this->request = $request;
        $this->rmaFactory = $rmaFactory;
        $this->storeManager = $storeManager;
    }

    /**
     * @param \Magento\Rma\Model\Config $subject
     * @param $result
     * @return mixed|null
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function afterGetCopyTo(\Magento\Rma\Model\Config $subject, $result)
    {
        $storeId = $this->storeManager->getStore()->getId();

        if (!$this->helper->getReturnToStoreEnabled($storeId)) {
            return $result;
        }

        $orderId = $this->request->getParam('order_id');
        $rmaId = $this->request->getParam('rma_id');

        if (!$orderId && !$rmaId) {
            return $result;
        }

        /** @var \Magento\Rma\Model\Rma $rma */
        $rma = $this->getRmaCollection($orderId);

        if ($rma->getStatus() !== 'pending') {
            return $result;
        }

        if ($this->helper->getReturnToStoreEnabled($storeId) && $rma->getReturnToStoreId()) {
            return null;
        }

        return $result;
    }

    /**
     * @param $orderId
     * @return \Magento\Framework\DataObject
     */
    public function getRmaCollection($orderId)
    {
        return $this->rmaFactory->create()->addFieldToSelect(
            '*'
        )->addFieldToFilter(
            'order_id',
            $orderId
        )->getLastItem();
    }
}