<?php
/**
 * Sanitization helpers for email template metadata.
 *
 * @package MailDoctor
 */

namespace MailDoctor;

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

/**
 * Provides sanitizers used across template management.
 */
trait WPMD_Email_Templates_Sanitizers {

	/**
	 * Sanitize a boolean meta field.
	 *
	 * @param mixed $value Raw value.
	 * @return bool
	 */
	public static function sanitize_bool_field( $value ): bool {
		return (bool) filter_var( $value, FILTER_VALIDATE_BOOLEAN );
	}

	/**
	 * Sanitize email type value.
	 *
	 * @param mixed $value Raw value.
	 * @return string
	 */
	public static function sanitize_email_type( $value ): string {
		return sanitize_key( (string) $value );
	}

	/**
	 * Sanitize single-line text while preserving braces.
	 *
	 * @param mixed $value Raw value.
	 * @return string
	 */
	public static function sanitize_line_field( $value ): string {
		$value = (string) $value;
		$value = preg_replace( '/\r|\n/', '', $value );

		return wp_kses( $value, array() );
	}

	/**
	 * Sanitize HTML content.
	 *
	 * @param mixed $value Raw value.
	 * @return string
	 */
	public static function sanitize_html_field( $value ): string {
		return is_string( $value ) ? wp_kses_post( $value ) : '';
	}

	/**
	 * Sanitize CSS field.
	 *
	 * @param mixed $value Raw value.
	 * @return string
	 */
	public static function sanitize_css_field( $value ): string {
		if ( ! is_string( $value ) ) {
			return '';
		}

		$value = str_replace( array( '</style>', '<?', '?>' ), '', $value );

		return trim( $value );
	}
}
