<?php
/**
 * Structural phone normalization for WhatsApp and contact matching.
 *
 * @package Niwa_AI
 */

defined( 'ABSPATH' ) || exit;

class Niwa_AI_Phone_Normalizer {

	public static function normalize( $phone, $country = '' ) {
		$raw    = trim( (string) $phone );
		$digits = preg_replace( '/\D+/', '', $raw );
		if ( ! is_string( $digits ) || '' === $digits ) {
			return '';
		}

		if ( 0 === strpos( $raw, '00' ) ) {
			$digits = substr( $digits, 2 );
		} elseif ( 0 !== strpos( $raw, '+' ) && '0' === $digits[0] ) {
			$calling_code = self::calling_code( $country );
			if ( '' === $calling_code ) {
				return '';
			}
			$digits = $calling_code . ltrim( $digits, '0' );
		}

		return strlen( $digits ) >= 7 && strlen( $digits ) <= 15 ? $digits : '';
	}

	private static function calling_code( $country ) {
		$country = strtoupper( trim( (string) $country ) );
		if ( '' === $country && function_exists( 'WC' ) ) {
			$wc = WC();
			if ( is_object( $wc ) && isset( $wc->customer ) && is_object( $wc->customer ) && method_exists( $wc->customer, 'get_billing_country' ) ) {
				$country = strtoupper( trim( (string) $wc->customer->get_billing_country() ) );
			}
		}
		if ( '' === $country && function_exists( 'wc_get_base_location' ) ) {
			$base    = wc_get_base_location();
			$country = is_array( $base ) ? strtoupper( trim( (string) ( $base['country'] ?? '' ) ) ) : '';
		}
		if ( '' === $country || ! function_exists( 'WC' ) ) {
			return '';
		}

		$wc = WC();
		if ( ! is_object( $wc ) || ! isset( $wc->countries ) || ! is_object( $wc->countries ) || ! method_exists( $wc->countries, 'get_country_calling_code' ) ) {
			return '';
		}
		$code = $wc->countries->get_country_calling_code( $country );
		if ( is_array( $code ) ) {
			$code = reset( $code );
		}
		$digits = preg_replace( '/\D+/', '', (string) $code );
		return is_string( $digits ) ? $digits : '';
	}
}
