<?php

namespace Lknwp\CrowdfundingExtension\Includes;

defined('ABSPATH') || exit;

final class LknwpCrowdfundingExtensionSimpleRegistration
{
    public function __construct()
    {
        add_action('wp_ajax_lkn_simple_wpcf_registration', array($this, 'lkn_simple_registration_save_action'));
        add_action('wp_ajax_nopriv_lkn_simple_wpcf_registration', array($this, 'lkn_simple_registration_save_action'));
    }

    public function lkn_simple_registration_callback()
    {
        ob_start();
        if (is_user_logged_in()) { ?>
            <h3 class="wpneo-center">
                <?php esc_html_e("You are already logged in.", "link-nacional-wp-crowdfunding-extension"); ?>
            </h3>
            <?php } else {
    global $lknwp_reg_errors,$lknwp_reg_success;
    ?>
<div class="wpneo-user-registration-wrap">
    <form
        action="<?php echo esc_url(isset($_SERVER['REQUEST_URI']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])) : ''); ?>"
        id="wpneo-registration"
        method="post"
    >
        <div
            id="form-errors"
            class="form-errors"
        ></div>
        <div id="form-success"></div>
        <?php echo wp_kses_post(wp_nonce_field('lkn_wpcf_form_action', 'lkn_wpcf_form_action_field', true, false)); ?>
        <?php
        if (get_option('lkn_wpcf_email_is_username') == 1) {
            $regisration_data = array(
                array(
                    'id' => 'lkn_email',
                    'label' => __("Email *", "link-nacional-wp-crowdfunding-extension"),
                    'type' => 'text',
                    'placeholder' => __('Enter Email', 'link-nacional-wp-crowdfunding-extension'),
                    'value' => '',
                    'warpclass' => '',
                    'class' => 'required',
                    'autocomplete' => 'off',
                    'required' => 'required',
                ),

                array(
                    'id' => 'lkn_password',
                    'label' => __('Password *', 'link-nacional-wp-crowdfunding-extension'),
                    'type' => 'password',
                    'placeholder' => __('Enter Password', 'link-nacional-wp-crowdfunding-extension'),
                    'class' => 'required',
                    'warpclass' => '',
                    'autocomplete' => 'off',
                    'required' => 'required',
                ),
            );
        } else {
            $regisration_data = array(
                array(
                    'id' => 'lkn_username',
                    'label' => __("Username *", "link-nacional-wp-crowdfunding-extension"),
                    'type' => 'text',
                    'placeholder' => __('Enter Username', 'link-nacional-wp-crowdfunding-extension'),
                    'value' => '',
                    'class' => 'required',
                    'warpclass' => '',
                    'autocomplete' => 'off',
                    'required' => 'required',
                ),
                array(
                    'id' => 'lkn_email',
                    'label' => __("Email *", "link-nacional-wp-crowdfunding-extension"),
                    'type' => 'email',
                    'placeholder' => __('Enter Email', 'link-nacional-wp-crowdfunding-extension'),
                    'value' => '',
                    'warpclass' => '',
                    'class' => 'required',
                    'autocomplete' => 'off',
                    'required' => 'required',
                ),
                array(
                    'id' => 'lkn_password',
                    'label' => __('Password *', 'link-nacional-wp-crowdfunding-extension'),
                    'type' => 'password',
                    'placeholder' => __('Enter Password', 'link-nacional-wp-crowdfunding-extension'),
                    'class' => 'required',
                    'warpclass' => '',
                    'autocomplete' => 'off',
                    'required' => 'required',
                ),
            );
        }

    $regisration_meta = apply_filters('wpcf_user_registration_fields', $regisration_data);

    foreach ($regisration_meta as $item) { ?>
        <div
            class="wpneo-single <?php echo esc_attr(isset($item['warpclass']) ? $item['warpclass'] : ""); ?>">
            <div class="wpneo-name">
                <?php echo esc_html(isset($item['label']) ? $item['label'] : ""); ?>
            </div>
            <div class="wpneo-fields">
                <?php
                switch ($item['type']) {
                    case 'text':
                        echo '<input type="text" id="' . esc_attr($item['id']) . '" autocomplete="' . esc_attr($item['autocomplete']) . '" class="' . esc_attr($item['class']) . '" name="' . esc_attr($item['id']) . '" placeholder="' . esc_attr($item['placeholder']) . '" required="' . esc_attr($item['required']) . '">';
                        break;
                    case 'email':
                        echo '<input type="email" id="' . esc_attr($item['id']) . '" autocomplete="' . esc_attr($item['autocomplete']) . '" class="' . esc_attr($item['class']) . '" name="' . esc_attr($item['id']) . '" placeholder="' . esc_attr($item['placeholder']) . '" required="' . esc_attr($item['required']) . '">';
                        break;
                    case 'password':
                        echo '<input type="password" id="' . esc_attr($item['id']) . '" autocomplete="' . esc_attr($item['autocomplete']) . '" class="' . esc_attr($item['class']) . '" name="' . esc_attr($item['id']) . '" placeholder="' . esc_attr($item['placeholder']) . '" required="' . esc_attr($item['required']) . '">';
                        break;
                    case 'textarea':
                        echo '<textarea id="' . esc_attr($item['id']) . '" autocomplete="' . esc_attr($item['autocomplete']) . '" class="' . esc_attr($item['class']) . '" name="' . esc_attr($item['id']) . '"></textarea>';
                        break;
                    case 'submit':
                        echo '<input type="submit" id="' . esc_attr($item['id']) . '" class="' . esc_attr($item['class']) . '" name="' . esc_attr($item['id']) . '" />';
                        break;
                    case 'shortcode':
                        echo do_shortcode($item['shortcode']);
                        break;
                } ?>
            </div>
        </div>
        <?php } ?>

        <div class="wpneo-single wpneo-register">
            <input
                type="hidden"
                name="action"
                value="lkn_simple_wpcf_registration"
            />
            <input
                type="hidden"
                name="current_page"
                value="<?php echo esc_url(get_the_permalink()); ?>"
            />
            <?php wp_nonce_field('lkn_wpcf_verify_register', 'lkn_verify_register'); ?>

            <input
                type="submit"
                class="wpneo-submit-campaign"
                id="lkn-user-registration-btn"
                value="<?php esc_html_e('Sign UP', 'link-nacional-wp-crowdfunding-extension'); ?>"
                name="submits"
            />
        </div>

    </form>
</div>
<?php
}
        return ob_get_clean();
    }

