<?php

namespace App\Services;

use Mews\Purifier\Facades\Purifier;

class RichTextSanitizer
{
    public static function clean(?string $html): ?string
    {
        if ($html === null) {
            return null;
        }

        $trimmed = trim($html);
        if ($trimmed === '') {
            return '';
        }

        // Remove data-* attributes EXCEPT those needed for rich text components
        // Preserve: data-type, data-layout (for columns), data-youtube-video, data-embed
        $normalized = preg_replace('/\sdata-(?!type|layout|youtube|embed)[a-z0-9\-]+=("[^"]*"|\'[^\']*\')/i', '', $html);
        $normalized = preg_replace('/\sallowfullscreen(=("[^"]*"|\'[^\']*\'))?/i', '', $normalized);

        return Purifier::clean($normalized);
    }
}
