<?php

declare(strict_types=1);

/**
 * @author Amasty Team
 * @copyright Copyright (c) Amasty (https://www.amasty.com)
 * @package Jet Theme Backend for Magento 2 (System)
 */

namespace Amasty\JetTheme\Controller\Adminhtml\FooterLink;

use Amasty\JetTheme\Api\FooterLinkRepositoryInterface;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Backend\Model\View\Result\Redirect;
use Magento\Framework\Controller\ResultInterface;
use Psr\Log\LoggerInterface;

class Delete extends Action
{
    public const ADMIN_RESOURCE = 'Amasty_JetTheme::manage_footer_links';

    /**
     * @var FooterLinkRepositoryInterface
     */
    private $footerLinkRepository;

    /**
     * @var LoggerInterface
     */
    private $logger;

    public function __construct(
        Context $context,
        FooterLinkRepositoryInterface $footerLinkRepository,
        LoggerInterface $logger
    ) {
        parent::__construct($context);
        $this->footerLinkRepository = $footerLinkRepository;
        $this->logger = $logger;
    }

    /**
     * Delete action
     *
     * @return ResultInterface
     */
    public function execute(): ResultInterface
    {
        /** @var Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();
        $id = $this->getRequest()->getParam('id');
        if ($id) {
            try {
                $this->footerLinkRepository->deleteById((int) $id);
                $this->messageManager->addSuccessMessage(__('Footer Link have been deleted.'));

                return $resultRedirect->setPath('*/*/');
            } catch (\Exception $e) {
                $this->messageManager->addErrorMessage(
                    __('We can\'t delete item right now. Please review the log and try again.')
                );
                $this->logger->critical($e);

                return $resultRedirect->setPath('*/*/edit', ['id' => $id]);
            }
        }

        $this->messageManager->addErrorMessage(__('We can\'t find a Footer Link to delete.'));

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