<?php

declare(strict_types=1);

namespace Dedi\SyliusTheme\Twig;

use NumberFormatter;
use Sylius\Bundle\MoneyBundle\Formatter\MoneyFormatterInterface;

class MoneyFormatter implements MoneyFormatterInterface
{
    private MoneyFormatterInterface $baseMoneyFormatter;

    public function __construct(MoneyFormatterInterface $baseMoneyFormatter)
    {
        $this->baseMoneyFormatter = $baseMoneyFormatter;
    }

    /**
     * @inheritdoc
     */
    public function format(int $amount, string $currencyCode, ?string $locale = null): string
    {
        $format = $this->baseMoneyFormatter->format($amount, $currencyCode, $locale); // 12,82 €
        $numberFormatter = NumberFormatter::create($locale ?? 'en', NumberFormatter::CURRENCY);

        $pattern = sprintf(
            '/([0-9 %s]+)%s([0-9]+)/m',
            $numberFormatter->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL),
            $numberFormatter->getSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL)
        );

        preg_match_all($pattern, $format, $matches);

        $var = $matches[1][0];
        $format = str_replace($var, sprintf('<span>%s</span>', $var), $format);

        return $format;
    }
}
