var currentStep = 1;
var recaptchaWidgetId;

function validaNumeroTelefono(numeroTelefono) {
    const regexTelefono = /^\d{6,}$/;
    return regexTelefono.test(numeroTelefono);
}

function validaEmail(email) {
    const regexEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return regexEmail.test(email);
}

function renderizzaRecaptcha() {
    const recaptchaContainer = document.getElementById('recaptcha-container');
    try { 
        recaptchaWidgetId = grecaptcha.render(recaptchaContainer, {
            sitekey: '6Ld5JjYpAAAAAEvtqBN-jGodlzF-PuPIlOZyHbHp'
        });
    } catch(err) {

    }
}

function verificaRecaptcha() {
    const recaptchaResponse = grecaptcha.getResponse(recaptchaWidgetId);
    if (recaptchaResponse === "") {
        jQuery('#error_process').html('Per favore, completa il reCAPTCHA prima di procedere.');
        jQuery('#error_process').show();
        return;
    } else {
        jQuery('#error_process').hide();
        jQuery('#recaptcha-container').hide();
        jQuery('#last_precedente_button').hide();
        jQuery('#invia_button').hide();
        submitForm();
    }
}

function nextStep() {

    jQuery('#error_process').hide();

    if(currentStep==1) {
        if(jQuery('#punti_vendita').val()==null) {
            jQuery('#error_process').html('Il punto vendita deve essere valorizzato');
            jQuery('#error_process').show();
            return;
        } else {
            const valoreSelezionato = jQuery('input[name="servizio"]:checked').val();
            if (valoreSelezionato !== undefined) {
                // OK
            } else {
                jQuery('#error_process').html('Devi selezionare almeno un servizio');
                jQuery('#error_process').show();
                return;
            }
        }

        const labelPv = jQuery("#punti_vendita").find("option:selected").text();
        let servizio = jQuery('input[name="servizio"]:checked').val();
        if(servizio==0) {
            servizio = 'Controllo della vista';
        } else if(servizio==1) {
            servizio = 'Prova delle lenti a contatto';
        }

        let breadHtml = '<b>Punto vendita:</b> '+labelPv+' - <b>Servizio:</b> '+servizio;
        jQuery("#bread_2").html(breadHtml);

        if(picker!=null) {
            let dataCorrente = new Date();
            let dayOfWeek = dataCorrente.getDay();
            if(dayOfWeek === 5) {
                dataCorrente.setDate(dataCorrente.getDate() + 3);
            } else if(dayOfWeek === 6) {
                dataCorrente.setDate(dataCorrente.getDate() + 2);
            } else {
                dataCorrente.setDate(dataCorrente.getDate() + 1);
            }
            
            picker.gotoDate(dataCorrente);
            picker.setDate(dataCorrente);
            get_slots(dataCorrente);
        }

        var targetElement = document.querySelector('.elementor-element-7daa5117');
        if (targetElement) {
            targetElement.scrollIntoView({ behavior: 'smooth' });
        }

    } else if(currentStep==2) {

        if(jQuery('#datepicker').val()==null || jQuery('#datepicker').val()=='') {
            jQuery('#error_process').html('Devi selezionare una data valida');
            jQuery('#error_process').show();
            return;
        } else {
            const valoreSelezionato = jQuery('input[name="form-field-aw_orario"]:checked').val();
            if (valoreSelezionato !== undefined) {
                // OK
            } else {
                jQuery('#error_process').html('Devi selezionare almeno un orario');
                jQuery('#error_process').show();
                return;
            }
        }

        const labelPv = jQuery("#punti_vendita").find("option:selected").text();
        let servizio = jQuery('input[name="servizio"]:checked').val();
        if(servizio==0) {
            servizio = 'Controllo della vista';
        } else if(servizio==1) {
            servizio = 'Prova delle lenti a contatto';
        }
        const date_selected = jQuery('#datepicker').val();
        const orario_selected = jQuery('input[name="form-field-aw_orario"]:checked').val();

        let breadHtml = '<b>Punto vendita:</b> '+labelPv+' - <b>Servizio:</b> '+servizio+' - <b>Giorno:</b> '+date_selected+' - <b>Orario:</b> '+orario_selected;
        jQuery("#bread_3").html(breadHtml);

        var targetElement = document.querySelector('.elementor-element-7daa5117');
        if (targetElement) {
            targetElement.scrollIntoView({ behavior: 'smooth' });
        }

    } else if(currentStep==3) {

        const privacyPolicyCheckbox = document.getElementById('privacy_policy');

        if(jQuery('#nome').val()==null || jQuery('#nome').val()=='') {
            jQuery('#error_process').html('Devi inserire un nome valido');
            jQuery('#error_process').show();
            return;
        } else if(jQuery('#cognome').val()==null || jQuery('#cognome').val()=='') {
            jQuery('#error_process').html('Devi inserire un cognome valido');
            jQuery('#error_process').show();
            return;
        } else if(jQuery('#email').val()==null || jQuery('#email').val()=='') {
            jQuery('#error_process').html('Devi inserire una e-mail valida');
            jQuery('#error_process').show();
            return;
        } else if(!validaEmail(jQuery('#email').val())) {
            jQuery('#error_process').html('Devi inserire una e-mail valida');
            jQuery('#error_process').show();
            return;
        } else if(jQuery('#telefono').val()==null || jQuery('#telefono').val()=='') {
            jQuery('#error_process').html('Devi inserire un telefono valido');
            jQuery('#error_process').show();
            return;
        } else if(!validaNumeroTelefono(jQuery('#telefono').val())) {
            jQuery('#error_process').html('Devi inserire un telefono valido (numerico di almeno 6 cifre)');
            jQuery('#error_process').show();
            return;
        } else if(!privacyPolicyCheckbox.checked) {
            jQuery('#error_process').html('Devi accettare termini e condizioni per proseguire');
            jQuery('#error_process').show();
            return;
        }

        const pv = jQuery("#punti_vendita").val();
        const labelPv = jQuery("#punti_vendita").find("option:selected").text();
        let servizio = jQuery('input[name="servizio"]:checked').val();
        if(servizio==0) {
            servizio = 'Controllo della vista';
        } else if(servizio==1) {
            servizio = 'Prova delle lenti a contatto';
        }
        const date_selected = jQuery('#datepicker').val();
        const orario_selected = jQuery('input[name="form-field-aw_orario"]:checked').val();
        const nome = jQuery('#nome').val();
        const cognome = jQuery('#cognome').val();
        const email = jQuery('#email').val();
        const telefono = jQuery('#telefono').val();
        const note = jQuery('#note').val();

        // RIEPILOGO PRENOTAZIONE NELLO STEP 4
        let htmlToShow = '';
        htmlToShow += '<b>Punto vendita:</b> '+labelPv+'<br>';
        htmlToShow += '<b>Servizio:</b> '+servizio+'<br>';
        htmlToShow += '<b>Giorno:</b> '+date_selected+'<br>';
        htmlToShow += '<b>Orario:</b> '+orario_selected+'<br>';
        htmlToShow += '<b>Nome:</b> '+nome+'<br>';
        htmlToShow += '<b>Cognome:</b> '+cognome+'<br>';
        htmlToShow += '<b>E-mail:</b> '+email+'<br>';
        htmlToShow += '<b>Telefono:</b> '+telefono+'<br>';
        htmlToShow += '<b>Note:</b> '+note+'<br>';
        jQuery("#conferma-dati-prenotazione").html(htmlToShow);

        var targetElement = document.querySelector('.elementor-element-7daa5117');
        if (targetElement) {
            targetElement.scrollIntoView({ behavior: 'smooth' });
        }

        renderizzaRecaptcha();
    }

    document.getElementById(`container-step-${currentStep}`).classList.add('nascosto');
    currentStep++;
    document.getElementById(`container-step-${currentStep}`).classList.remove('nascosto');
    document.getElementById(`pill-step-${currentStep}`).classList.add('active');
}

