window.onload = function () {
    var extraFields = document.getElementById('extra-fields');
    var formAction = document.getElementById('form-action');
    var toggleText = document.getElementById('toggle-form');
    var loadingOverlay = document.getElementById('loading-overlay');
    if (extraFields) {
        extraFields.style.display = 'block';
    }
    if (formAction) {
        formAction.innerText = 'Cadastrar';
    }
    if (toggleText) {
        toggleText.innerHTML = '<span style="color: #069;">Já tem cadastro?</span> <a href="#" onclick="toggleForm();return false;">Faça login</a>';
    }
}
function toggleForm() {
    var extraFields = document.getElementById('extra-fields');
    var formAction = document.getElementById('form-action');
    var toggleText = document.getElementById('toggle-form');
    if (extraFields.style.display === 'none') {
        extraFields.style.display = 'block';
        formAction.innerText = 'Cadastrar';
        toggleText.innerHTML = '<span style="color: #069;">Já tem cadastro?</span> <a href="#" onclick="toggleForm()">Faça login</a>';
    } else {
        extraFields.style.display = 'none';
        formAction.innerText = 'Autenticar';
        toggleText.innerHTML = 'Não tem uma conta? <a href="#" onclick="toggleForm();return false;">Cadastre-se</a>';
    }
}
function alternaForm(tipo) {
    var extraFields = document.getElementById('extra-fields');
    var formAction = document.getElementById('form-action');
    var toggleText = document.getElementById('toggle-form');
    if (tipo === 'login') {
        extraFields.style.display = 'none';
        formAction.innerText = 'Autenticar';
        toggleText.innerHTML = 'Não tem uma conta? <a href="#" onclick="toggleForm();return false;">Cadastre-se</a>';
    } else {
        extraFields.style.display = 'block';
        formAction.innerText = 'Cadastrar';
        toggleText.innerHTML = '<span style="color: #069;">Já tem cadastro?</span> <a href="#" onclick="toggleForm()">Faça login</a>';
    }
}
function togglePasswordVisibility() {
    const passwordField = document.getElementById("form-login__password");
    const toggleButton = document.getElementById("togglePassword");
    if (passwordField.type === "password") {
        passwordField.type = "text";
        toggleButton.innerHTML = '<i class="fa fa-eye-slash"></i>';
    } else {
        passwordField.type = "password";
        toggleButton.innerHTML = '<i class="fa fa-eye"></i>';
    }
}
function mascara_checkout(i, t) {
    let v = i.value.replace(/\D/g, ''); // Remove tudo que não for dígito
    if (t === "cpf") {
        i.setAttribute("maxlength", "14");
        if (v.length > 3 && v.length <= 6) {
            v = v.replace(/(\d{3})(\d+)/, "$1.$2");
        } else if (v.length > 6 && v.length <= 9) {
            v = v.replace(/(\d{3})(\d{3})(\d+)/, "$1.$2.$3");
        } else if (v.length > 9) {
            v = v.replace(/(\d{3})(\d{3})(\d{3})(\d+)/, "$1.$2.$3-$4");
        }
        i.value = v;
    }
    if (t === "data") {
        i.setAttribute("maxlength", "10");
        if (v.length >= 2 && v.length < 4) {
            v = v.replace(/(\d{2})(\d+)/, "$1/$2");
        } else if (v.length >= 4) {
            v = v.replace(/(\d{2})(\d{2})(\d+)/, "$1/$2/$3");
        }
        i.value = v;
    }
    if (t === "cel") {
        if (v.length > 0) {
            v = v.replace(/(\d{1})(\d{4})(\d{4})(\d*)/, "($1$2) $3-$4");
        }
        i.value = v.substring(0, 15); // Limita a string para o tamanho máximo
    }
}
// Inicialmente mostrar o formulário de cadastro
var loginForm = document.getElementById('form-login');
if (loginForm) {
    loginForm.addEventListener('submit', function (event) {
        event.preventDefault();
        // Obter valores dos campos
        var loadingOverlay = document.getElementById('loading-overlay');
        var button = document.getElementById('btn-autenticar');
        button.disabled = true;
        loadingOverlay.style.display = 'flex';
        var email = document.getElementById('form-login__email').value;
        var password = document.getElementById('form-login__password').value;
        // Se extraFields estiver visível, é cadastro
        var isRegistering = document.getElementById('extra-fields').style.display !== 'none';
        if (isRegistering) {
            // Código para realizar o cadastro do usuário no WordPress
            var firstName = document.getElementById('form-login__payerFirstName').value;
            var cpf = null;
            var identificationNumberElement = document.getElementById('form-login__identificationNumber');
            if (identificationNumberElement && identificationNumberElement.value) {
                cpf = identificationNumberElement.value;
            }
            // Função Ajax para realizar o cadastro
            wp_ajax_register_user(email, password, firstName, cpf);
        } else {
            // Código para realizar o login do usuário no WordPress
            wp_ajax_login_user(email, password);
            button.disabled = false;
        }
        loadingOverlay.style.display = 'none';
    });
}
function wp_ajax_register_user(email, password, firstName) {
    var button = document.getElementById('btn-autenticar');
    // Chamada Ajax para registrar o usuário no WordPress
    var loadingOverlay = document.getElementById('loading-overlay');
    jQuery.ajax({
        url: wpPlanosAjax.ajaxurl, // ajaxurl é a URL padrão do WordPress para chamadas AJAX
        type: 'POST',
        dataType: 'json',
        data: {
            action: 'custom_register_user',
            email: email,
            password: password,
            firstName: firstName
        },
        success: function (response) {
            if (response.success) {
                document.querySelector('.payment_method').style.display = '';
                document.querySelector('.efetuar-login').style.display = 'none';
                document.querySelector('.divEmail').style.display = 'none';
                document.querySelector('.divName').style.display = 'none';
                document.querySelector('.inputEmail').readonly = true;
                document.querySelector('.inputName').readonly = true;
                document.querySelector('.payment_method').style.display = '';
                document.getElementById('wpGatewaysLabel').innerHTML = '<span style="color: black;">Escolha um método de pagamento</span>';
                document.querySelector('.inputEmail').value = response.data.email;
                document.querySelector('.inputName').value = response.data.nome;
                jQuery('.inputEmail').attr('readonly', true);
                jQuery('.inputName').attr('readonly', true);
                jQuery('.inputEmail').val(response.data.email);
                jQuery('.inputName').val(response.data.nome);
                localStorage.setItem('nome', response.data.nome);
                localStorage.setItem('email', response.data.email);
                sessionStorage.setItem('nome', response.data.nome);
                sessionStorage.setItem('email', response.data.email);
            } else {
                alert(response.data.message);
                jQuery('.payment_method').hide();
                jQuery('.efetuar-login').show();
                //if (response.data.sts === 'existe') {
                alternaForm('register');
                //} else {
                //alternaForm('login');
                //}
            }
            button.disabled = false;
            loadingOverlay.style.display = 'none';
        },
        error: function (xhr, status, error) {
            console.error("Erro AJAX:", status, error);
            alert('Erro ao processar o registro. Tente novamente.');
        },
        complete: function () {
            // Habilitar o botão e esconder o overlay
            button.disabled = false;
            loadingOverlay.style.display = 'none';
        }
    });
}
function wp_ajax_login_user(email, password) {
    var button = document.getElementById('btn-autenticar');
    // Chamada Ajax para logar o usuário no WordPress
    var loadingOverlay = document.getElementById('loading-overlay');
    jQuery.ajax({
        url: wpPlanosAjax.ajaxurl, // ajaxurl é a URL padrão do WordPress para chamadas AJAX
        type: 'POST',
        dataType: 'json',
        data: {
            action: 'custom_login_user',
            email: email,
            password: password,
        },
        success: function (response) {
            if (response.success) {
                jQuery('.payment_method').attr('style', 'display: flex');
                jQuery('.efetuar-login').attr('style', 'display: none');
                jQuery('.divName').attr('style', 'display: none');
                jQuery('.divEmail').attr('style', 'display: none');
                jQuery('#form-checkout__email').val(response.data.email);
                jQuery('#form-checkout__payerFirstName').val(response.data.nome);
            } else {
                jQuery('.alerta').html('<div class="alert alert-danger">' + response.data.message + ' <a href="#" onclick="toggleForm();return false;">Cadastre-se</a></div>');
            }
            loadingOverlay.style.display = 'none';
            button.disabled = false;
        },
        error: function (xhr, status, error) {
            //console.log("Erro AJAX:", status, error);
            alert('Erro ao processar o login. Tente novamente.');
            loadingOverlay.style.display = 'none';
        }
    });
}
function clearForm() {
    // Limpando a função setInterval, caso exista
    var localStorage_intervaloID = sessionStorage.getItem('intervaloID');
    if (localStorage_intervaloID) {
        clearInterval(localStorage_intervaloID);
    }
    jQuery('#wp-planos-pix-btn-submit').show();
    var inputEmail = jQuery('#form-checkout__email');
    var inputName = jQuery('#form-checkout__payerFirstName');
    var email = inputEmail.val();
    var payerFirstName = inputName.val();
    // Limpa os campos de entrada (input) e textarea
    jQuery('input[type="text"], input[type="password"], input[type="email"], textarea').val('');
    // Limpa os campos select
    jQuery('select').prop('selectedIndex', 0); // Reseta o índice para o primeiro item
    // Desmarca todos os checkboxes
    jQuery('input[type="checkbox"]').prop('checked', false);
    // Desmarca todos os radio buttons
    jQuery('input[type="radio"]').prop('checked', false);
    jQuery('#status-pagamento').hide();
    jQuery('#status-pagamento').empty();
    jQuery('#wp-planos-pix-result').hide();
    jQuery('#wp-planos-pix-result').empty();
    jQuery('.botao').removeClass('active-button');
    inputEmail.val(email);
    inputName.val(payerFirstName);
    inputEmail.attr('readonly', true);
    inputName.attr('readonly', true);
}
function login(ID, title, value, tempo, periodos, value_dolar,product_id) {
    localStorage.setItem('objeto', JSON.stringify({ID, title, value, tempo, periodos, value_dolar,product_id}));
    alternaForm('logino');
    jQuery("#wpGateways").modal('show');
}
function recuperar(ID, title, value, tempo, periodos, value_dolar,product_id) {
    // Armazenar informações no localStorage
    //clearForm();
    try {
        localStorage.setItem('objeto', JSON.stringify({ID, title, value, tempo, periodos, value_dolar,product_id}));
        jQuery('.plano_titulo').text(title);
        jQuery('.plano_titulo').val(title);
        jQuery('.plano_valor').text(formatCurrency(value));
        jQuery('.plano_valor').val((value));
        jQuery('.plano_id').val(ID);
        jQuery('.product_id').val(product_id);
        jQuery('.periodo').val(periodos);
        // Manipulação do DOM após confirmação do armazenamento
        jQuery("#wpGateways").modal('show');
        jQuery('#wpFormCheckout').modal('hide');
        jQuery('#form-checkout').hide();

    } catch (error) {
        console.error("Erro ao acessar o localStorage: ", error);
    }
}
// Função para formatar valor como moeda no formato pt-BR
function formatCurrency(value) {
    return new Intl.NumberFormat('pt-BR', {
        style: 'currency',
        currency: 'BRL'
    }).format(value);
}

