<?php
/**
 * REST Lookup Carrier Helper.
 *
 * @package automation-web-platform
 */

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

use WAWP\Vendor\libphonenumber\PhoneNumberUtil;
use WAWP\Vendor\libphonenumber\PhoneNumberToCarrierMapper;

add_action(
	'rest_api_init',
	function () {
		register_rest_route(
			'wawp/v2',
			'/lookup-carrier',
			array(
				'methods'             => 'GET',
				'permission_callback' => function () {
					return true;
				},
				'callback'            => function ( WP_REST_Request $req ) {
					$e164 = $req->get_param( 'e164' );
					if ( ! $e164 ) {
						return new WP_Error( 'bad_request', 'Missing e164', array( 'status' => 400 ) );
					}

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

					if ( ! class_exists( PhoneNumberUtil::class ) ) {
						return new WP_REST_Response( array( 'carrier' => null ), 200 );
					}

					try {
						$phone_util = PhoneNumberUtil::getInstance();
						$carrier    = PhoneNumberToCarrierMapper::getInstance();
						$num        = $phone_util->parse( $e164, null );
						$name       = $carrier->getNameForNumber( $num, 'en' );
						return new WP_REST_Response( array( 'carrier' => $name ? $name : null ), 200 );
					} catch ( \Throwable $e ) {
						return new WP_REST_Response( array( 'carrier' => null ), 200 );
					}
				},
			)
		);
	}
);
