<?php
/**
 * File Path: includes/helpers/class-mbs-color-helper.php
 *
 * My Book Showroom — Color Helper
 *
 * Static helper for sanitizing color values. Extracted from the global
 * mbs_sanitize_color() function (RF-013) so it can be autoloaded and
 * referenced as a proper PHP callable for register_setting().
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class MBS_Color_Helper { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- mbs_/MBS_ prefix is correct; scanner not configured with plugin prefix

	/**
	 * Sanitize a color value supporting both hex and rgba() formats.
	 *
	 * Used as the sanitize_callback for all Appearance tab color settings
	 * and for direct sanitization in output helpers.
	 *
	 * Preserves existing rgba defaults (e.g. overlay rgba(0,0,0,0.7)) while
	 * blocking dangerous CSS injection.
	 *
	 * @param string $color Raw color value from user input.
	 * @return string       Sanitized color, or empty string on failure.
	 */
	public static function sanitize( string $color ): string {
		$color = trim( $color );

		if ( '' === $color ) {
			return '';
		}

		// Hex colors (#rrggbb or #rgb). WP's sanitize_hex_color() returns null for
		// invalid input; our function signature is : string, so we must reject
		// null alongside empty string or PHP 8+ throws TypeError on return.
		if ( str_starts_with( $color, '#' ) ) {
			$sanitized = sanitize_hex_color( $color );
			if ( null !== $sanitized && '' !== $sanitized ) {
				return $sanitized;
			}
		}

		// rgba() or rgb() — allow existing defaults and valid patterns only.
		if ( preg_match( '/^rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*(?:,\s*[\d.]+\s*)?\)$/i', $color ) ) {
			return $color;
		}

		// Fallback: strip anything dangerous.
		return sanitize_text_field( $color );
	}
}