function atualizarStatusPagamento(paymentId, clear) {
    const intervalo = 5000; // Intervalo de tempo para checar o status em milissegundos (5 segundos)
    function checarStatus() {
        const data = new FormData();
        data.append('action', 'consultar_status_pagamento_pix');
        data.append('payment_id', paymentId);
        data.append('method', 'PIX');
        fetch(wpPlanosAjax.ajaxurl, {
            method: 'POST',
            body: data
        })
                .then(response => response.json())
                .then(result => {
                    const statusElement = document.getElementById('status-pagamento');
                    statusElement.style.display = 'block';
                    jQuery('#status-pagamento').show();
                    if (result.status === 'approved') {
                        jQuery('#status-pagamento').attr('style', 'color: green;');
                        jQuery('#status-pagamento').html('Pagamento aprovado.');
                        clearInterval(intervaloID); // Parar a verificação
                        if (result.url === 'null') {
                            window.location.reload();
                        } else {
                            window.location.href = result.url;
                        }
                    } else if (result.status === 'pending') {
                        jQuery('#status-pagamento').attr('style', 'color: orange;');
                        jQuery('#status-pagamento').html('Pagamento pendente.');
                    } else if (result.status === 'rejected') {
                        jQuery('#status-pagamento').attr('style', 'color: red;');
                        jQuery('#status-pagamento').html('Pagamento rejeitado.');
                        clearInterval(intervaloID); // Parar a verificação
                        if (result.url === 'null') {
                            window.location.reload();
                        } else {
                            window.location.href = result.url;
                        }
                    } else {
                        jQuery('#status-pagamento').attr('style', 'color: red;');
                        jQuery('#status-pagamento').html('Erro ao verificar o pagamento.');
                        clearInterval(intervaloID); // Parar a verificação
                        if (result.url === 'null') {
                            window.location.reload();
                        } else {
                            window.location.href = result.url;
                        }
                    }
                })
                .catch(error => {
                    console.error('Erro na consulta do pagamento:', error);
                });
    }
    // Iniciar a verificação periódica
    const intervaloID = setInterval(checarStatus, intervalo);
    sessionStorage.setItem('intervaloID', intervaloID);
}

