<?php
/**
 * Phone Helper Trait for Automation Web Platform.
 * Centralizes phone number formatting and validation for WhatsApp and SMS.
 *
 * @package automation-web-platform
 */

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

trait WAWP_Phone_Helper_Trait {

	/**
	 * Extracts only digits from a phone number.
	 *
	 * @param string $phone Phone number. The raw phone number.
	 * @return string Digits only.
	 */
	public static function get_digits_only( $phone ) {
		return preg_replace( '/\D/', '', $phone );
	}

	/**
	 * Formats a phone number for WhatsApp and general use.
	 *
	 * @param string $raw The raw phone number input.
	 * @return array{0:string, 1:string} Returns [digits_only, whatsapp_chat_id].
	 */
	public static function format_phone_number( $raw ) {
		static $cache = array();
		if ( isset( $cache[ $raw ] ) ) {
			return $cache[ $raw ];
		}

		// Remove all non-digits, but keep a leading + if present for initial parsing.
		$digits = self::get_digits_only( ltrim( $raw, '+' ) );
		if ( empty( $digits ) ) {
			return array( '', '' );
		}

		// WhatsApp Specific Logic for Latin America.
		if ( strlen( $digits ) >= 10 ) {

			// Mexico.
			if ( '52' === substr( $digits, 0, 2 ) && '1' !== substr( $digits, 2, 1 ) ) {
				$digits = '521' . substr( $digits, 2 );
			} elseif ( '54' === substr( $digits, 0, 2 ) && '9' !== substr( $digits, 2, 1 ) ) { // Argentina.
				$digits = '549' . substr( $digits, 2 );
			} elseif ( '55' === substr( $digits, 0, 2 ) && '9' !== substr( $digits, 2, 1 ) ) { // Brazil.
				$digits = '559' . substr( $digits, 2 );
			} elseif ( '56' === substr( $digits, 0, 2 ) && '9' !== substr( $digits, 2, 1 ) ) { // Chile.
				$digits = '569' . substr( $digits, 2 );
			} elseif ( '57' === substr( $digits, 0, 2 ) && '1' === substr( $digits, 2, 1 ) ) { // Colombia.
				$digits = '57' . substr( $digits, 3 );
			} elseif ( '58' === substr( $digits, 0, 2 ) && '4' !== substr( $digits, 2, 1 ) ) { // Venezuela.
				$digits = '584' . substr( $digits, 2 );
			} elseif ( '51' === substr( $digits, 0, 2 ) && '9' !== substr( $digits, 2, 1 ) ) { // Peru.
				$digits = '519' . substr( $digits, 2 );
			} elseif ( '593' === substr( $digits, 0, 3 ) && '9' !== substr( $digits, 3, 1 ) ) { // Ecuador.
				$digits = '5939' . substr( $digits, 3 );
			}
		}

		$chat_id       = $digits . '@c.us';
		$cache[ $raw ] = array( $digits, $chat_id );

		return $cache[ $raw ];
	}

	/**
	 * Formats a phone number specifically for SMS.
	 *
	 * @param string $phone Phone number. The raw phone number.
	 * @return string E.164 formatted number (e.g., +1234567890).
	 */
	public static function format_for_sms( $phone ) {
		$digits = self::get_digits_only( $phone );
		if ( empty( $digits ) ) {
			return '';
		}

		return '+' . $digits;
	}

	/**
	 * Checks if a phone number is blocked.
	 *
	 * @param string $phone Phone number.
	 * @return bool
	 */
	public static function is_phone_blocked( $phone ) {
		list( $digits, ) = self::format_phone_number( $phone );
		if ( empty( $digits ) ) {
			return false;
		}

		if ( class_exists( 'WAWP' ) ) {
			if ( WAWP()->block_manager ) {
				return (bool) WAWP()->block_manager->is_phone_blocked( $digits );
			}
		}

		return false;
	}
	/**
	 * Basic phone number validation.
	 *
	 * @param string $phone Phone number.
	 * @return bool
	 */
	public static function is_valid_phone( $phone ) {
		return (bool) preg_match( '/^\+?[0-9]{7,15}$/', $phone );
	}

	/**
	 * Looks up the telecom carrier name for a given phone number.
	 *
	 * @param string $phone The raw or formatted phone number.
	 * @return string|null The carrier name in English, or null if not found.
	 */
	public static function lookup_phone_carrier( $phone ) {
		$digits = self::get_digits_only( $phone );
		if ( empty( $digits ) ) {
			return null;
		}

		if ( defined( 'WAWP_PLUGIN_DIR' ) ) {
			$autoload = WAWP_PLUGIN_DIR . 'vendor/autoload.php';
			if ( file_exists( $autoload ) ) {
				require_once $autoload;
			}
		}

		if ( ! class_exists( 'WAWP\Vendor\libphonenumber\PhoneNumberUtil' ) ) {
			return null;
		}

		try {
			$phone_util = \WAWP\Vendor\libphonenumber\PhoneNumberUtil::getInstance();
			$carrier    = \WAWP\Vendor\libphonenumber\PhoneNumberToCarrierMapper::getInstance();
			$e164       = '+' . $digits;
			$num        = $phone_util->parse( $e164, null );
			$name       = $carrier->getNameForNumber( $num, 'en' );
			return $name ? $name : null;
		} catch ( \Throwable $e ) {
			return null;
		}
	}
}
