<?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\Data\FooterLinkInterfaceFactory;
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 Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Psr\Log\LoggerInterface;

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

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

    /**
     * @var FooterLinkInterfaceFactory
     */
    private $footerLinkFactory;

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

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

    /**
     * Save action
     *
     * @return ResultInterface
     */
    public function execute(): ResultInterface
    {
        /** @var Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();
        $data = $this->getRequest()->getPostValue();

        $id = $this->getRequest()->getParam('entity_id', null);

        try {
            if ($id) {
                $model = $this->footerLinkRepository->get((int)$id);
            } else {
                $model = $this->footerLinkFactory->create();
            }
        } catch (NoSuchEntityException $e) {
            $model = $this->footerLinkFactory->create();
        }

        try {
            $model->setData($data);
            $this->footerLinkRepository->save($model);
            $this->messageManager->addSuccessMessage(__('Footer link have been saved.'));

            if ($this->getRequest()->getParam('back')) {
                return $resultRedirect->setPath('*/*/edit', ['id' => $model->getId()]);
            }

            return $resultRedirect->setPath('*/*/');
        } catch (LocalizedException $e) {
            $this->messageManager->addErrorMessage($e->getMessage());
        } catch (\Exception $e) {
            $this->messageManager->addExceptionMessage($e, __('Something went wrong while saving the Footer link.'));
            $this->logger->error($e->getMessage());
        }

        return $resultRedirect->setPath(
            '*/*/edit',
            ['id' => $model->getId() ?? $this->getRequest()->getParam('id')]
        );
    }
}
