<?php

defined('ABSPATH') or die();

function registration(WP_REST_Request $request)
{
    $resp = wp_create_user(
        $request->get_param('login'),
        $request->get_param('password'),
        $request->get_param('email'),
    );

    if (!is_wp_error($resp)){
        $new_user = get_user_by("ID", $resp);
        drk_create_user_profile($new_user);

        return [
            'token' => false,
            'user_email' => $request->get_param('email'),
            'user_nicename' => $request->get_param('login'),
            "user_id" => $resp,
            "2fa" => false,
            "is_email_confirmed" => false,
            "user_avatar" => false
        ];
    }
    return $resp;
}

function registration_rest()
{

    register_rest_route('auth/v1', '/registration', [
        'methods' => 'POST',
        'callback' => 'registration',
        'permission_callback' => '__return_true',
        'args' => [
            'login' => [
                'required' => true,
                'type' => 'string',
            ],
            'email' => [
                'required' => true,
                'type' => 'email',
            ],
            'password' => [
                'required' => true,
                'type' => 'string',
            ],
            'captcha' => [
                'required' => true,
                'validate_callback' => function ($param) {
                    $code = crypt(trim($param), CAPTCHA_SECRET);
                    session_start();

                    $captcha = $_SESSION['captcha'];
                    unset($_SESSION['captcha']);

                    if (!$captcha) return false;

                    return $captcha === $code;
                },
                'type' => 'string',
            ],
        ]
    ]);
}

add_action('rest_api_init', 'registration_rest');