<?php
/**
 * NHT Trading Academy GetLinked Support Plugin
 *
 * @package NHT_Trading_Academy_GetLinked_Support_Plugin
 * @author New Horizon Technology Ltd.
 * @copyright 2024 New Horizon Technology Ltd.
 * @license All rights reserved.
 */

defined( 'ABSPATH' ) or die( 'Access Denied' );

/**
 * The callback function for the API route that handles automatic user creation.
 *
 * @param WP_REST_Request $request - an instance of WP_REST_Request.
 */
function from_landing( WP_REST_Request $request ) {
	$parameters = $request->get_params();

	// Check if the user already exists.
	$user = get_user_by( 'email', $parameters['email'] );
	if ( $user ) {
		return new WP_Error( 'user_exists', 'User already exists.', array( 'status' => 400 ) );
	}

	// Create the user.
	$user_id = wp_insert_user(
		array(
			'user_pass'     => $parameters['password'],
			'user_login'    => $parameters['email'],
			'user_nicename' => $parameters['firstName'] . ' ' . $parameters['lastName'],
			'user_email'    => $parameters['email'],
			'display_name'  => $parameters['firstName'] . ' ' . $parameters['lastName'],
			'nickname'      => $parameters['firstName'] . ' ' . $parameters['lastName'],
			'first_name'    => $parameters['firstName'],
			'last_name'     => $parameters['lastName'],
		)
	);
	if ( is_wp_error( $user_id ) ) {
		return new WP_Error( 'user_creation_failed', 'User creation failed.', array( 'status' => 500 ) );
	}

	// Return the user ID.
	return new WP_REST_Response( array( 'user_id' => $user_id ), 201 );
}

/**
 * Validate an email address sent to the registration postback endpoint.
 *
 * @param  string          $param   Value of the parameter.
 * @param  WP_REST_Request $request The current request object.
 * @param  string          $key   Key of the parameter.
 * @return WP_Error|boolean
 */
function nht_trading_academy_api_route_postback_registration_validate_email( $param, $request, $key ) {
	$is = is_email( $param );
	if ( ! $is ) {
		return new WP_Error( 'rest_invalid_email', __( 'Invalid email address.' ), array( 'status' => 400 ) );
	}
	return $is;
}

/**
 * Validate a name sent to the registration postback endpoint.
 *
 * @param  string          $param   Value of the parameter.
 * @param  WP_REST_Request $request The current request object.
 * @param  string          $key   Key of the parameter.
 * @return WP_Error|boolean
 */
function nht_trading_academy_api_route_postback_registration_validate_name( $param, $request, $key ) {
	$is_string = is_string( $param );
	if ( ! $is_string ) {
		return new WP_Error( 'rest_invalid_name', __( 'Invalid name.' ), array( 'status' => 400 ) );
	}
	$has_contents = strlen( $param ) > 0;
	if ( ! $has_contents ) {
		return new WP_Error( 'rest_invalid_name', __( 'Invalid name.' ), array( 'status' => 400 ) );
	}
	return $is_string && $has_contents;
}

/**
 * Validate a password sent to the registration postback endpoint.
 *
 * @param  string          $param   Value of the parameter.
 * @param  WP_REST_Request $request The current request object.
 * @param  string          $key   Key of the parameter.
 * @return WP_Error|boolean
 */
function nht_trading_academy_api_route_postback_registration_validate_password( $param, $request, $key ) {
	$is_string = is_string( $param );
	if ( ! $is_string ) {
		return new WP_Error( 'rest_invalid_password', __( 'Invalid password.' ), array( 'status' => 400 ) );
	}
	$has_contents = strlen( $param ) > 0;
	if ( ! $has_contents ) {
		return new WP_Error( 'rest_invalid_password', __( 'Invalid password.' ), array( 'status' => 400 ) );
	}
	return $is_string && $has_contents;
}

/**
 * Validate an advertiser hash sent to the registration postback endpoint.
 *
 * @param  string          $param   Value of the parameter.
 * @param  WP_REST_Request $request The current request object.
 * @param  string          $key   Key of the parameter.
 * @return WP_Error|boolean
 */
function nht_trading_academy_api_route_postback_registration_validate_advertiserhash( $param, $request, $key ) {
	$is_string = is_string( $param );
	if ( ! $is_string ) {
		return new WP_Error( 'rest_invalid_advertiserhash', __( 'Invalid advertiserhash.' ), array( 'status' => 400 ) );
	}
	$has_contents = strlen( $param ) > 0;
	if ( ! $has_contents ) {
		return new WP_Error( 'rest_invalid_advertiserhash', __( 'Invalid advertiserhash.' ), array( 'status' => 400 ) );
	}
	$options = get_option( 'nht_trading_academy_advertiser_hashes' );
	if ( ! is_array( $options ) ) {
		return new WP_Error( 'rest_invalid_advertiserhash', __( 'Invalid advertiserhash.' ), array( 'status' => 403 ) );
	}
	if ( ! in_array( $param, $options, true ) ) {
		return new WP_Error( 'rest_invalid_advertiserhash', __( 'Invalid advertiserhash.' ), array( 'status' => 403 ) );
	}
	return $is_string && $has_contents;
}

/**
 * Register the API routes for handling automatic user creation.
 */
function nht_trading_academy_register_api_routes() {
	register_rest_route(
		'nht-trading-academy-get-linked-support/v1',
		'/postback/registration',
		array(
			'methods'             => WP_REST_Server::ALLMETHODS,
			'callback'            => 'from_landing',
			'permission_callback' => '__return_true',
			'args'                => array(
				'email'          => array(
					'required'          => true,
					'type'              => 'string',
					'validate_callback' => 'nht_trading_academy_api_route_postback_registration_validate_email',
					'description'       => 'The email address of the user to create.',
				),
				'firstName'      => array(
					'required'          => true,
					'type'              => 'string',
					'description'       => 'The first name of the user to create.',
					'validate_callback' => 'nht_trading_academy_api_route_postback_registration_validate_name',
				),
				'lastName'       => array(
					'required'          => true,
					'type'              => 'string',
					'description'       => 'The last name of the user to create.',
					'validate_callback' => 'nht_trading_academy_api_route_postback_registration_validate_name',
				),
				'password'       => array(
					'required'          => true,
					'type'              => 'string',
					'description'       => 'The password of the user to create.',
					'validate_callback' => 'nht_trading_academy_api_route_postback_registration_validate_password',
				),
				'advertiserhash' => array(
					'required'          => true,
					'type'              => 'string',
					'description'       => 'The advertiser account offer hash.',
					'validate_callback' => 'nht_trading_academy_api_route_postback_registration_validate_advertiserhash',
				),
			),
		)
	);
}

add_action( 'rest_api_init', 'nht_trading_academy_register_api_routes' );
