<?php
/**
 * MetaFieldSanitizer class.
 *
 * Sanitizes values from $_POST based on provided field types.
 *
 * @package Ilabs\Firevert\Core\Form\Sanitization
 */

declare( strict_types=1 );

namespace Ilabs\Firevert\Core\Form\Sanitization;

/**
 * Class MetaFieldSanitizer
 */
final class MetaFieldSanitizer {

	/**
	 * Sanitize and validate a meta field value.
	 *
	 * @param string $key   POST key.
	 * @param string $type  Expected data type: bool, int, text, color, url, datetime.
	 * @param string $nonce Optional nonce field name to verify.
	 *
	 * @return mixed|null Sanitized value or null if not set or nonce fails.
	 */
	public function sanitize( string $key, string $type, string $nonce = '' ) {
		$post_data = wp_unslash( $_POST );

		if ( ! is_array( $post_data ) || ! array_key_exists( $key, $post_data ) ) {
			return null;
		}

		if ( '' !== $nonce ) {
			if ( ! array_key_exists( $nonce, $post_data ) ) {
				return null;
			}

			$nonce_value = sanitize_text_field( wp_unslash( $post_data[ $nonce ] ) );

			if ( ! wp_verify_nonce( $nonce_value, $nonce ) ) {
				return null;
			}
		}

		$value = $post_data[ $key ] ?? null;

		if ( null === $value ) {
			return null;
		}
		switch ( $type ) {
			case 'bool':
				return ! empty( sanitize_text_field( $value ) ) ? 1 : 0;

			case 'int':
				$color_value = sanitize_text_field( $value );
				return is_numeric( $color_value ) ? (int) $color_value : null;

			case 'color':
				$color = sanitize_hex_color( sanitize_text_field( $value ) );

				return $color ?? null;

			case 'url':
				return esc_url_raw( sanitize_text_field( $value ) );

			case 'datetime':
				// todo: better datetime validation.
				return sanitize_text_field( $value );

			case 'array':
				if ( is_array( $value ) ) {
					return array_map( 'sanitize_text_field', wp_unslash( $value ) );
				}
				return array( sanitize_text_field( wp_unslash( $value ) ) );

			case 'html':
				return wp_kses_post( $value );

			case 'text':
			default:
				return sanitize_text_field( $value );
		}
	}
}