function escolher_metodo(metodo, link, display, emailInput, nameInput, readonly, cpf, img) {
    // Prevenir o evento de propagação
    if (event) {
        event.stopPropagation();
    }


    mostrarOverlay(true);
    carregarInformacoesPlano();

    configurarFormulario(metodo);

    var url = construirUrl(link, display, emailInput, nameInput, readonly, cpf, img);

    carregarFormularioDinamico(metodo, url);

    mostrarOverlay(false);
    clearForm();
}

function mostrarOverlay(exibir) {
    var loadingOverlay = jQuery('#loading-overlay');
    loadingOverlay.css('display', exibir ? 'flex' : 'none');
}

function carregarInformacoesPlano() {
    const objeto = JSON.parse(localStorage.getItem('objeto'));

    if (!objeto)
        return;

    jQuery('.product_id').text(objeto.product_id);
    jQuery('.plano_titulo').text(objeto.title);
    jQuery('.plano_valor').text(formatCurrency(objeto.value));
    jQuery('.valor_dolar').text(formatCurrency(objeto.value_dolar));
    jQuery('.plano_periodicidade').text(objeto.tempo);

    jQuery('#form-checkout__email').val(objeto.emailInput);
    jQuery('#form-checkout__payerFirstName').val(objeto.nameInput);
}

