<?php
namespace Solwin\Verticalmenu\Controller\Adminhtml\Menu;

class Delete extends \Solwin\Verticalmenu\Controller\Adminhtml\Menu
{
    /**
     * execute action
     *
     * @return \Magento\Backend\Model\View\Result\Redirect
     */
    public function execute()
    {
        $resultRedirect = $this->resultRedirectFactory->create();
        $id = $this->getRequest()->getParam('menu_id');
        if ($id) {
            $menu_title = "";
            try {
                /** @var \Solwin\Verticalmenu\Model\Menu $menu */
                $menu = $this->menuFactory->create();
                $menu->load($id);
                $menu_title = $menu->getMenu_title();
                $menu->delete();
                $this->messageManager->addSuccess(__('The Menu has been deleted.'));
                $this->_eventManager->dispatch(
                    'adminhtml_solwin_verticalmenu_menu_on_delete',
                    ['menu_title' => $menu_title, 'status' => 'success']
                );
                $resultRedirect->setPath('solwin_verticalmenu/*/');
                return $resultRedirect;
            } catch (\Exception $e) {
                $this->_eventManager->dispatch(
                    'adminhtml_solwin_verticalmenu_menu_on_delete',
                    ['menu_title' => $menu_title, 'status' => 'fail']
                );
                // display error message
                $this->messageManager->addError($e->getMessage());
                // go back to edit form
                $resultRedirect->setPath('solwin_verticalmenu/*/edit', ['menu_id' => $id]);
                return $resultRedirect;
            }
        }
        // display error message
        $this->messageManager->addError(__('Menu to delete was not found.'));
        // go to grid
        $resultRedirect->setPath('solwin_verticalmenu/*/');
        return $resultRedirect;
    }
}
