<?php

namespace App\Services\PromptLandingPageEditor;

class UniqueDuplicateIds
{
    public function rewrite(string $html): string
    {
        if ($html === '') {
            return $html;
        }

        $seen = [];

        $rewritten = preg_replace_callback(
            '/\bid=(["\'])([^"\']+)\1/i',
            function (array $matches) use (&$seen): string {
                $id = $matches[2];

                if (! isset($seen[$id])) {
                    $seen[$id] = 1;

                    return $matches[0];
                }

                $seen[$id]++;
                $copy = $id.'-copy-'.$seen[$id];

                while (isset($seen[$copy])) {
                    $seen[$id]++;
                    $copy = $id.'-copy-'.$seen[$id];
                }

                $seen[$copy] = 1;

                return 'id='.$matches[1].$copy.$matches[1];
            },
            $html,
        );

        return is_string($rewritten) ? $rewritten : $html;
    }
}
