<?php

namespace FiloBlu\Storelocator\Controller\Adminhtml\Stores;

use FiloBlu\Storelocator\Block\Adminhtml\Stores\Edit\Tab\Image;
use FiloBlu\Storelocator\Model\StoresFactory;
use Magento\Backend\App\Action;
use Magento\Framework\Registry;
use Magento\Framework\View\Result\LayoutFactory;
use Magento\Framework\View\Result\PageFactory;

/**
 *
 */
class Images 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 \Magento\Framework\View\Result\LayoutFactory $resultLayoutFactory
     * @param \FiloBlu\Storelocator\Model\StoresFactory $storesFactory
     * @param Registry $registry
     */
    public function __construct(
        Action\Context $context,
        LayoutFactory $resultLayoutFactory,
        StoresFactory $storesFactory,
        Registry $registry
    ) {
        parent::__construct($context);
        $this->resultLayoutFactory = $resultLayoutFactory;
        $this->registry = $registry;
        $this->storesFactory = $storesFactory;
    }

    /**
     * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\Result\Redirect|\Magento\Framework\Controller\ResultInterface|\Magento\Framework\View\Result\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 Image $imagesBlock */
        $imagesBlock = $resultLayout->getLayout()->getBlock('store.edit.tab.image');
        if ($imagesBlock) {
            $imagesBlock->setStoreImages($this->getRequest()->getPost('store_images', null));
        }
        return $resultLayout;
    }

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