<?php
namespace FiloBlu\Storelocator\Controller\Adminhtml\Images;

use FiloBlu\Storelocator\Model\ImagesFactory;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;

/**
 *
 */
class Delete extends Action
{
    /**
     * @var \FiloBlu\Storelocator\Model\ImagesFactory
     */
    private $imagesFactory;

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

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

    /**
     * Delete action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $id = $this->getRequest()->getParam('image_id');
        /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();
        if ($id) {
            try {
                $model = $this->imagesFactory->create();
                $model->load($id);
                $model->delete();
                $this->messageManager->addSuccess(__('The image has been deleted.'));
                return $resultRedirect->setPath('*/*/');
            } catch (\Exception $e) {
                $this->messageManager->addError($e->getMessage());
                return $resultRedirect->setPath('*/*/edit', ['image_id' => $id]);
            }
        }
        $this->messageManager->addError(__('We can\'t find a image to delete.'));
        return $resultRedirect->setPath('*/*/');
    }
}