<?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\Exception\NoSuchEntityException;
use Magento\Framework\Registry;
use Magento\Framework\View\Result\PageFactory;
use Magento\Rma\Model\Rma;
use Magento\Store\Model\StoreManagerInterface;

/**
 *
 */
class Rmareceived extends Action
{
    /** @var \Magento\Framework\View\Result\PageFactory */
    protected $resultPageFactory;

    /** @var \FiloBlu\Storelocator\Helper\Data */
    protected $helper;

    /**
     * @var \Magento\Framework\Registry
     */
    protected $_coreRegistry;

    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;

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

    /**
     * @return \Magento\Framework\Controller\ResultInterface|\Magento\Framework\View\Result\Page|void|null
     * @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->_coreRegistry->register('pickupinstore_rma_received', $rma);
            $resultPage = $this->resultPageFactory->create();

            $title = __('PickUp In Store - Confirmation of acceptance of the package for return ');

            if (!$this->helper->getUseStandardRmaMailFlow($storeId) && $rma->getStatus() === 'pending') {
                $title = __('PickUp In Store - Confirmation of authorization of the package for return ');
            }

            $resultPage->getConfig()->getTitle()->set($title . $rma->getData('increment_id'));

            return $resultPage;
        }

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