function ricominciaPagina() {
    var url = new URL(window.location.href);
    url.searchParams.set('openPopupApp', 'true');
    window.history.replaceState({}, '', url);
    location.reload();
}

function checkParameterInURL(key) {
    var urlParams = new URLSearchParams(window.location.search);
    return urlParams.has(key);
}
  
function simulateClickOnClass(className) {
    var linkToClick = document.querySelector('#menu-1-13780945 li.'+className+' a');
    linkToClick.click();
}

function submitForm() {

    console.log('Verifica slot libero...');

    const pv = jQuery("#punti_vendita").val();
    const date_selected = jQuery('#datepicker').val();
    var orario_selected = jQuery('input[name="form-field-aw_orario"]:checked').val();
    var partiData = date_selected.split('/');
    var datainlinea = `${partiData[2]}-${partiData[1]}-${partiData[0]}`;

    // TEST DEBUG
    // orario_selected = '09:30';

    jQuery.ajax({
        type: "POST",
        url: "/wp-admin/admin-ajax.php",
        data: {
            action: 'get_agenda_web',
            giorno: datainlinea,
            filiale: pv
        },
        success: function (output) {

            console.log(output);

            var prenotati = output.data.orari;
            if(prenotati.errore=='000') {
                var occupati = prenotati.contaSlotOccupati;
                var slotPren = [];
                if(parseInt(occupati)>0) {
                    jQuery.each(prenotati.slotOccupati, function(index,value){
                        slotPren.push(value.oraInizio);
                    });
                }
                if(slotPren.length > 0 && jQuery.inArray( orario_selected, slotPren ) !== -1) {
                    jQuery('#conferma-dati-prenotazione').html('<div style="opacity:1!important;"><h4 style="color:red;">Errore durante la prenotazione!</h4><p style="font-size:16px;">Spiacente, un utente ha appena prenotato la data e l\'ora selezionati, scegli una nuova data e/o un nuovo orario tra quelli attualmente disponibili, grazie.<br>Grazie per aver scelto Demenego</p></div>');
                    jQuery('#ricomincia_button').show();
                } else {
                    continueToSubmit();
                }
            } else {
                jQuery('#conferma-dati-prenotazione').html('<div style="opacity:1!important;"><h4 style="color:red;">Errore durante la prenotazione!</h4><p style="font-size:16px;">Spiacente, un utente ha appena prenotato la data e l\'ora selezionati, scegli una nuova data e/o un nuovo orario tra quelli attualmente disponibili, grazie.<br>Grazie per aver scelto Demenego</p></div>');
                jQuery('#ricomincia_button').show();
            }
        },
        error: function (output) {
            jQuery('#conferma-dati-prenotazione').html('<div style="opacity:1!important;"><h4 style="color:red;">Errore durante la prenotazione!</h4><p style="font-size:16px;">Spiacente, un utente ha appena prenotato la data e l\'ora selezionati, scegli una nuova data e/o un nuovo orario tra quelli attualmente disponibili, grazie.<br>Grazie per aver scelto Demenego</p></div>');
            jQuery('#ricomincia_button').show();
        }
    });
}

