<?php

namespace FiloBlu\Storelocator\Controller\Adminhtml\Images;

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

use function count;

/**
 * Cms page grid inline edit controller
 *
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class InlineEdit extends Action
{
    /** @var JsonFactory */
    protected $jsonFactory;
    /**
     * @var \FiloBlu\Storelocator\Model\ImagesFactory
     */
    private $imagesFactory;

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

    /**
     * @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->imagesFactory->create();
            $model->load($storeId);
            $model->setData($postItems[$storeId]);

            $this->_eventManager->dispatch(
                'storelocator_image_prepare_save', ['image' => $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
        ]);
    }
}
