<?php
declare(strict_types=1);

namespace Autogedal\Manufacturers\Setup\Patch\Data;

use Magento\Cms\Api\BlockRepositoryInterface;
use Magento\Cms\Api\GetBlockByIdentifierInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Store\Model\Store;

class AddManufacturersLinkToFooter implements DataPatchInterface
{
    private const BLOCK_IDENTIFIER = 'autogedal_foooter_about_us';

    private const LINK_CLASS = 'manufacturers-link';

    private const LINK_HTML = '<li class="' . self::LINK_CLASS . '">'
        . '<a href="/producatori" title="Producatori">Producatori</a></li>';

    private const CONTACT_ITEM_PATTERN = '~(*ANYCRLF)^([ \t]*)(<li>.*anchor_text="Contact".*</li>)[ \t]*$~m';

    public function __construct(
        private readonly GetBlockByIdentifierInterface $getBlockByIdentifier,
        private readonly BlockRepositoryInterface $blockRepository
    ) {
    }

    public function apply(): self
    {
        try {
            $block = $this->getBlockByIdentifier->execute(self::BLOCK_IDENTIFIER, Store::DEFAULT_STORE_ID);
        } catch (NoSuchEntityException) {
            return $this;
        }

        $content = (string)$block->getContent();
        if (str_contains($content, self::LINK_CLASS)) {
            return $this;
        }

        $updated = preg_replace(self::CONTACT_ITEM_PATTERN, "$1$2\n$1" . self::LINK_HTML, $content, 1, $count);
        if (!$count) {
            return $this;
        }

        $block->setContent($updated);
        $this->blockRepository->save($block);

        return $this;
    }

    public static function getDependencies(): array
    {
        return [];
    }

    public function getAliases(): array
    {
        return [];
    }
}