function continueToSubmit() {

    console.log('Invio form prenotazione...');
    
    const pv = jQuery("#punti_vendita").val();
    const date_selected = jQuery('#datepicker').val();
    const labelPv = jQuery("#punti_vendita").find("option:selected").text();
    const emailPv = jQuery("#punti_vendita option:selected").attr('data-cpv');
    let servizio = jQuery('input[name="servizio"]:checked').val();
    /*
    if(servizio==0) {
        servizio = 'Controllo della vista';
    } else if(servizio==1) {
        servizio = 'Prova delle lenti a contatto';
    }
    */
    const orario_selected = jQuery('input[name="form-field-aw_orario"]:checked').val();
    const nome = jQuery('#nome').val();
    const cognome = jQuery('#cognome').val();
    const email = jQuery('#email').val();
    const telefono = jQuery('#telefono').val();
    const note = jQuery('#note').val();
    var partiData = date_selected.split('/');
    var datainlinea = `${partiData[2]}-${partiData[1]}-${partiData[0]}`;

    if (orario_selected.length === 8 && orario_selected[2] === ':' && orario_selected[5] === ':') {
        // Rimuovi la parte finale (":SS")
        orario_selected = orario_selected.substring(0, 5);
    }

    var formData = {
        'action': 'get_set_agenda',
        'aw_punto_vendita': pv,
        'datainlinea': datainlinea,
        'aw_ora': orario_selected,
        'aw_durata': 30,
        'aw_servizio': servizio,
        'aw_nome': nome,
        'aw_cognome': cognome,
        'aw_note': note,
        'aw_telefono': telefono,
        'aw_email': email,
        'aw_npv': labelPv,
        'aw_epv': emailPv
    };

    jQuery.ajax({
        type: 'POST',
        url: "/wp-admin/admin-ajax.php",
        data: formData,
        success: function(response) {
            console.log('Richiesta riuscita:', response);
            if(response.status=='success') {
                jQuery('#conferma-dati-prenotazione').html('<div style="opacity:1!important;"><h4 style="color:green;">Prenotazione inviata con successo!</h4><p style="font-size:16px;">Riceverai a breve un\'email con il riepilogo della tua prenotazione.<br>Grazie per aver scelto Demenego</p></div>');
            } else {
                jQuery('#conferma-dati-prenotazione').html('<div style="opacity:1!important;"><h4 style="color:red;">Errore durante la prenotazione!</h4></div>');
            }            
        },
        error: function(error) {
            console.error('Errore nella richiesta:', error);
            jQuery('#conferma-dati-prenotazione').html('<div><p style="font-size:16px;">Attenzione! Si è verificato un errore durante la richiesta</p></div>');
        },
        beforeSend: function() {
            console.log('Invio della richiesta...');
            jQuery('#conferma-dati-prenotazione').html('<div><p style="font-size:16px;">Invio la prenotazione, attendere...</p></div>');
        }
    });
}

