<?php

namespace FiloBlu\Storelocator\Controller\Adminhtml\Tags;

use Exception;
use FiloBlu\Storelocator\Model\TagsFactory;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Exception\LocalizedException;
use RuntimeException;

/**
 *
 */
class InlineEdit extends Action
{
    /** @var JsonFactory */
    protected $jsonFactory;
    /**
     * @var \FiloBlu\Storelocator\Model\TagsFactory
     */
    private $tagsFactory;

    /**
     * @param Context $context
     * @param JsonFactory $jsonFactory
     * @param \FiloBlu\Storelocator\Model\TagsFactory $tagsFactory
     */
    public function __construct(
        Context $context,
        JsonFactory $jsonFactory,
        TagsFactory $tagsFactory
    ) {
        parent::__construct($context);
        $this->jsonFactory = $jsonFactory;
        $this->tagsFactory = $tagsFactory;
    }

    /**
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        /** @var \Magento\Framework\Controller\Result\Json $resultJson */
        $resultJson = $this->jsonFactory->create();
        $error = false;
        $messages = [];

        $postItems = $this->getRequest()->getParam('items', []);

        if (!($this->getRequest()->getParam('isAjax') && count($postItems))) {
            return $resultJson->setData([
                'messages' => [__('Please correct the data sent.')],
                'error'    => true,
            ]);
        }

        foreach (array_keys($postItems) as $storeId) {
            $model = $this->tagsFactory->create();
            $model->load($storeId);
            $model->setData($postItems[$storeId]);

            $this->_eventManager->dispatch(
                'storelocator_tag_prepare_save',
                ['tag' => $model, 'request' => $this->getRequest()]
            );

            try {
                $model->save();
            } catch (LocalizedException $e) {
                $messages[] = $e->getMessage();
                $error = true;
            } catch (RuntimeException $e) {
                $messages[] = $e->getMessage();
                $error = true;
            } catch (Exception $e) {
                $messages[] = $e->getMessage();
                $error = true;
            }
        }

        return $resultJson->setData([
            'messages' => $messages,
            'error'    => $error
        ]);
    }
}
