<?php

defined('ABSPATH') or die();

function enable_mail_auth()
{
    $user = wp_get_current_user();

    if (!$user) {
        return new WP_Error('invalid_otp', 'Not authorized', array('status' => 401));
    }

    update_user_meta($user->ID, 'user_otp_mail_code', drk_generate_otp_code());
    delete_user_meta($user->ID, 'user_otp_secret','');
    update_user_meta($user->ID, 'drk_pgp_is_active', "false");
    delete_user_meta($user->ID, 'user_pgp_key', '');

    return 'ok';
}

function disable_mail_auth()
{
    $user = wp_get_current_user();

    if (!$user) {
        return new WP_Error('invalid_otp', 'Not authorized', array('status' => 401));
    }

    delete_user_meta($user->ID, 'user_otp_mail_code');

    return 'ok';
}

function verify_mail_auth(WP_REST_Request $request)
{
    $secret_key = defined('JWT_AUTH_SECRET_KEY') ? JWT_AUTH_SECRET_KEY : false;

    $token = $request->get_param('token');

    try {
        $data = Firebase\JWT\JWT::decode($token, $secret_key . 'verify', ['HS256']);
    } catch (Exception $e) {
        return new WP_Error('invalid_token', $e->getMessage(), array('status' => 401));
    }

    $user = get_user_by('ID', $data->data->user->ID);

    if (!$user) {
        return new WP_Error('invalid_otp', 'Not authorized', array('status' => 401));
    }

    $otpSecret = get_user_meta($user->ID, 'user_otp_mail_code', true);

    if (!$otpSecret) {
        return new WP_Error('invalid_otp', 'Otp mail disable', array('status' => 500));
    }

    if ($otpSecret !== $request->get_param('code')) {
        return new WP_Error('invalid_otp', 'Invalid otp code', array('status' => 400));
    }

    $issuedAt = time();
    $notBefore = $issuedAt;
    $expire = $issuedAt + (DAY_IN_SECONDS * 7);

    $token = [
        'iss' => get_bloginfo('url'),
        'iat' => $issuedAt,
        'nbf' => $notBefore,
        'exp' => $expire,
        'data' => [
            'user' => [
                'id' => $user->ID,
            ],
        ],
    ];

    $email_is_confirmed = get_the_author_meta('drk_email_is_confirmed',$user->data->ID);
    $profile = drk_get_user_profile((array)$user->data);
    $roles = $user->get_role_caps();

    return [
        'token' => Firebase\JWT\JWT::encode($token, $secret_key),
        '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" => "Mail",
        "is_email_confirmed" => $email_is_confirmed,
        "profile" => $profile
    ];
}

add_action('rest_api_init', 'get_2fa_mail_rest');
function get_2fa_mail_rest()
{

    register_rest_route('2fa/v1', '/enable-mail', [
        'methods' => 'POST',
        'callback' => 'enable_mail_auth',
        'permission_callback' => '__return_true'
    ]);

    register_rest_route('2fa/v1', '/disable-mail', [
        'methods' => 'POST',
        'callback' => 'disable_mail_auth',
        'permission_callback' => '__return_true'
    ]);

    register_rest_route('2fa/v1', '/verify-mail', [
        'methods' => 'POST',
        'callback' => 'verify_mail_auth',
        'permission_callback' => '__return_true'
    ]);

}

add_filter('jwt_auth_token_before_dispatch', 'check_mail_auth_is_enable', 10, 2);
function check_mail_auth_is_enable($data, $user)
{
    $otpSecret = get_user_meta($user->id, 'user_otp_mail_code', true);

    if (!$otpSecret) {
        return $data;
    }

    $otpSecret = drk_generate_otp_code();
    update_user_meta($user->ID, 'user_otp_mail_code', $otpSecret);

    $secret_key = defined('JWT_AUTH_SECRET_KEY') ? JWT_AUTH_SECRET_KEY : false;
    $issuedAt = time();
    $notBefore = $issuedAt;
    $expire = $issuedAt + 3600;

    //drk_send_mail($user, 'Darkey: OTP code', $otpSecret);

    wp_mail($user->data->user_email,'Darkey: OTP code', $otpSecret);
    $token = [
        'iss' => get_bloginfo('url'),
        'iat' => $issuedAt,
        'nbf' => $notBefore,
        'exp' => $expire,
        'data' => [
            'user' => [
                'id' => $user->ID,
            ],
        ],
    ];

    $jwt = Firebase\JWT\JWT::encode($token, $secret_key . 'verify');

    return new WP_Error('invalid_otp', 'OTP Auth is enabled', ['checker' => 'mailer', 'token' => $jwt, 'status' => 403]);
}