function prevStep() {
    document.getElementById(`container-step-${currentStep}`).classList.add('nascosto');
    document.getElementById(`pill-step-${currentStep}`).classList.remove('active');
    currentStep--;
    document.getElementById(`container-step-${currentStep}`).classList.remove('nascosto');

    var targetElement = document.querySelector('.elementor-element-7daa5117');
    if (targetElement) {
        targetElement.scrollIntoView({ behavior: 'smooth' });
    }
}

function get_pv() {

    /*
    var pagina_pv = '';
    var currentLocation = location.pathname;
    var sel_punto_vendita = currentLocation.slice(0,-1).split("/");
    if(location.pathname.indexOf('punti-vendita')>0) {
        pagina_pv = sel_punto_vendita.pop();
        var soloprimaparte = pagina_pv.split('-');
        if(soloprimaparte.length>1) pagina_pv = soloprimaparte[0];
        console.log(pagina_pv);
    }
    */

    var pagina_pv = '';
    var currentUrl = window.location.href;
    var url = new URL(currentUrl);
    var searchParams = new URLSearchParams(url.search);
    var pvValue = searchParams.get('pv');
    if (pvValue !== null) {
        pvValue = pvValue.split("-")[0];
        pagina_pv = pvValue;
    }

    jQuery('#punti_vendita option:not(:first)').remove();
    jQuery.ajax({
        type: "POST",
        url: "/wp-admin/admin-ajax.php",
        data: {
            action: 'get_agenda_web_pv',
        },
        success: function (output) {
            let risposta = output.data.pv;
            codpv = '';
            jQuery.each(risposta, function(key,value){
                slug_nome = value.nome.toLowerCase().replace(" ","-");
                codfiliale = value.cod;
                nomefiliale = value.nome;
                emailfiliale = value.email.replace('@demenego.it','').replace('@demengo.it','');    
                // console.log('DATI RICEVUTI: '+'CODICE FILIALE: '+codfiliale+" NOME FILIALE: "+nomefiliale+" EMAIL FILIALE: "+emailfiliale);
                if(nomefiliale.indexOf('San Don')!=-1) nomefiliale = 'San Donà di Piave';
                if(pagina_pv!=''&&emailfiliale.replace('ottica.','') == pagina_pv) {
                    codpv = value.cod;
                }
                jQuery('#punti_vendita').append('<option value="'+codfiliale+'" data-cpv="'+emailfiliale+'">'+nomefiliale+'</option>');
            });
            if(pagina_pv!=""&&codpv!="") {
                jQuery('#punti_vendita').val(codpv);
            }
        },
        error: function (output) {
            var risposta = output.data.pv;
            console.log("ERRORE durante la chiamata...");
        }
    });
}

