<?php
/**
 * Accounts REST API
 *
 * Registers account-related REST API routes.
 *
 * @package AmbassadorHub\Accounts
 */

namespace AmbassadorHub\Accounts;

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

use AmbassadorHub\Api\ApiModule;
use AmbassadorHub\Accounts\Admin\Settings\SettingsManager;

use function add_action;
use function do_action;
use function get_current_user_id;
use function is_user_logged_in;
use function register_rest_route;
use function rest_ensure_response;
use function sanitize_text_field;
use function update_user_meta;
use function __;

/**
 * Account API routes.
 */
final class AccountsApi {
	/**
	 * Initialize the Accounts API routes.
	 *
	 * @return void
	 */
	public static function init(): void {
		add_action( 'ambh_register_rest_routes', array( self::class, 'register_routes' ) );
	}

	/**
	 * Register account-related REST routes.
	 *
	 * @return void
	 */
	public static function register_routes(): void {
		// Email verification endpoint.
		register_rest_route(
			ApiModule::NAMESPACE,
			'/verify-email',
			array(
				'methods'             => 'POST',
				'callback'            => array( self::class, 'verify_email_handler' ),
				'permission_callback' => '__return_true', // Public: verification link is visited by unauthenticated users; the token in the request body provides its own authorisation.
				'args'                => array(
					'token'   => array(
						'type'     => 'string',
						'required' => true,
					),
					'user_id' => array(
						'type'              => 'integer',
						'required'          => false,
						'sanitize_callback' => 'absint',
					),
				),
			)
		);

		// Profile picture upload endpoint.
		register_rest_route(
			ApiModule::NAMESPACE,
			'/account/profile-picture/upload',
			array(
				'methods'             => 'POST',
				'callback'            => array( ProfilePicture::class, 'handle_upload_rest' ),
				'permission_callback' => array( ProfilePicture::class, 'check_nonce_permission' ),
			)
		);

		// Profile picture remove endpoint.
		register_rest_route(
			ApiModule::NAMESPACE,
			'/account/profile-picture/remove',
			array(
				'methods'             => 'POST',
				'callback'            => array( ProfilePicture::class, 'handle_remove_rest' ),
				'permission_callback' => array( ProfilePicture::class, 'check_nonce_permission' ),
			)
		);

		// Profile update endpoint.
		register_rest_route(
			ApiModule::NAMESPACE,
			'/account/profile',
			array(
				'methods'             => 'POST',
				'callback'            => array( self::class, 'update_profile_handler' ),
				'permission_callback' => array( ProfilePicture::class, 'check_nonce_permission' ),
			)
		);
	}

	/**
	 * Handle account profile updates via REST endpoint.
	 *
	 * @param \WP_REST_Request $request REST request object.
	 *
	 * @return \WP_REST_Response|\WP_Error Response with update result.
	 */
	public static function update_profile_handler( \WP_REST_Request $request ) {

		if ( ! is_user_logged_in() ) {
			return new \WP_Error(
				'not_logged_in',
				__( 'You must be logged in to update your profile.', 'ambassadorhub' ),
				array( 'status' => 403 )
			);
		}

		$user_id = get_current_user_id();
		$params  = $request->get_params();

		if ( isset( $params['first_name'] ) ) {
			$first_name = sanitize_text_field( (string) $params['first_name'] );
			update_user_meta( $user_id, 'first_name', $first_name );
		}

		if ( isset( $params['last_name'] ) ) {
			$last_name = sanitize_text_field( (string) $params['last_name'] );
			update_user_meta( $user_id, 'last_name', $last_name );
		}

		$address_meta_keys = array( 'ambh_street', 'ambh_city', 'ambh_postal_code', 'ambh_country' );
		foreach ( $address_meta_keys as $meta_key ) {
			if ( isset( $params[ $meta_key ] ) ) {
				update_user_meta( $user_id, $meta_key, sanitize_text_field( (string) $params[ $meta_key ] ) );
			}
		}

		AccountFields::save_from_request( $user_id, $params, 'profile' );
		AccountFields::maybe_update_display_name( $user_id );

		do_action( 'ambh_profile_save_fields', $user_id, $params );
		do_action( 'ambh_profile_updated', $user_id );

		return rest_ensure_response(
			array(
				'success' => true,
				'message' => __( 'Profile updated successfully.', 'ambassadorhub' ),
			)
		);
	}

	/**
	 * Handle email verification via REST endpoint.
	 *
	 * @param \WP_REST_Request $request REST request object.
	 *
	 * @return \WP_REST_Response|\WP_Error Response with verification result.
	 */
	public static function verify_email_handler( \WP_REST_Request $request ) {
		$token   = $request->get_param( 'token' );
		$user_id = $request->get_param( 'user_id' );

		if ( ! $token ) {
			return new \WP_Error(
				'missing_token',
				'Verification token is required.',
				array( 'status' => 400 )
			);
		}

		// Pass user_id to verify_token for efficient direct lookup.
		$verified_user_id = EmailVerification::verify_token( $token, $user_id );

		if ( ! $verified_user_id ) {
			return new \WP_Error(
				'invalid_token',
				'Verification token is invalid or has expired.',
				array( 'status' => 400 )
			);
		}

		return rest_ensure_response(
			array(
				'success' => true,
				'message' => __( 'Email verified successfully. Your account is now active.', 'ambassadorhub' ),
				'user_id' => $verified_user_id,
			)
		);
	}
}
