<?php

declare(strict_types=1);

namespace Dedi\SyliusTheme\Common\Twig\Extension;

use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class CheckboxWithLinkExtension extends AbstractExtension
{
    // the ? makes the .* not greedy
    private const LINK_REGEX = '/#LINK\("(.*?)"\,"(.*?)"\)#/';

    public function getFunctions()
    {
        return [
            new TwigFunction('dedi_checkbox_with_link_label', [$this, 'computeLabel'], ['safe_html' => true]),
        ];
    }

    public function computeLabel(string $label): string
    {
        preg_match_all(self::LINK_REGEX, $label, $matches);
        [
            1 => $labels,
            2 => $hrefs
        ] = $matches;

        for ($i = 0, $max = count($labels); $i < $max; ++$i) {
            $label = preg_replace(
                self::LINK_REGEX,
                $this->buildLinkTag($hrefs[$i], $labels[$i]),
                $label,
                1,
            );
        }

        return $label;
    }

    private function buildLinkTag(string $href, string $label)
    {
        return sprintf(
            '<a href="%s">%s</a>',
            $href,
            $label,
        );
    }
}
