<?php
/**
 * Content helper to safely render admin-authored HTML with an allowlist of tags/attributes.
 * This avoids showing raw HTML text while still preventing most unsafe markup.
 */

if (!function_exists('sanitize_rich_content')) {
    /**
     * Allow a safe subset of HTML. Extend as needed.
     *
     * @param string $html
     * @return string sanitized HTML
     */
    function sanitize_rich_content($html)
    {
        if (!is_string($html) || $html === '') {
            return '';
        }

        // Allowed tags (including button/svg for FAQ toggles, and 'i' for icons)
        $allowed_tags = '<p><br><br/><strong><b><em><i><u><s><ul><ol><li><blockquote><code><pre>' .
                        '<h1><h2><h3><h4><h5><h6>' .
                        '<a><img><hr><span><div><button><svg><path><i>';

        // Strip disallowed tags first
        $clean = strip_tags($html, $allowed_tags);

        // Basic attribute allowlist
        $clean = preg_replace('/\son[a-z]+\s*=\s*"[^"]*"/i', '', $clean); // on*="..."
        $clean = preg_replace("/\son[a-z]+\s*=\s*'[^']*'/i", '', $clean); // on*='...'
        
        // We allow 'class' so Tailwind-like UI works, but strip potentially harmful 'style'
        $clean = preg_replace('/\sstyle\s*=\s*"[^"]*"/i', ' ', $clean);   
        $clean = preg_replace("/\sstyle\s*=\s*'[^']*'/i", ' ', $clean);

        // Disallow javascript: in href/src
        $clean = preg_replace('/(href|src)\s*=\s*"\s*javascript:[^"]*"/i', '$1="#"', $clean);
        $clean = preg_replace("/(href|src)\s*=\s*'\s*javascript:[^']*'/i", '$1="#"', $clean);

        return $clean;
    }
}
