<?php

namespace FiloBlu\Storelocator\Controller\Adminhtml\Stores;

use Exception;
use FiloBlu\Storelocator\Model\StoresFactory;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;

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

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

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

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