var picker = null;

function get_slots(date) {

    let anno = date.getFullYear();
    let mese = (date.getMonth() + 1).toString().padStart(2, '0');
    let giorno = date.getDate().toString().padStart(2, '0');
    let dataFormat = `${anno}-${mese}-${giorno}`;

    if(dataFormat!='') {
        jQuery("#orario").css({'font-size':'15px','color':'#569ff7'}).html('<i class="fas fa-cog fa-spin"></i> Cerco orari disponibili...');
        
        jQuery.ajax({
            type: "POST",
            url: "/wp-admin/admin-ajax.php",
            data: {
                action: 'get_agenda_web',
                giorno: dataFormat,
                filiale: jQuery('#punti_vendita').val()
            },
            success: function (output) {
                let slotPrenotati = [];
                let radioHtmlAmPm = '';
                let risposta = output.data.orari;
                let minutiDurata = 30;
                if(risposta.errore == '000') {
                    // console.log("Slot occupati: "+JSON.stringify(risposta.slotOccupati));
                    
                    let radioHtmlAmPm = '';
                    jQuery.each(risposta.slotOccupati, function(index,value){
                        let orain, orafi;
                        if(value.oraInizio.length>5) orain = value.oraInizio.substring(0, value.oraInizio.length - 3);
                            else orain = value.oraInizio;
                        if(value.oraFine.length>5) orafi = value.oraFine.substring(0, value.oraFine.length - 3);
                            else orafi = value.oraFine;
                        slotPrenotati.push(orain);
                    });
                    jQuery.each(risposta.slotLiberi, function(index,value){

                        // PULISCO E UNIFORMO GLI ORARI
                        if(value.oraInizio.length>5) orain = value.oraInizio.substring(0, value.oraInizio.length - 3);
                            else orain = value.oraInizio;
                        if(value.oraFine.length>5) orafi = value.oraFine.substring(0, value.oraFine.length - 3);
                            else orafi = value.oraFine;

                        let datauser = new Date();
                        let addminutein;
                        let dataorain;
                        let addminutefi;
                        let dataorafi;

                        if(value.minutiDurata==30 && jQuery.inArray(orain, slotPrenotati) === -1) {
                            
                            radioHtmlAmPm += '<span class="elementor-field-option aw_orario_result" style="margin-top: 5px;"><input type="radio" value="'+orain+'" id="form-field-aw_orario-'+index+'" name="form-field-aw_orario" required="required" aria-required="true" data-durata="'+minutiDurata+'" data-orain="'+orain+'" data-orafi="'+orafi+'"><label for="form-field-aw_orario-'+index+'">'+orain+'</label></span>';

                        } else {

                            majorof30 = value.minutiDurata/30;
                            slotindiviso = value.oraInizio.split(':');
                            slotfidiviso = value.oraFine.split(':');

                            for(i=1;i<=majorof30;i++) {
                                
                                if(i>1) {
                                    addminutein = datauser.setHours(slotindiviso[0],slotindiviso[1],0) + 30 * 60 * 1000;
                                    dataorain = new Date(addminutein).toLocaleTimeString('it-IT', { hour: '2-digit', minute: '2-digit' });
                                    addminutefi = datauser.setHours(slotindiviso[0],slotindiviso[1],0) + 60 * 60 * 1000;
                                    dataorafi = new Date(addminutefi).toLocaleTimeString('it-IT', { hour: '2-digit', minute: '2-digit' });
                                } else {
                                    addminutein = datauser.setHours(slotindiviso[0],slotindiviso[1],0) + 0 * 60 * 1000;
                                    dataorain = new Date(addminutein).toLocaleTimeString('it-IT', { hour: '2-digit', minute: '2-digit' });
                                    addminutefi = datauser.setHours(slotindiviso[0],slotindiviso[1],0) + 30 * 60 * 1000;
                                    dataorafi = new Date(addminutefi).toLocaleTimeString('it-IT', { hour: '2-digit', minute: '2-digit' });
                                }

                                if(dataorain.length>5) orain = dataorain.substring(0, dataorain.length - 3);
                                    else orain = dataorain;
                                if(dataorafi.length>5) orafi = dataorafi.substring(0, dataorafi.length - 3);
                                    else orafi = dataorafi;

                                if(jQuery.inArray(orain, slotPrenotati) === -1) {
                                    radioHtmlAmPm += '<span class="elementor-field-option aw_orario_result" style="margin-top: 5px;"><input type="radio" value="'+orain+'" id="form-field-aw_orario-'+index+i+'" name="form-field-aw_orario" required="required" aria-required="true" data-durata="'+minutiDurata+'" data-orain="'+orain+'" data-orafi="'+orafi+'"><label for="form-field-aw_orario-'+index+i+'">'+orain+'</label></span>';
                                }

                                slotindiviso = dataorain.split(':');
                                slotfidiviso = dataorafi.split(':');
                            }
                        }
                    });
                    jQuery("#orario").html('<div style="">'+radioHtmlAmPm+'</div>');
                } else if(risposta.errore=='914') {
                    jQuery("#orario").html('<div style="">In questo giorno non è possibile prendere appuntamento in questa sede.</div>');
                } else if(risposta.errore) {
                    jQuery("#orario").html('<div style="">Ci scusiamo per il disagio. Al momento non è possibile effettuare la prenotazione, riprova tra qualche minuto.</div>');
                }
            },
            error: function (output) {
                jQuery("#orario").html('Errore del server, riprovare più tardi.');
                console.log(output);
            }
        });
    } else {
        jQuery("#orario").html('<div class="wrapper-orari">Selezionare una data per visualizzare gli orari.</div>');
    }
}

