<?php

namespace App\Support;

use App\Models\Setting;

class BadWordFilter
{
    public static function sanitize(?string $text): ?string
    {
        if ($text === null || $text === '') {
            return $text;
        }

        $words = self::words();
        if (!$words) {
            return $text;
        }

        $cleaned = $text;
        foreach ($words as $word) {
            $quoted = preg_quote($word, '/');
            $pattern = str_contains($word, ' ')
                ? "/{$quoted}/iu"
                : "/(?<![\\pL\\pN_]){$quoted}(?![\\pL\\pN_])/iu";
            $cleaned = preg_replace($pattern, '', $cleaned) ?? $cleaned;
        }

        return $cleaned;
    }

    protected static function words(): array
    {
        $raw = (string) Setting::get('blog_bad_words', '');
        if ($raw === '') {
            return [];
        }

        $parts = preg_split('/[\r\n,]+/', $raw) ?: [];
        return array_values(array_unique(array_filter(array_map(
            static fn ($item) => trim((string) $item),
            $parts
        ))));
    }
}