function configurarFormulario(metodo) {
    jQuery('.botao').removeClass('active-button');
    jQuery('.payment-form').hide();
    jQuery('.payment_method').css('display', 'flex');
    jQuery('.efetuar-login, .divName, .divEmail').hide();

    jQuery('#form-checkout-pix').remove();
    jQuery('#form-checkout-cartao').remove();
    jQuery('#form-checkout-mp_ambiente').remove();

    switch (metodo) {
        case 'cartao':
            jQuery('#form-checkout-pix').remove();
            jQuery('#form-checkout-mp_ambiente').remove();

            prepararPagamento('cartao', 'btn-card', ['pix', 'mp_ambiente', 'coinpayments']);
            break;
        case 'pix':
            jQuery('#form-checkout-cartao').remove();
            jQuery('#form-checkout-mp_ambiente').remove();

            prepararPagamento('pix', 'btn-mp-pix', ['cartao', 'mp_ambiente', 'coinpayments']);
            mostrarBotaoPix();
            break;
        case 'mp_ambiente':
            jQuery('#form-checkout-pix').remove();
            jQuery('#form-checkout-cartao').remove();

            prepararPagamento('mp_ambiente', 'btn-mp-ambiente', ['pix', 'cartao', 'coinpayments']);
        case 'coinpayments':
            break;
        default:
            console.error("Método de pagamento não suportado");
    }
}