var appuntamenti_opened = false;

jQuery( document ).ready(function() {
    // console.log( "ready!" );
    
    if(!appuntamenti_opened) {
        setTimeout(function() {
            if (checkParameterInURL('openPopupApp')) {
                simulateClickOnClass('menu-item-968344');
                appuntamenti_opened = true;
            }
        }, 1000);
    }
    
    get_pv();

    let dataCorrente = new Date();
    dataCorrente.setDate(dataCorrente.getDate() + 1);

    if(document.getElementById('datepicker')!=null && !document.querySelector('.easepick-wrapper')) {
        picker = new easepick.create({
            element: document.getElementById('datepicker'),
            css: [
                'https://cdn.jsdelivr.net/npm/@easepick/core@1.2.1/dist/index.css',
                'https://cdn.jsdelivr.net/npm/@easepick/lock-plugin@1.2.1/dist/index.css',
            ],
            lang: 'it-IT',
            inline: true,
            format: 'DD/MM/YYYY',
            plugins: ['LockPlugin'],
            LockPlugin: {
                minDate: dataCorrente,
                filter(date, picked) {
                    return [0, 6].includes(date.getDay());
                }
            },
            setup(picker) {
                picker.on('select', (e) => {
                    const { view, date, target } = e.detail;
                    // console.log('change... '+date);
    
                    if (date <= new Date()) {
                        jQuery("#orario").css({'font-size':'15px','color':'#569ff7'});
                        jQuery("#orario").html('<div style="">Puoi cercare solamente da domani in poi.</div>');
                        return;
                    }
        
                    get_slots(date);
                });
            }
        });
    }
});