<?php

declare(strict_types=1);

namespace FiloBlu\Storelocator\Controller\Adminhtml\Stores;

use FiloBlu\Storelocator\Model\StoresFactory;
use Magento\Backend\App\Action;
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 Events extends Action
{
    /**
     * Core registry
     *
     * @var Registry
     */
    protected $registry = null;

    /**
     * @var PageFactory
     */
    protected $resultLayoutFactory;

    /**
     * @var StoresFactory
     */
    private $storesFactory;

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

    /**
     * @return Layout|\Magento\Framework\Controller\Result\Redirect|\Magento\Framework\View\Result\Page|ResultInterface
     */
    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();
        $tagsBlock = $resultLayout->getLayout()->getBlock('store.edit.tab.events');
        if ($tagsBlock) {
            $tagsBlock->setStoreTags($this->getRequest()->getPost('store_tags'));
        }
        return $resultLayout;
    }

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