<?php

namespace FiloBlu\Storelocator\Controller\Adminhtml\Tags;

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

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

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

    /**
     * {@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('tag_id');
        /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();
        if ($id) {
            try {
                $model = $this->tagsFactory->create();
                $model->load($id);
                $model->delete();
                $this->messageManager->addSuccess(__('The tag has been deleted.'));
                return $resultRedirect->setPath('*/*/');
            } catch (\Exception $e) {
                $this->messageManager->addError($e->getMessage());
                return $resultRedirect->setPath('*/*/edit', ['tag_id' => $id]);
            }
        }
        $this->messageManager->addError(__('We can\'t find a tag to delete.'));
        return $resultRedirect->setPath('*/*/');
    }
}