<?php

namespace FiloBlu\Storelocator\Controller\PickUpInStore;

use Exception;
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\Store\Model\StoreManagerInterface;

/**
 *
 */
class Confirm 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;
    /**
     * @var Context
     */
    protected $context;


    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
     * @param \FiloBlu\Storelocator\Helper\Data $helper
     * @param \Magento\Framework\Registry $registry
     * @param \Magento\Store\Model\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;
        $this->context = $context;
        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()
        ;

        if (!$hash || !$this->helper->getPickupInStoreEnabled($storeId))
        {
            $this->_forward('noRoute');
            return;
        }

        try
        {
            $order = $this->helper->getOrderByHash($hash);
        } catch (Exception $exception)
        {
            $this->_forward('noRoute');
            return;
        }

        $this->registry->register('pickupinstore_order_confirm', $order);
        $resultPage = $this->resultPageFactory->create();
        $resultPage->getConfig()
                   ->getTitle()
                   ->set(
                       __('PickUp In Store - Confirm customer pick up for order ') . $order->getIncrementId()
                   )
        ;

        return $resultPage;
    }
}
