<?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\Plugin\Framework\View\Element\Html\Links;

use Amasty\JetTheme\Model\ConfigProvider;
use Amasty\JetTheme\Model\StoreThemeMapper;
use Amasty\JetTheme\ViewModel\FooterLinkViewModel;
use Magento\Framework\View\Element\Html\Link\Current;
use Magento\Framework\View\Element\Html\Links;

class ReplaceFooterLinks
{
    public const BLOCK_NAME = 'footer_links';

    /**
     * @var ConfigProvider
     */
    private $configProvider;

    /**
     * @var FooterLinkViewModel
     */
    private $footerLinkViewModel;

    /**
     * @var StoreThemeMapper
     */
    private $storeThemeMapper;

    public function __construct(
        ConfigProvider $configProvider,
        FooterLinkViewModel $footerLinkViewModel,
        StoreThemeMapper $storeThemeMapper
    ) {
        $this->configProvider = $configProvider;
        $this->footerLinkViewModel = $footerLinkViewModel;
        $this->storeThemeMapper = $storeThemeMapper;
    }

    /**
     * @param Links $subject
     * @param array $result
     */
    public function afterGetLinks(Links $subject, array $result): array
    {
        if ($this->storeThemeMapper->isCurrentThemeJetTheme() &&
            $this->configProvider->isReplaceDefaultFooterLinks() &&
            $subject->getNameInLayout() === self::BLOCK_NAME
        ) {
            $result = [];
            $footerLinks = $this->footerLinkViewModel->getFooterLinks();
            foreach ($footerLinks as $footerLink) {
                /** @var Current $link */
                $link = $subject->getLayout()->createBlock(Current::class);
                $link->setData('label', $footerLink->getTitle());
                $link->setData('path', $footerLink->getPath());
                $result[] = $link;
            }
        }

        return $result;
    }
}
