function populateCountrySelect() {
    const select = document.getElementById('country-select');

    countries.forEach(country => {
        const option = document.createElement('option');
        option.value = country.code;
        option.dataset.phoncode = country.phonecode;
        option.textContent = country.name;
        select.appendChild(option);
    });
}

// Call the function on page load
window.onload = populateCountrySelect;
const selectBox = document.getElementById('country-select');
selectBox.onchange = function () {
    let selectedI = this.selectedIndex;
    const selectedValue = this.options[selectedI].dataset.phoncode
    // console.log('You selected: ' + selectedValue);
    document.getElementById("tel-1").value = '+' + selectedValue;

    // document.getElementById('output').textContent = 'Selected country: ' + selectedValue;
};

const inputBox = document.getElementById('tel-1');

// Add an event listener for the input event
inputBox.addEventListener('input', function (event) {
    // Only allow numbers and the plus sign
    const selectBox = document.getElementById('country-select');
    const validChars = /^[\d+]+$/;
    if (!validChars.test(event.target.value)) {
        // Remove invalid characters
        event.target.value = event.target.value.replace(/[^0-9+]/g, '');
    }
    try {
        const phoneNumber = libphonenumber.parsePhoneNumber(event.target.value, selectBox.value)
        event.target.value = phoneNumber.formatInternational();
        //console.log(selectBox.value);
    } catch (error) {

    }

});
function xhrrequest(){
    let data = null;
    const xhr = new XMLHttpRequest();

}
(function () {
    'use strict';
    window.addEventListener('load', function () {
        // Fetch all the forms we want to apply custom Bootstrap validation styles to
        var forms = document.getElementsByClassName('needs-validation');
        // Loop over them and prevent submission
        var validation = Array.prototype.filter.call(forms, function (form) {
            form.addEventListener('submit', function (event) {
                //console.log(event);
                var requeststatus = true;
                if (form.checkValidity() === false) {
                    event.preventDefault();
                    event.stopPropagation();
                    requeststatus = false;
                }
                console.log(event.target.elements['tel-1'].value);
                if (event.target.elements['tel-1'].value) {
                    try {
                        const phoneNumber = libphonenumber.parsePhoneNumber(event.target.elements['tel-1'].value);
                        if (!phoneNumber.isValid()) {
                            event.preventDefault();
                            event.stopPropagation();
                            console.log('Invalid phone number');
                            event.target.elements['tel-1'].classList.add('is-invalid');
                            requeststatus = false;
                        } else {
                            //event.target.elements['tel-1'].value = phoneNumber.formatInternational();
                            event.target.elements['tel-1'].classList.remove('is-invalid');
                        }
                    } catch (error) {
                        requeststatus = false;
                        console.log(error);
                        event.preventDefault();
                        event.stopPropagation();
                        event.target.elements['tel-1'].classList.add('is-invalid');
                    }
                }
                form.classList.add('was-validated');
                if(requeststatus){
                    let resdata = null;
                    const formData = new FormData(form);
                    //console.log(formData);
                    const xhr = new XMLHttpRequest();
                    xhr.open('POST', './save_member.php', true);
                    xhr.responseType = 'json';
                    xhr.onload = function() {
                        console.log(xhr.response);
                        if (xhr.status >= 200 && xhr.status < 300) {
                            if(xhr.response.status == 'true'){
                                location.reload();
                            }else{
                                if(xhr.response.data){
                                    var resdata = xhr.response.data;
                                    var errorhtml = '<ul></ul>';
                                    for(var rkey in resdata) {
                                        if (resdata.hasOwnProperty(rkey)) {
                                            errorhtml += '<li class="text-danger">'+resdata[rkey]+'</li>'; 
                                        }
                                    }
                                    errorhtml += '</ul>';
                                    document.getElementById('formrespo').innerHTML = errorhtml;
                                   
                                }
                            }
                            //console.log(200);
                        } else {
                            
                            
                            console.log(xhr.response);
                        }
                    };
                    xhr.onerror = function() {
                        document.getElementById('result').innerHTML = `<p>Request failed</p>`;
                    };            
                    xhr.send(formData);
                }
                
                event.preventDefault();
                event.stopPropagation();
            }, false);
        });
    }, false);
})();
(function () {
    'use strict';
    document.getElementById('verifyemail').onclick = function () {
        if (document.getElementById('PersonalEmail').value) {  
            document.getElementById('otpload').style.display = "block";
            var xhr = new XMLHttpRequest();
            xhr.open('POST', './verify_mail.php', true);
            xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
           xhr.responseType = 'json';
            xhr.onload = function () {
                if (xhr.status >= 200 && xhr.status < 300) {
                    // Success! Handle the response
                    if(xhr.response.status == 'true'){
                        document.getElementById('verifyemail').style.display = "none";
                        document.getElementById('verifybtn').style.display = "block";
                        document.getElementById('verifybtnmsg').style.display = "block"; 
                        document.getElementById('otpload').style.display = "none";                       
                    }
                    console.log('Success:', xhr);
                } else {
                    // Error! Handle the error
                    console.error('Error:', xhr.statusText);
                    document.getElementById('otpload').style.display = "none";
                }
            };

            // Prepare the data to be sent
            var data = JSON.stringify({
                email: document.getElementById('PersonalEmail').value
            });

            // Send the request with the data
            xhr.send(data);
        } else {
            alert("Email required");
        }

    };
    
    document.getElementById('verifybtn').onclick = function () {
        if (document.getElementById('otpverify').value) {
           // console.log(document.getElementById('otpverify').value);
            var otpvalue = document.getElementById('otpverify').value;
            var xhr = new XMLHttpRequest();
            xhr.open('POST', './verify_mail.php', true);
            xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
            xhr.responseType = 'json';
            xhr.onload = function () {
                console.log(xhr.response);
                if(xhr.response.token){
                    document.getElementById('verifytoken').value = xhr.response.token;
                    document.getElementById('verifybtn').style.display = 'none';                    
                    document.getElementById('verifybtnmsg').innerHTML = "<span class='text-success'>Verified successfully</span>";
                }else{

                }
                
            };
            var data = JSON.stringify({
                vemail: document.getElementById('PersonalEmail').value,
                otp:otpvalue
            });
            xhr.send(data);
        }else{
            document.getElementById('verifybtnmsg').innerHTML = "<span class='text-danger'>OTP Cannot be blank</span>";
        }
    };
    const acceptance1 = document.getElementById('acceptance1');
    acceptance1.addEventListener('change', e => {
        if (e.target.checked === true) {
            console.log("Checkbox is checked - boolean value: ", e.target.checked)
            document.getElementById("acceptance2_area").style.display='none';
        }else{
            console.log("Checkbox is not checked - boolean value: ", e.target.checked)
            document.getElementById("acceptance2_area").style.display='block';
        }
        
    });
    const acceptance2 = document.getElementById('acceptance2');
    acceptance2.addEventListener('change', e => {
        if (e.target.checked === true) {
            console.log("Checkbox is checked - boolean value: ", e.target.checked)
            document.getElementById("acceptance1_area").style.display='none';
            document.getElementById("acceptance2_area_inner").style.display='block';
            
        }else{
            console.log("Checkbox is not checked - boolean value: ", e.target.checked)
            document.getElementById("acceptance1_area").style.display='block';
            document.getElementById("acceptance2_area_inner").style.display='none';
        }
        
    });

})();

