<?php

function drk_get_token($login_data)
{

    $site_url = get_site_url();

    if ($_SERVER['SERVER_NAME'] == 'localhost') {

        $site_url = "http://" . $_SERVER['SERVER_ADDR'] . ":" . $_SERVER["SERVER_PORT"];
    }
    $http_client = new WP_Http();
    $args = array(
        'method' => 'POST',
        'body' => $login_data
    );

    return $http_client->request($site_url . '/wp-json/jwt-auth/v1/token', $args);
}

function drk_validate_token($token)
{

    $site_url = get_site_url();
    if ($_SERVER['SERVER_NAME'] == 'localhost') {
        $site_url = "http://" . $_SERVER['SERVER_ADDR'] . ":" . $_SERVER["SERVER_PORT"];
    }
    $http_client = new WP_Http();
    $args = array(
        'method' => 'POST',
        'headers' => array(
            'Authorization' => "Bearer " . $token,
        ),
    );
    $data = $http_client->request($site_url . '/wp-json/jwt-auth/v1/token/validate', $args);
    if (json_decode($data["body"])->data->status != 200)
        return false;
    $user = wp_get_current_user();
    if($user->data->ID === null)
        return false;
    $roles = $user->get_role_caps();
    $twoFa = false;
    $twoFaAuth = get_the_author_meta('drk_otp_is_active', $user->data->ID);
    $twoFaEmail = get_the_author_meta('user_otp_mail_code', $user->data->ID);
    $twoFaPGP = get_the_author_meta('drk_pgp_is_enabled', $user->data->ID);
    $email_is_confirmed = get_the_author_meta('drk_email_is_confirmed', $user->data->ID);
    $profile = drk_get_user_profile((array)$user->data);
    if (strlen(trim($twoFaAuth)) > 0) {
        $twoFa = "Auth";
    } elseif (strlen(trim($twoFaEmail)) > 0) {
        $twoFa = "Email";
    } elseif ($twoFaPGP == 'true') {
        $twoFa = 'PGP';
    }

    $resp = array(
        'token' => $token,
        'user_email' => $user->data->user_email,
        'user_nicename' => $user->data->user_nicename,
        'user_display_name' => $user->data->display_name,
        "user_id" => $user->data->ID,
        "user_role" => get_userdata($user->data->ID)->roles,
        "user_caps" => $roles,
        "user_registered" => $user->data->user_registered,
        "2fa" => $twoFa,
        "is_email_confirmed" => $email_is_confirmed,
        "profile" => $profile
    );
    return $resp;
}

function drk_generate_otp_code()
{
    $g = new Sonata\GoogleAuthenticator\GoogleAuthenticator();
    return $g->generateSecret();
}

function drk_generate_confirmation_code()
{
    return substr(str_shuffle('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 6);
}

function drk_generate_secret_code()
{
    return substr(str_shuffle('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 16);
}