<?php

defined('ABSPATH') or die();

function drk_get_captcha()
{
    $code = substr(str_shuffle('0123456789'), 0, 6);

    session_start();
    $_SESSION['captcha'] = crypt($code, CAPTCHA_SECRET);
    session_write_close();

    $image = imagecreate(150, 44);
    imagecolorallocate($image, 58, 58, 58);

    $size = 32;
    $color = imagecolorallocate($image, 129, 129, 129);
    $font = dirname(__DIR__,4) . '/files/oswald.ttf';
    $angle = rand(-2, 2);
    $x = 5;
    $y = 42;
    imagefttext($image, $size, $angle, $x, $y, $color, $font, $code);

    $color = imagecolorallocate($image, 196, 196, 196);
    imagefilledpolygon($image, [0, 25, 0, 28, 150, 20, 150, 17], 4, $color);

    header('Cache-Control: no-store, must-revalidate');
    header('Expires: 0');
    header('Content-Type: image/png');
    imagepng($image);
    imagedestroy($image);
}

function captcha_rest()
{
    register_rest_route('auth/v1', '/captcha', [
        'methods' => 'POST',
        'callback' => 'drk_get_captcha',
        'permission_callback' => '__return_true'
    ]);
}

add_action('rest_api_init', 'captcha_rest');

function drk_check_captcha(WP_REST_Request $param){
    $code = crypt(trim($param), CAPTCHA_SECRET);
    session_start();
    $captcha = $_SESSION['captcha'];
    unset($_SESSION['captcha']);
    if (!$captcha) return false;
    return $captcha === $code;
}

function drk_check_captcha_rest(){
    register_rest_route('auth/v1', '/check_captcha', [
        'methods' => 'POST',
        'callback' => 'drk_check_captcha',
        'permission_callback' => '__return_true'
    ]);
}
add_action('rest_api_init', 'drk_check_captcha_rest');