<?php
/**
 * Validates names stored in the structured identity profile.
 *
 * @package Niwa_AI
 */

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

class Niwa_AI_Identity_Name {
	public static function normalize( $value ) {
		$value = html_entity_decode( wp_strip_all_tags( (string) $value ), ENT_QUOTES | ENT_HTML5, 'UTF-8' );
		$value = trim( (string) preg_replace( '/\s+/u', ' ', $value ) );
		if ( '' === $value || self::length( $value ) > 80 ) {
			return '';
		}

		$parts = preg_split( '/\s+/u', $value, -1, PREG_SPLIT_NO_EMPTY );
		if ( ! is_array( $parts ) || count( $parts ) > 4 ) {
			return '';
		}

		return preg_match( "/^[\p{L}\p{M}\p{N}][\p{L}\p{M}\p{N}\s'’\-]*$/u", $value ) ? $value : '';
	}

	private static function length( $value ) {
		return function_exists( 'mb_strlen' ) ? mb_strlen( $value, 'UTF-8' ) : strlen( $value );
	}
}
