<?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\Framework\Controller\ResultInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\View\Result\PageFactory;

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

    /**
     * @var PageFactory
     */
    private $resultPageFactory;

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

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

    /**
     * Edit action
     *
     * @return ResultInterface
     */
    public function execute(): ResultInterface
    {
        $id = $this->getRequest()->getParam('id', null);

        if ($id) {
            try {
                $model = $this->footerLinkRepository->get((int)$id);
            } catch (NoSuchEntityException $e) {
                $this->messageManager->addErrorMessage(__('This Footer Link no longer exists.'));
                $resultRedirect = $this->resultRedirectFactory->create();

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

        $resultPage = $this->resultPageFactory->create();
        $resultPage->addBreadcrumb(
            $id ? __('Edit Footer Link') : __('New Footer Link'),
            $id ? __('Edit Footer link') : __('New Footer Link')
        );
        $resultPage->getConfig()->getTitle()->prepend(__('Footer Link'));
        $resultPage->getConfig()->getTitle()->prepend(
            $id ?
                __('Edit Footer Link "%1" (ID: %2)', $model->getTitle(), $model->getId())
                : __('New Footer Link')
        );

        return $resultPage;
    }
}
