<?php

namespace VinCSS\TwoFactor\Model;

use Exception;

class Profile2FA
{

    public function manager2FA()
    {

        global $user_id;
        $validate_nonce = wp_create_nonce('vincss_remove_2fa');
?>
        <p class="text-danger description mt-1" id="error_2fa_remove"></p>

        <?php
        $is_reset = true;
        $this->Setup2FA($is_reset);
        $vincss_2fa_backup_code = getOption('is_backup_code');
        if ($vincss_2fa_backup_code === 'true') {
            $this->generateRecoveryCode();
        }

        ?>

        <button user-id="<?php echo esc_attr($user_id) ?>" data-nonce="<?php echo esc_attr($validate_nonce); ?>" type="button" id="v_remove_2fa" class="button button-danger ms-2">
            <div class="flex align-items-center">
                <span class="me-1 btn_loading spinner-grow spinner-grow-sm" id="remove_2fa_loading" role="status" aria-hidden="true"></span><span> <?php _e('Remove 2FA', 'vincss-fido2-login'); ?></span>
            </div>
        </button>
    <?php
    }


    public function setup2FA($is_reset = false)
    {
        global $user_id;
    ?>
        <p class="description mb-2">
            <?php _e('Increase your account\'s security by enabling Two-Factor Authentication (2FA).', 'vincss-fido2-login'); ?>
        </p>
        <button type="button" class="button  <?php echo ($is_reset) ? "btn-secondary" : "btn-primary"; ?>" data-bs-toggle="modal" data-bs-target="#vincss-2fa-modal-setup">
            <?php $is_reset ? _e("Reset 2FA", 'vincss-fido2-login') : _e("Setup 2FA", 'vincss-fido2-login'); ?>
        </button>
    <?php
        $this->renderModalSetup($user_id);
    }


    public function renderModalSetup($user_id)
    {
        $google2fa = new Generate2FA();
        $site_url = get_site_url();
        $user_login = get_user_by('id', $user_id)->user_login;
        $validate_nonce = wp_create_nonce('vincss_validate_2fa_form');
        $secret_key = $google2fa->generateSecretKey();
        $qrcode_img = $google2fa->generateQRCodeImage($site_url, $user_login, $secret_key);

    ?>
        <div class="modal fade" id="vincss-2fa-modal-setup" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">

            <div class="modal-dialog modal-lg modal-dialog-centered modal-2fa">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel"><?php _e('Setup two-factor authentication', 'vincss-fido2-login'); ?></h5>

                        <button type="button" class="btn-close btn-close-modal-2fa" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body pb-0" id="setup-2fa-form">
                        <p class="description"><?php _e('Use a one-time password authenticator on your mobile device or computer to enable two-factor authentication (2FA).', 'vincss-fido2-login'); ?></p>
                        <p class="description"><?php _e('We recommend cloud-based mobile authenticator apps such as Authy, Duo Mobile, and LastPass. They can restore access if you lose your hardware device.', 'vincss-fido2-login'); ?></p>
                        <div class="d-flex account-well">
                            <img class="d-block mx-auto qr_code" src="<?php echo esc_attr($qrcode_img) ?>" />
                            <div class="mt-3">
                                <p class="description"> <?php _e('Can\'t scan the code?', 'vincss-fido2-login'); ?></p>
                                <p class="description"><?php _e('To add the entry manually, provide the following details to the application on your phone.', 'vincss-fido2-login'); ?></p>
                                <p class="description"><?php _e('Account:', 'vincss-fido2-login'); ?> <code><?php echo esc_url($site_url) . ' (' . esc_html($user_login) . ')' ?></code></p>
                                <p class="description"><?php _e('Key:', 'vincss-fido2-login'); ?> <code><?php echo esc_html($secret_key) ?></code></p>
                                <p class="description"><?php _e('Time based:', 'vincss-fido2-login'); ?> <code?><?php _e('Yes', 'vincss-fido2-login'); ?></code></p>
                            </div>
                        </div>
                        <p class="description mt-3"><?php _e('Enter the security code generated by your two-factor authentication app.', 'vincss-fido2-login'); ?></p>
                        <input type="hidden" value="<?php echo esc_attr($secret_key); ?>" name="v_2fa_secret">
                        <input type="hidden" value="<?php echo esc_attr($user_id); ?>" name="v_user_id">
                        <input value="" name="v_otp" class="input_otp" placeholder="<?php _e('Pin code', 'vincss-fido2-login'); ?>">
                        <p class="text-danger description mt-1" id="error_2fa_setup"></p>
                        <div class="modal-footer">
                            <button type="button" class="button button-secondary me-2  btn-close-modal-2fa" data-bs-dismiss="modal"><?php _e('Cancel', 'vincss-fido2-login'); ?></button>
                            <button data-nonce="<?php echo esc_attr($validate_nonce); ?>" type="button" id="v_enable_2fa" class="button button-primary">
                                <div class="flex align-items-center">
                                    <span class="me-1 btn_loading spinner-grow spinner-grow-sm" id="setup_2fa_loading" role="status" aria-hidden="true"></span><span><?php _e('Enable', 'vincss-fido2-login'); ?></span>
                                </div>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    <?php }