    // register a new user
    public function lkn_simple_registration_save_action(): void
    {

        if (!isset($_POST['lkn_verify_register']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['lkn_verify_register'])), 'lkn_wpcf_verify_register')) {
            die(wp_json_encode(array('success' => 0, 'message' => __('Sorry, your status did not verify.', 'link-nacional-wp-crowdfunding-extension'))));
            exit;
        }

        $username = $password = $email = '';
        $password = isset($_POST['lkn_password']) ? sanitize_text_field(wp_unslash($_POST['lkn_password'])) : '';
        $email = isset($_POST['lkn_email']) ? sanitize_email(wp_unslash($_POST['lkn_email'])) : '';

        if (get_option('lkn_wpcf_email_is_username') == 1) {
            list($username) = explode('@', $email);
            $original_username = $username;
            $suffix = 1;
            while (username_exists($username)) {
                $username = $original_username . $suffix;
                $suffix++;
            }
        } else {
            $username = isset($_POST['lkn_username']) ? sanitize_user(wp_unslash($_POST['lkn_username'])) : '';
        }

        $this->lkn_simple_registration_validation($username, $password, $email);
        $this->lkn_simple_complete_registration($username, $password, $email);
    }

    public function lkn_simple_complete_registration($username, $password, $email): void
    {
        global $lknwp_reg_errors;
        if (count($lknwp_reg_errors->get_error_messages()) < 1) {

            header('Content-Type: application/json');

            $registroPorValidacao = get_option('lkn_wpcf_registro_por_validacao');
            if ($registroPorValidacao !== false && $registroPorValidacao != 0) {
                $token = bin2hex(random_bytes(16));
                $user_token = array(
                    'email' => $email,
                    'username' => $username,
                    'password' => $password,
                    'token' => $token,
                    'timestamp' => time()
                );

                $email_sent = get_option('lkn_send_email_verification_' . $email, false);
                if ($email_sent) {
                    die(wp_json_encode(array(
                        'success' => 0,
                        'message' => 'Um email de verificação já foi enviado! Verifique sua caixa de entrada.',
                    )));
                }

                $nonce = wp_create_nonce('lkn_registration_nonce');

                // Salva o token no banco de dados
                update_option('lkn_custom_email_verification_' . $token, maybe_serialize($user_token), false);

                // Envia email de verificação
                $verification_url = add_query_arg(array(
                    'token' => $token,
                    'nonce' => $nonce
                ), home_url('wp-json/lknwpcrowdfunding/v1/complete-registration'));

                $subject = 'ParaQuemDoar: Verificação de Email';
                $message = 'Pronto! Seu cadastro no ParaQuemDoar.org esta quase concluído! Agora só falta clicar no <a href="' . $verification_url . '" target="_blank">link</a> assim garantimos sua segurança e validamos seu endereço de e-mail. <a href="' . $verification_url . '" target="_blank"> Ativar agora seu registro.</a>';
                $headers = array('Content-Type: text/html; charset=UTF-8');

                if (wp_mail($email, $subject, $message, $headers)) { // Email enviado com sucesso

                    //Option de email enviado com timestamp
                    $option_value = array(
                        'value' => true,
                        'timestamp' => time()
                    );
                    update_option('lkn_send_email_verification_' . $email, maybe_serialize($option_value));

                    $redirect_uri = get_option('lkn_wpcf_redurl_envio_email');

                    $response = array(
                        'success' => 1,
                        'message' => 'Um email de verificação foi enviado. Verifique sua caixa de entrada.',
                        'validation' => 1
                    );

                    if (empty($redirect_uri)) {
                        die(wp_json_encode($response));
                    }

                    die(wp_json_encode(array(
                        'success' => 1,
                        'message' => 'Um email de verificação foi enviado. Verifique sua caixa de entrada.' ,
                        'redirect' => $redirect_uri,
                        'validation' => 1
                    )));
                } else {
                    die(wp_json_encode(array(
                        'success' => 0,
                        'message' => 'Erro ao enviar email de verificação. Por favor, tente novamente.',
                    )));
                }
            } else {
                $userdata = array(
                    'user_login' => $username,
                    'user_email' => $email,
                    'user_pass' => $password,
                );
                $user_id = wp_insert_user($userdata);

                //On success
                if (! is_wp_error($user_id)) {
                    WC()->mailer(); // load email classes
                    do_action('wpcf_after_user_registration', $user_id);

                    $saved_redirect_uri = get_option('wpcf_redurl');

                    $redirect = $saved_redirect_uri ? $saved_redirect_uri : 'Nenhuma';

                    header('Content-Type: application/json');
                    echo wp_json_encode(array('success' => 1, 'message' => 'Registro feito com sucesso!', 'validation' => 0, 'redirect' => $redirect));
                    exit();
                } else {
                    $errors = '';
                    if (is_wp_error($lknwp_reg_errors)) {
                        foreach ($lknwp_reg_errors->get_error_messages() as $error) {
                            $errors .= '<strong>' . __('ERROR', 'link-nacional-wp-crowdfunding-extension') . '</strong>:' . $error . '<br />';
                        }
                    }
                    die(wp_json_encode(array('success' => 0, 'message' => $errors)));
                }
            }
        } else {
            $errors = '';
            if (is_wp_error($lknwp_reg_errors)) {
                foreach ($lknwp_reg_errors->get_error_messages() as $error) {
                    $errors .= '<strong>' . __('ERROR', 'link-nacional-wp-crowdfunding-extension') . '</strong>:' . $error . '<br />';
                }
            }
            die(wp_json_encode(array('success' => 0, 'message' => $errors)));
        }
    }

    public function lkn_simple_registration_validation($username, $password, $email): void
    {
        global $lknwp_reg_errors;
        $lknwp_reg_errors = new \WP_Error();

        if (empty($username) || empty($password) || empty($email)) {
            $lknwp_reg_errors->add('field', __('Required form field is missing', 'link-nacional-wp-crowdfunding-extension'));
        }

        if (strlen($username) < 4) {
            $lknwp_reg_errors->add('username_length', __('Username too short. At least 4 characters is required', 'link-nacional-wp-crowdfunding-extension'));
        }

        if (username_exists($username)) {
            $lknwp_reg_errors->add('user_name', __('Sorry, that username already exists!', 'link-nacional-wp-crowdfunding-extension'));
        }

        if (! validate_username($username)) {
            $lknwp_reg_errors->add('username_invalid', __('Sorry, the username you entered is not valid', 'link-nacional-wp-crowdfunding-extension'));
        }

        if (strlen($password) < 6) {
            $lknwp_reg_errors->add('password', __('Password length must be greater than 5', 'link-nacional-wp-crowdfunding-extension'));
        }

        if (! is_email($email)) {
            $lknwp_reg_errors->add('email_invalid', __('Email is not valid', 'link-nacional-wp-crowdfunding-extension'));
        }

        if (email_exists($email)) {
            $lknwp_reg_errors->add('email', __('Email Already in use', 'link-nacional-wp-crowdfunding-extension'));
        }
    }
}
?>