<?php
namespace Autogedal\BlogInternalLinking\Controller\Adminhtml\Group;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Autogedal\BlogInternalLinking\Model\GroupFactory;

class Delete extends Action
{
    protected $groupFactory;

    public function __construct(Context $context, GroupFactory $groupFactory)
    {
        $this->groupFactory = $groupFactory;
        parent::__construct($context);
    }

    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('Autogedal_BlogInternalLinking::groups');
    }

    public function execute()
    {
        $id       = (int)$this->getRequest()->getParam('group_id');
        $redirect = $this->resultRedirectFactory->create();

        if (!$id) {
            $this->messageManager->addError(__('Invalid group ID.'));
            return $redirect->setPath('*/*/');
        }

        try {
            $group = $this->groupFactory->create()->load($id);
            $group->delete();
            $this->messageManager->addSuccess(__('Group deleted.'));
        } catch (\Exception $e) {
            $this->messageManager->addError($e->getMessage());
        }

        return $redirect->setPath('*/*/');
    }
}
