<?php

namespace FiloBlu\Storelocator\Controller\Adminhtml\Stores;

use FiloBlu\Storelocator\Block\Adminhtml\Stores\Edit\Tab\Tag;
use FiloBlu\Storelocator\Model\StoresFactory;
use Magento\Backend\App\Action;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\Result\Layout;
use Magento\Framework\View\Result\LayoutFactory;
use Magento\Framework\View\Result\PageFactory;

/**
 *
 */
class Tags extends Action
{
    /**
     * Core registry
     *
     * @var Registry
     */
    protected $registry = null;

    /**
     * @var PageFactory
     */
    protected $resultLayoutFactory;
    /**
     * @var \FiloBlu\Storelocator\Model\StoresFactory
     */
    private $storesFactory;

    /**
     * @param Action\Context $context
     * @param LayoutFactory $resultLayoutFactory
     * @param Registry $registry
     * @param \FiloBlu\Storelocator\Model\StoresFactory $storesFactory
     */
    public function __construct(
        Action\Context $context,
        LayoutFactory $resultLayoutFactory,
        Registry $registry,
        StoresFactory $storesFactory
    ) {
        $this->resultLayoutFactory = $resultLayoutFactory;
        $this->registry = $registry;
        parent::__construct($context);
        $this->storesFactory = $storesFactory;
    }

    /**
     * @return ResponseInterface|\Magento\Framework\Controller\Result\Redirect|ResultInterface|Layout|\Magento\Framework\View\Result\Page
     */
    public function execute()
    {
        $id = $this->getRequest()->getParam('id');

        $model = $this->storesFactory->create();

        if ($id) {
            $model->load($id);
            if (!$model->getId()) {
                $this->messageManager->addError(__('This store no longer exists.'));
                /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
                $resultRedirect = $this->resultRedirectFactory->create();

                return $resultRedirect->setPath('*/*/');
            }
        }

        $data = $this->_getSession()->getFormData(true);
        if (!empty($data)) {
            $model->setData($data);
        }

        $this->registry->register('storelocator_store', $model);

        $resultLayout = $this->resultLayoutFactory->create();
        /** @var Tag $tagsBlock */
        $tagsBlock = $resultLayout->getLayout()->getBlock('store.edit.tab.tag');
        if ($tagsBlock) {
            $tagsBlock->setStoreTags($this->getRequest()->getPost('store_tags', null));
        }
        return $resultLayout;
    }

    /**
     * {@inheritdoc}
     */
    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('FiloBlu_Storelocator::storelocator_save');
    }
}
