<?php


defined('ABSPATH') or die();


function drk_login(WP_REST_Request $request)
{
    global $error;
    $login_data = json_decode($request->get_body(),true);
    $resp = drk_get_token($login_data);
    if (!is_wp_error($resp))
        return json_decode($resp['body']);
    return $resp;
}

function drk_auth_rest()
{
    register_rest_route('auth/v1', '/login', [
        'methods' => 'POST',
        'callback' => 'drk_login',
        'permission_callback' => '__return_true',
        'args' => [
            'username' => [
                'required' => true,
                'type' => 'string',
            ],
            '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', 'drk_auth_rest');
