<?php

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

class WPForms_Persian_SMS_Helpers {

	public static function split_and_trim( $input ) {

		// Split by comma or space using regex
		$parts = preg_split( '/[\s,]+/', $input );
		// Trim each part and remove empty values
		$trimmedParts = array_filter( array_map( 'trim', $parts ) );
		return $trimmedParts;
	}

	public static function validate_phone( $mobile ) {

		$mobile = self::modify_phone( $mobile );
		return preg_match( '/9\d{9,}?$/', trim( $mobile ) );
	}

	public static function modify_phone( $mobile ) {

		if ( is_array( $mobile ) ) {
			return array_map( [ self::class, __FUNCTION__ ], $mobile );
		}

		$mobile   = self::convert_phone_number_digits( $mobile );
		$modified = preg_replace( '/\D/is', '', (string) $mobile );

		if ( substr( $mobile, 0, 1 ) == '+' ) {
			return '+' . $modified;
		} elseif ( substr( $modified, 0, 2 ) == '00' ) {
			return '+' . substr( $modified, 2 );
		} elseif ( substr( $modified, 0, 1 ) == '0' ) {
			return $modified;
		} elseif ( ! empty( $modified ) ) {
			$modified = '0' . $modified;
		}

		return $modified;
	}

	public static function convert_phone_number_digits( $mobile ) {

		if ( is_array( $mobile ) ) {
			return array_map( [ self::class, __FUNCTION__ ], $mobile );
		} else {
			$mobile = sanitize_text_field( $mobile );
			$mobile = str_ireplace( [ '۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹' ], [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ], $mobile ); //farsi
			$mobile = str_ireplace( [ '٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩' ], [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ], $mobile ); //arabic

			return $mobile;
		}
	}
}
