<?php

namespace FiloBlu\Storelocator\Model\Plugin\Rma;

use FiloBlu\Storelocator\Helper\Data;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Controller\ResultInterface;
use Magento\Rma\Controller\Returns\Submit;
use Magento\Store\Model\StoreManagerInterface;

/**
 *
 */
class RmaSubmit
{
    /**
     * @var ResultFactory
     */
    protected $resultFactory;
    /**
     * @var Data
     */
    protected $helper;
    /**
     * @var RequestInterface
     */
    protected $request;
    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;

    /**
     * @param ResultFactory $resultFactory
     * @param RequestInterface $request
     * @param Data $helper
     * @param StoreManagerInterface $storeManager
     */
    public function __construct(
        ResultFactory $resultFactory,
        RequestInterface $request,
        Data $helper,
        StoreManagerInterface $storeManager
    ) {
        $this->resultFactory = $resultFactory;
        $this->helper = $helper;
        $this->request = $request;
        $this->storeManager = $storeManager;
    }

    /**
     * @param Submit $subject
     * @param $result
     * @return ResultInterface|mixed
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function afterExecute(Submit $subject, $result)
    {
        $storeId = $this->storeManager->getStore()->getId();

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

        if (!$this->request->getParam('rma_returntostore_store_id')) {
            return $result;
        }

        $isAjax = $subject->getRequest()->getParam('ajax');

        if ($isAjax) {
            $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
            $resultJson->setData(['message' => __('Rma created sccessfully!'), 'success' => true]);

            return $resultJson;
        }

        return $result;
    }
}