<?php
declare(strict_types=1);

namespace Autogedal\Manufacturers\Plugin\Catalog\Block\Product\View;

use Autogedal\Manufacturers\Model\Config;
use Autogedal\Manufacturers\Model\ManufacturerUrl;
use Magento\Catalog\Block\Product\View\Attributes as AttributesBlock;
use Magento\Framework\Escaper;

class Attributes
{
    public function __construct(
        private readonly ManufacturerUrl $manufacturerUrl,
        private readonly Config $config,
        private readonly Escaper $escaper
    ) {
    }

    public function afterGetAdditionalData(AttributesBlock $subject, array $result): array
    {
        if (!$this->config->isEnabled()) {
            return $result;
        }

        $attributeCode = $this->config->getProductAttribute();
        if (!isset($result[$attributeCode])) {
            return $result;
        }

        $optionId = $subject->getProduct()->getData($attributeCode);
        $url = $optionId ? $this->manufacturerUrl->getUrlByOptionId($optionId) : null;
        if ($url !== null) {
            $result[$attributeCode]['value'] = sprintf(
                '<a href="%s" onclick="event.stopPropagation(); return true;">%s</a>',
                $this->escaper->escapeUrl($url),
                $this->escaper->escapeHtml($result[$attributeCode]['value'])
            );
        }

        return $result;
    }
}
