<?php


namespace Pinova\API;

use Exception;
use Pinova\Channels\SMS;
use Pinova\Objects\Identifier;
use Pinova\Services\UserService;
use Pinova\Services\ValidationService;
use WP_REST_Request;

defined( 'ABSPATH' ) || exit;

class AdminAPI extends RestAPI {

	public const ROUTE_PERMISSION = [
		'/pinova/admin/users/create' => 'edit_shop_orders',
		'/pinova/admin/test/sms'     => 'manage_options',
	];

	public function register_routes() {

		register_rest_route( 'pinova/admin/users', '/create', [
			'methods'             => 'POST',
			'callback'            => [ $this, 'user_create' ],
			'permission_callback' => [ $this, 'permission_callback' ],
			'args'                => [
				'first_name' => [
					'required'          => true,
					'sanitize_callback' => 'sanitize_text_field',
					'validate_callback' => [ ValidationService::class, 'not_empty' ],
				],
				'last_name'  => [
					'required'          => true,
					'sanitize_callback' => 'sanitize_text_field',
					'validate_callback' => [ ValidationService::class, 'not_empty' ],
				],
				'mobile'     => [
					'required'          => true,
					'validate_callback' => [ ValidationService::class, 'mobile' ],
				],
				'email'      => [
					'required'          => false,
					'validate_callback' => [ ValidationService::class, 'email' ],
				],
			],
		] );

		register_rest_route( 'pinova/admin/test', '/sms', [
			'methods'             => 'POST',
			'callback'            => [ $this, 'test_sms' ],
			'permission_callback' => [ $this, 'permission_callback' ],
			'args'                => [
				'identifier' => [
					'required'          => true,
					'validate_callback' => [ ValidationService::class, 'identifier' ],
				],
			],
		] );

	}

	/**
	 * @param WP_REST_Request $request
	 *
	 * @return void
	 */
	public function user_create( WP_REST_Request $request ): void {
		/** @var Identifier $mobile */
		$mobile = $request->get_param( 'mobile' );

		/** @var ?Identifier $email */
		$email = $request->get_param( 'email' );

		$first_name = $request->get_param( 'first_name' );
		$last_name  = $request->get_param( 'last_name' );

		$user_id = UserService::match( $mobile );

		if ( $user_id ) {
			self::response( false, sprintf( __( 'کاربر با تلفن همراه %s وجود دارد.', 'pinova' ), $mobile->get_value() ) );
		}

		if ( $email ) {

			$user_id = UserService::match( $email );

			$email = $email->get_value();

			if ( $user_id ) {
				self::response( false, sprintf( __( 'کاربر با ایمیل %s وجود دارد.', 'pinova' ), $email ) );
			}

		}

		try {

			$user_id = UserService::create( $mobile->get_value(), $email, [
				'first_name' => $first_name,
				'last_name'  => $last_name,
			] );

		} catch ( Exception $e ) {
			self::response( false, $e->getMessage() );
		}

		$message = sprintf(
			__( 'حساب کاربری «%s %s» با تلفن همراه %s با موفقیت ایجاد شد.', 'pinova' ),
			$first_name,
			$last_name,
			$mobile->get_value()
		);

		self::response( true, $message, [
			'user_id' => $user_id,
		] );
	}

	/**
	 * @param WP_REST_Request $request
	 *
	 * @return void
	 */
	public function test_sms( WP_REST_Request $request ): void {

		/** @var Identifier $identifier */
		$identifier = $request->get_param( 'identifier' );

		$code = mt_rand( 10_00_00, 99_99_99 );

		try {

			SMS::send_code( $identifier->get_value(), $code );

			$message = sprintf( "کد تایید «%d» با موفقیت پیامک شد.", $code );
			$success = true;

		} catch ( Exception $e ) {
			$message = $e->getMessage();
			$success = false;
		}

		self::response( $success, $message );
	}

	/**
	 * @param WP_REST_Request $request
	 *
	 * @return bool
	 */
	public function permission_callback( WP_REST_Request $request ): bool {
		return current_user_can( self::ROUTE_PERMISSION[ $request->get_route() ] ?? 'manage_options' );
	}
}