    public function generateRecoveryCode()
    {
        global $user_id;
        $validate_nonce = wp_create_nonce('v_recovery_2fa');
    ?>
        <button type="button" user-id="<?php echo $user_id ?>" data-nonce="<?php echo esc_attr($validate_nonce); ?>" class="button btn-primary ms-2" id="v_recovery_2fa">
            <?php _e('Generate Backup Codes', 'vincss-fido2-login'); ?>
        </button>
    <?php
        $this->renderModalRecovery($user_id);
    }

    public function renderModalRecovery($user_id)
    {


    ?>
        <div class="modal fade" id="vincss-2fa-generate-backup-codes" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">

            <div class="modal-dialog modal-md modal-dialog-centered modal-2fa">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel"><?php _e('Two-Factor Authentication Recovery codes', 'vincss-fido2-login'); ?>
                        </h5>

                        <button type="button" class="btn-close btn-close-modal-2fa" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body pb-0" id="setup-2fa-form">
                        <div class="justify-content-center py-5" id="loading_recovery_code">
                            <span class="me-1 spinner-border spinner-border"></span>
                        </div>
                        <p class="text-danger description mt-1" id="error_2fa_recovery"></p>
                        <div class="v_list_code_recovery">
                            <p class="description"><?php _e('Here are your backup codes:', 'vincss-fido2-login'); ?></p>
                            <ul style="list-style-type: disc; padding: 16px; padding-left: 32px; border: solid 1px #dbdbdb; border-radius: 4px">
                            </ul>
                            <!-- <textarea class="w-100" rows="10" disabled></textarea> -->
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="button button-secondary me-2  btn-close-modal-2fa" data-bs-dismiss="modal"><?php _e('Close', 'vincss-fido2-login'); ?></button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
<?php }

    public function verifyOTP()
    {

        check_ajax_referer('vincss_validate_2fa_form');

        // $nonce = filter_input(INPUT_POST, '_wpnonce', FILTER_SANITIZE_STRING);

        $payload = sanitizeArray($_POST['payload']);
        $our_errors = '';

        if (isset($payload['v_2fa_secret'])) {
            $secret = wp_unslash($payload['v_2fa_secret']);
        }
        if (isset($payload['v_otp'])) {
            $otp = wp_unslash($payload['v_otp']);
        }

        if ($secret && $otp) {
            $google2fa = new Generate2FA();
            $is_valid = $google2fa->verifyOTP($secret, $otp);
            if (!$is_valid) {
                $our_errors = 'Invalid pin code';
            }
        } else {
            $our_errors = 'Please enter the code.';
        }

        if (!empty($our_errors)) {
            // Send the response.
            wp_send_json_error(
                array(
                    'error' => $our_errors,
                ),
                400
            );
        } else {
            update_user_meta($payload['v_user_id'], 'vincss_2fa_secret', $secret);
            update_user_meta($payload['v_user_id'], 'vincss_enable_2fa', 1);
            wp_send_json_success();
        }
    }




    public function remove2FA()
    {
        check_ajax_referer('vincss_remove_2fa');

        if (!isset($_POST['user_id'])) {
            return 'No user_id';
        }
        $user_id =
            filter_input(INPUT_POST, 'user_id', FILTER_SANITIZE_STRING);
        $our_errors = '';

        if (isset($user_id)) {
            update_user_meta($user_id, 'vincss_enable_2fa', 0);
            delete_user_meta($user_id, 'vincss_2fa_secret');
            delete_user_meta($user_id, 'vincss_recovery_code');
            wp_send_json_success();
        } else {
            $our_errors = 'Error!';
            wp_send_json_error(
                array(
                    'error' => $our_errors,
                ),
                400
            );
        }
    }

    public function handleGenerateRecovery()
    {
        check_ajax_referer('v_recovery_2fa');

        if (!isset($_POST['user_id'])) {
            return 'No user_id';
        }
        $user_id = filter_input(INPUT_POST, 'user_id', FILTER_SANITIZE_STRING);
        $our_errors = '';

        if (isset($user_id)) {;

            $google2fa = new Generate2FA();
            $codes = $google2fa->generateRecoveryCode();
            update_user_meta($user_id, 'vincss_recovery_code', $codes);
            wp_send_json_success(
                array(
                    'codes' => $codes,
                ),
                201
            );
        } else {
            $our_errors = 'Error! Please try again!';
            wp_send_json_error(
                array(
                    'error' => $our_errors,
                ),
                400
            );
        }
    }
}
