<?php
/**
 * Sanitize CSS before wp_add_inline_style() output.
 *
 * @package JOCBM
 *
 * Copyright (C) 2026 JayOnCode
 * License: GPL-2.0-or-later
 */

namespace JOCBM\Services;

defined( 'ABSPATH' ) || exit;

/**
 * Class CssSanitizer
 */
final class CssSanitizer {

	/**
	 * Sanitize a CSS fragment for safe inline style output.
	 *
	 * @param string $css Raw CSS rules.
	 */
	public static function sanitize_inline( string $css ): string {
		$css = trim( wp_strip_all_tags( $css ) );
		if ( '' === $css ) {
			return '';
		}

		// Block markup/script breakouts inside a style context.
		$css = preg_replace( '/<\/style|<\s*script|<!--|-->/i', '', $css ) ?? '';
		$css = str_replace( array( "\0", "\r" ), '', $css );

		$lower = strtolower( $css );
		$blocked = array(
			'expression(',
			'javascript:',
			'behavior:',
			'-moz-binding',
			'@import',
			'@charset',
			'@namespace',
		);
		foreach ( $blocked as $token ) {
			if ( str_contains( $lower, $token ) ) {
				return '';
			}
		}

		/**
		 * Filter sanitized inline CSS before wp_add_inline_style().
		 *
		 * @param string $css Sanitized CSS.
		 */
		return (string) apply_filters( 'jocbm_sanitize_inline_css', $css );
	}
}
