<?php
namespace Svea_Webpay_For_Woocommerce\Traits;

use Svea_Webpay_For_Woocommerce\Service_Providers\Config_Production;
use Svea_Webpay_For_Woocommerce\Service_Providers\Config_Test;

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

/**
 * Trait for handling phone number formatting
 *
 * @property string[] phone_country_codes
 */
trait Phone_Format {

	/**
	 * Get the posted phone number in a standardized format
	 *
	 * @param string $key
	 * @param string $default_country
	 * @return string
	 */
	public function get_payment_phone_number( $key, $default_country = '') {
		if ( ! isset( $_POST[ 'svea_' . $key . '_phone_number' ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
			return '';
		}

		$number = sanitize_text_field( wp_unslash( $_POST[ 'svea_' . $key . '_phone_number' ] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing

		// Remove all non-numeric characters
		$number = preg_replace( '/[^0-9]/', '', $number );

		// Vipps doesn't use country codes and only works with Norwegian numbers as of now
		if ( $key === 'vipps' && strpos( $number, '47' ) === 0 ) {
			$number = substr( $number, 2 );
		}

		foreach ( $this->phone_country_codes as $code ) {
			$plain_code = ltrim( $code, '0+' ); // Remove leading zeros or plus
			if ( preg_match( '/^(?:' . $plain_code . '|00' . $plain_code . '|\+' . $plain_code . ')/', $number ) ) {
				// Remove leading country code if present
				$number = preg_replace( '/^(?:' . $plain_code . '|00' . $plain_code . '|\+' . $plain_code . ')/', '', $number );
				return $code . $number;
			}
		}

		// Add default country code if no match
		$prefix = $this->phone_country_codes[ $default_country ] ?? '';

		// If the prefix doesn't contain double zeros we need to remove the first zero from the number
		if ( strpos( $prefix, '00' ) === false ) {
			$number = ltrim( $number, '0' );
		}

		return $prefix . $number;
	}
}
