<?php

namespace FiloBlu\Storelocator\Controller\PickUpInStore;


use FiloBlu\Storelocator\Helper\Data;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Registry;
use Magento\Framework\View\Result\PageFactory;
use Magento\Rma\Model\Rma;
use Magento\Rma\Model\RmaFactory;
use Magento\Store\Model\StoreManagerInterface;

/**
 *
 */
class Rmarefused extends Action
{
    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $resultPageFactory;
    /**
     * @var \FiloBlu\Storelocator\Helper\Data
     */
    protected $helper;
    /**
     * @var \Magento\Framework\Registry
     */
    protected $registry;
    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;

    /**
     * @param Context $context
     * @param PageFactory $resultPageFactory
     * @param Data $helper
     * @param RmaFactory $rmaFactory
     * @param Registry $registry
     * @param StoreManagerInterface $storeManager
     */
    public function __construct(
        Context $context,
        PageFactory $resultPageFactory,
        Data $helper,
        Registry $registry,
        StoreManagerInterface $storeManager
    ) {
        $this->resultPageFactory = $resultPageFactory;
        $this->helper = $helper;
        $this->registry = $registry;
        $this->storeManager = $storeManager;
        parent::__construct($context);
    }

    /**
     * @return \Magento\Framework\Controller\ResultInterface|\Magento\Framework\View\Result\Page|void
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function execute()
    {
        $hash = $this->getRequest()->getParam('hash');
        $storeId = $this->storeManager->getStore()->getId();

        $isPickupInStoreEnabled = $this->helper->getPickupInStoreEnabled($storeId);
        $isReturnInStoreEnabled = $this->helper->getReturnToStoreEnabled($storeId);

        if ((!$isPickupInStoreEnabled && !$isReturnInStoreEnabled) || !$hash) {
            $this->_forward('noRoute');
            return;
        }

        // check if is rma or order request
        $rma = $this->helper->getRmaByHash($hash);
        $order = $rma->getOrder();

        if ($order->getId()  && (int)$rma->getReturnToStoreId() > 0) {
            $this->registry->register('pickupinstore_rma_refused', $rma);
            $resultPage = $this->resultPageFactory->create();
            $resultPage->getConfig()->getTitle()->set(
                'PickUp In Store - Confirmation of rejected of the package for return ' . $rma->getData('increment_id')
            );

            return $resultPage;
        }

        $this->_forward('noRoute');
    }
}