function prepararPagamento(metodo, botaoClasse, formulariosParaEsconder) {
    jQuery(`.${botaoClasse}`).addClass('active-button');
    jQuery("#wpGateways").modal('hide');
    jQuery('#wpFormCheckout').modal('show');
    jQuery(`#${metodo}-form`).show();
    formulariosParaEsconder.forEach(form => jQuery(`#${form}-form`).hide());
}

function mostrarBotaoPix() {
    var button = document.getElementById('wp-planos-pix-btn-submit');
    if (button) {
        button.style.display = '';
    }
}

function construirUrl(link, display, emailInput, nameInput, readonly, cpf, img) {
    const objeto = JSON.parse(localStorage.getItem('objeto'));
    if (!objeto)
        return '';


    var product_id = objeto.product_id;
    var id = objeto.ID;
    var titulo = objeto.title;
    var valor = objeto.value;
    var periodicidade = objeto.tempo;
    var periodo = objeto.periodos;
    var valor_dolar = objeto.value_dolar;
    var rec = "recuperar('" + id + "', '" + titulo + "', '" + valor + "', '" + periodicidade + "','" + periodo + "','" + valor_dolar + "','" + product_id + "')";
    jQuery('#other').html('<button type="button" class="btn btn-default btn-sm" onclick="' + rec + '">Escolher outro método de pagamento</button>');

    return link + '?' + jQuery.param({
        display,
        emailInput,
        nameInput,
        readonly,
        cpf,
        img,
        id: objeto.ID,
        titulo: objeto.title,
        valor: objeto.value,
        valor_dolar: objeto.value_dolar,
        periodicidade: objeto.tempo,
        periodo: objeto.periodos,
        product_id: objeto.product_id
    });
}

function carregarFormularioDinamico(metodo, url) {
    jQuery(`#${metodo}-form`).load(url, function (response, status, xhr) {
        if (status === "error") {
            console.error("Erro ao carregar o formulário: " + xhr.status + " " + xhr.statusText);
        }
    });
}


jQuery(document).ready(function ($) {
    $(document).on('click', '.close', function () {
        clearForm();
    });

    $(document).on('click', '#wp-planos-pix-btn-submit', function (e) {
        e.preventDefault();
        var formPIX = document.getElementById('form-checkout-pix');
        var loadingOverlay = $('#loading-overlay');
        var button = $('#wp-planos-pix-btn-submit');
        loadingOverlay.attr('style', 'display: flex');
        button.attr('style', 'display: none');
        var formData = new FormData(formPIX);
        formData.append('action', 'process_payment');

        // Envia a requisição AJAX
        fetch(wpPlanosAjax.ajaxurl, {
            method: 'POST',
            body: formData
        })
                .then(response => response.json())
                .then(data => {
                    jQuery('#wp-planos-pix-result').show();
                    jQuery('.pix_qr_code').show();
                    jQuery('#pix-code').val(data.data.qr_code_url);
                    jQuery('#wp-planos-pix-result').attr('style', 'display: block; overflow-x: hidden; height: 180px;');
                    if (data.success) {
                        var resultHtml = `
                <div class="row" style="text-align: center;">
                    <div class="col-md-12">
                        <img src="data:image/jpeg;base64,${data.data.qr_code_base64}" alt="QR Code" style="width: 180px;"/>
                    </div>
                </div>
                <div class="row">
                    
                </div>`;

                        jQuery('#wp-planos-pix-result').html(resultHtml);
                        atualizarStatusPagamento(data.data.payment_id);
                    } else {
                        jQuery('#wp-planos-pix-result').html('<p>' + data.data + '</p>');
                    }
                })
                .catch(error => console.error('Erro:', error))
                .finally(() => {
                    loadingOverlay.attr('style', 'display: none');
                });
    });

    $(document).on('click', '#wp-planos-cartao-btn-submit', function (e) {
        e.preventDefault();
        var formCartao = document.getElementById('form-checkout-cartao');
        var loadingOverlay = $('#loading-overlay');//document.getElementById('loading-overlay');
        var button = $('#wp-planos-cartao-btn-submit');//document.getElementById('wp-planos-pix-result');
        loadingOverlay.attr('style', 'display: flex');
        button.attr('style', 'display: none');
        var formData = new FormData(formCartao);
        // Adiciona um nonce para segurança
        formData.append('action', 'process_payment');
        //formData.append('security', wpPlanosAjax.ajaxNonce);
        // Envia a requisição AJAX
        fetch(wpPlanosAjax.ajaxurl, {
            method: 'POST',
            body: formData
        })
                .then(response => response.json())
                .then(data => {
                    //jQuery('#wp-planos-cartao-result').show();
                    //jQuery('#wp-planos-cartao-result').attr('style', 'display: block;overflow-x: hidden;height:180px;');

                    if (data.success) {
                        window.location.href = data.data.url;
                    } else {
                        // Mensagem de erro
                        jQuery('#wp-planos-cartao-result').html('<p>' + data.data + '</p>');
                    }
                })
                .catch(error => console.error('Erro:', error))
                .finally(() => {
                    // Oculta o overlay de carregamento
                    loadingOverlay.attr('style', 'display: none');
                });
    });

    $(document).on('click', '#wp-planos-mp_ambiente-btn-submit', function (e) {
        e.preventDefault();
        var formMPA = document.getElementById('form-checkout-mp_ambiente');
        var loadingOverlay = $('#loading-overlay');//document.getElementById('loading-overlay');
        var button = $('#wp-planos-mp_ambiente-btn-submit');//document.getElementById('wp-planos-pix-result');
        loadingOverlay.attr('style', 'display: flex');
        button.attr('style', 'display: none');
        var formData = new FormData(formMPA);
        // Adiciona um nonce para segurança
        formData.append('action', 'process_payment');
        //formData.append('security', wpPlanosAjax.ajaxNonce);
        // Envia a requisição AJAX
        fetch(wpPlanosAjax.ajaxurl, {
            method: 'POST',
            body: formData
        })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        window.location.href = data.data.payment_link;
                    } else {
                        // Mensagem de erro
                        jQuery('#wp-planos-mp_ambiente-result').html('<p>' + data.data + '</p>');
                    }
                })
                .catch(error => console.error('Erro:', error))
                .finally(() => {
                    // Oculta o overlay de carregamento
                    loadingOverlay.attr('style', 'display: none');
                });
    });

    $(document).on('click', '#copy-pix-code', function () {
        var pixCode = $('#pix-code');

        // Verificar se o textarea com o ID pix-code existe e se contém o valor correto
        if (pixCode.length && pixCode.val() !== "") {
            // Torna o textarea temporariamente visível para permitir a cópia
            pixCode.css({position: 'absolute', left: '0px', visibility: 'hidden'});

            // Seleciona o conteúdo do textarea
            pixCode.select();
            pixCode[0].setSelectionRange(0, 99999); // Para compatibilidade com mobile

            // Executa o comando de cópia
            document.execCommand('copy');

            // Restaura o estado do textarea
            pixCode.css({visibility: 'hidden'});

            // Mostra alerta de sucesso
            $('.pay-go-pro-alert')
                    .addClass('alert alert-success')
                    .html('Código PIX copiado!')
                    .show();

            // Oculta o alerta após 5 segundos
            setTimeout(function () {
                $('.pay-go-pro-alert').fadeOut('slow', function () {
                    $(this).remove();
                });
            }, 5000);
        } else {
            // Se o textarea não existe ou está vazio
            console.error("O elemento #pix-code não foi encontrado ou está vazio.");
            alert("Código PIX não encontrado ou não gerado corretamente.");
        }
    });

});




