//Start get app properties from db js
function ai_app_onsite_get_app_properties() {
    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                var response = JSON.parse(xhr.responseText);
                // Check if status is 404 (Table does not exist or no rows found)
                if (response.status === '404') {
                    document.getElementById('app-properties-msg-container').innerHTML = '<p>It looks like some required settings are missing. Please ensure that "App Settings" are configured & an app has been created before adding app details.</p>';
                    document.getElementById('app-details-form').style.display = 'none';
                    return;
                }else {
                    document.getElementById('app-properties-msg-container').innerHTML = '';
                    document.getElementById('app-details-form').style.display = 'block';
                }
                // Accessing the first object in the array
                var firstObject = response[0];
                var app_logo = firstObject.appLogoImagePreview;
                var fileUploadDiv = document.getElementById('file-upload-div');
                var removeLogoBtn = document.getElementById('remove-logo-btn');
                var previewImage = document.getElementById('previewImage');

                if (app_logo != 'No preview available') {
                    previewImage.style.backgroundImage = `url('${app_logo}')`;
                    previewImage.style.backgroundSize = 'contain'; // Optional: Adjust background size
                    previewImage.style.backgroundRepeat = 'no-repeat'; // Optional: Prevent repetition
                    previewImage.style.backgroundPosition = 'center'; // Optional: Center the image
                    previewImage.style.display = 'block';
                    previewImage.style.width = '350px';
                    previewImage.style.height = '160px';
                    fileUploadDiv.classList.add('col-md-8');
                    fileUploadDiv.classList.remove('col-md-12');
                } else {
                    previewImage.style.backgroundImage = ''; // Remove any previous image
                    previewImage.style.display = 'none'; // Hide the preview image
                    removeLogoBtn.style.display = 'none';
                    fileUploadDiv.classList.add('col-md-12');
                    fileUploadDiv.classList.remove('col-md-8');
                }



                // Accessing properties of the first object
                var app_name = firstObject.app_name;
                var app_name_show = firstObject.app_name_show;

                var app_disclaimer = firstObject.app_disclaimer;
                var app_response_header = firstObject.response_header;
                var response_message = firstObject.response_message;
                var app_description = firstObject.app_description;
                var submit_button_txt = firstObject.submit_button_txt;

                if (app_name_show === "" || app_name_show == null) {
                    document.getElementById('app-name').value = app_name;
                } else {
                    document.getElementById('app-name').value = app_name_show;
                    var checkbox = document.getElementById('app-name-toggle');
                    checkbox.checked = true;
                }

                document.getElementById('app-disclaimer').value = app_disclaimer;
                document.getElementById('response-message').value = response_message;
                document.getElementById('response-header').value = app_response_header;
                document.getElementById('app-description').value = app_description;
                document.getElementById('submit-btn-txt').value = submit_button_txt;
                document.getElementById('preview-submit-btn-txt').textContent = submit_button_txt;
            } else {
                // Handle error response
                alert('Error: ' + xhr.status + ' ' + xhr.statusText);
            }

            const appDetailsFormTracker = trackFormChanges('#app-details-form');
            window.FormChangeRegistry.register('app_settings', appDetailsFormTracker, 'app-details');

            document.getElementById('save_ai_app_app_properties_data').addEventListener('click', function () {
                appDetailsFormTracker.reset();
            });
        }
    };

    xhr.open('POST', myPluginAjax.ajaxurl, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    xhr.send('action=ai_app_onsite_get_app_properties');
}

function getSelectedTitleColor(data) {
    for (var i = 0; i < data.length; i++) {
        if (data[i].hasOwnProperty('title_color_selected')) {
            return data[i].title_color_selected;
        }
    }
    return null;
}
function getSelectedFontColor(data) {
    for (var i = 0; i < data.length; i++) {
        if (data[i].hasOwnProperty('font_color_selected')) {
            return data[i].font_color_selected;
        }
    }
    return null;
}
function getSelectedBgColor(data) {
    for (var i = 0; i < data.length; i++) {
        if (data[i].hasOwnProperty('bg_color_selected')) {
            return data[i].bg_color_selected;
        }
    }
    return null;
}
//============End get app properties from db js========================

//Start save app_properties JS
function ai_app_onsite_save_app_properties() {
    // Clear all previous error messages
    document.querySelectorAll('.fields-error').forEach(function (error) {
        error.textContent = '';
    });

    // Get form fields
    var appName = document.getElementById('app-name').value.trim();
    var appDescription = document.getElementById('app-description').value.trim();
    var appResponseHeader = document.getElementById('response-header').value.trim();
    var appResponseMessage = document.getElementById('response-message').value.trim();
    var appDisclaimer = document.getElementById('app-disclaimer').value.trim();
    var appNameToggle = document.getElementById('app-name-toggle').checked

    // Collect error messages
    var errors = [];
    if (appName === '') {
        errors.push('App Name is required.');
    }
    if (appDescription === '') {
        errors.push('App Description is required.');
    }
    if (appDisclaimer === '') {
        errors.push('App Disclaimer is required.');
    }
    if (appDescription.length > 5000) {
        errors.push('App Description cannot exceed 5000 characters.');
    }
    if (appDisclaimer.length > 500) {
        errors.push('App Disclaimer cannot exceed 500 characters.');
    }
    // if (appResponseHeader === '') {
    //     errors.push('App Response Header is required.');
    // }

    // If there are errors, display them and return
    if (errors.length > 0) {
        errors.forEach(function (error) {
            // Find the corresponding error container and display the message
            if (error === 'App Name is required.') {
                document.getElementById('app-name-error').textContent = error;
            }
            if (error === 'App Description is required.' || error === 'App Description cannot exceed 5000 characters.') {
                document.getElementById('app-description-error').textContent = error;
            }
            if (error === 'App Disclaimer is required.' || error === 'App Disclaimer cannot exceed 500 characters.') {
                document.getElementById('app-disclaimer-error').textContent = error;
            }
            // if (error === 'App Response Header is required.') {
            //     document.getElementById('response-header-error').textContent = error;
            // }
        });
        return;
    }

    ai_app_onsite_get_plugin_settings_from_properties(function(settings) {
        let setting = settings?.result;

        const agreeTerms = Array.isArray(setting)
            ? setting[0]?.agree_terms === '1'
            : setting?.agree_terms === '1';

        if (!agreeTerms) {
            const modalElement = document.getElementById('terms_conditions_modal');
            const modalInstance = new bootstrap.Modal(modalElement);
            modalInstance.show();

            setTimeout(() => {
                const scrollContainer = document.getElementById('terms_conditions_modal')?.querySelector('.modal-body');
                if (scrollContainer) {
                    smoothScrollToBottom(scrollContainer, 1800); 
                }
            }, 500);

            return;
        }


        // Show loader
        var loader = document.getElementById('loader');
        loader.style.display = 'flex';

        // Create and send AJAX request
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                var messageContainer = document.getElementById('app-properties-msg-container');
                setTimeout(function () {
                    loader.style.display = 'none';

                    if (xhr.status === 200) {
                        // Handle the response from the server
                        var response = JSON.parse(xhr.responseText);

                        if (response.success) {
                            // Show success message
                            messageContainer.innerHTML = '<span style="color: green;"> ' + response.data + '</span>';
                        } else {
                            // Show error message if request fails
                            messageContainer.innerHTML = '<span style="color: red;">Error: ' + response.error + '</span>';
                        }
                    } else {
                        // Show error message if request fails
                        messageContainer.innerHTML = '<span style="color: red;">Error: Failed to save data</span>';
                    }
                    // Hide message after 3 seconds
                    setTimeout(function () {
                        messageContainer.innerHTML = '';
                    }, 3000);
                }, 2000);
            }
        };

        xhr.open('POST', myPluginAjax.ajaxurl, true);

        // Create FormData object
        var formData = new FormData();

        // Gather form data
        formData.append('action', 'ai_app_onsite_save_app_properties');
        formData.append('app-name', document.getElementById("app-name") ? document.getElementById("app-name").value : '');
        formData.append('app-name-show', document.getElementById("app-name-toggle").checked);

        // Check if file is selected
        const fileInput = document.getElementById('file-upload');
        if (fileInput.files.length > 0) {
            const file = fileInput.files[0];
            formData.append('app-file', file);
        }

        formData.append('app-description', document.getElementById("app-description") ? document.getElementById("app-description").value : '');
        formData.append('response-header', document.getElementById("response-header") ? document.getElementById("response-header").value : '');
        formData.append('response-message', appResponseMessage ? appResponseMessage : '');
        formData.append('app-disclaimer', document.getElementById("app-disclaimer") ? document.getElementById("app-disclaimer").value : '');
        formData.append('submit-btn-txt', document.getElementById("submit-btn-txt") ? document.getElementById("submit-btn-txt").value : '');

        // Check if radio buttons are selected before accessing their value
        //var titleColorRadio = document.querySelector('input[name="title-color"]:checked');

        var titleColorRadios = document.querySelectorAll('input[type="radio"][name="title-color"]');
        var titleColors = [];

        if (titleColorRadios) {
            titleColorRadios.forEach(function (titleColorRadio) {
                if (titleColorRadio.checked) {
                    titleColors.push({"title_color_selected": titleColorRadio.value});
                } else {
                    titleColors.push({"title_color": titleColorRadio.value});
                }
            });
        }

        // Append titleColors as a nested array within formData
        formData.append('titleColors', JSON.stringify(titleColors));

        //var fontColorRadio = document.querySelector('input[name="font-color"]:checked');
        //formData.append('font-color', fontColorRadio ? fontColorRadio.value : '');
        var fontColorRadios = document.querySelectorAll('input[type="radio"][name="font-color"]');
        var fontColor = [];

        if (fontColorRadios) {
            fontColorRadios.forEach(function (fontColorRadio) {
                if (fontColorRadio.checked) {
                    fontColor.push({"font_color_selected": fontColorRadio.value});
                } else {
                    fontColor.push({"font_color": fontColorRadio.value});
                }
            });
        }

        formData.append('fontColor', JSON.stringify(fontColor));

        // var bgColorRadio = document.querySelector('input[name="bg-color"]:checked');
        // formData.append('bg-color', bgColorRadio ? bgColorRadio.value : '');
        var bgColorRadios = document.querySelectorAll('input[type="radio"][name="bg-color"]');
        var bgColor = [];
     
        if (bgColorRadios) {
            bgColorRadios.forEach(function (bgColorRadio) {
                if (bgColorRadio.checked) {
                    bgColor.push({"bg_color_selected": bgColorRadio.value});
                } else {
                    bgColor.push({"bg_color": bgColorRadio.value});
                }
            });
        }

        formData.append('bgColor', JSON.stringify(bgColor));


        var btnColorRadios = document.querySelectorAll('input[type="radio"][name="btn-color"]');
        var btnColor = [];
        if (btnColorRadios) {
            btnColorRadios.forEach(function (btnColorRadio) {
                if (btnColorRadio.checked) {
                    btnColor.push({"btn_color_selected": btnColorRadio.value});
                } else {
                    btnColor.push({"btn_color": btnColorRadio.value});
                }
            });
        }
        formData.append('btnColor', JSON.stringify(btnColor));

        var btnFontColorRadios = document.querySelectorAll('input[type="radio"][name="btn-font-color"]');
        var btnFontColor = [];
        if (btnFontColorRadios) {
            btnFontColorRadios.forEach(function (btnFontColorRadio) {
                if (btnFontColorRadio.checked) {
                    btnFontColor.push({"btn_font_color_selected": btnFontColorRadio.value});
                } else {
                    btnFontColor.push({"btn_font_color": btnFontColorRadio.value});
                }
            });
        }
        formData.append('btnFontColor', JSON.stringify(btnFontColor));

        var responseBgColorRadios = document.querySelectorAll('input[type="radio"][name="response-bg-color"]');
        var responseBgColor = [];
        if (responseBgColorRadios) {
            responseBgColorRadios.forEach(function (responseBgColorRadio) {
                if (responseBgColorRadio.checked) {
                    responseBgColor.push({"response_bg_color_selected": responseBgColorRadio.value});
                } else {
                    responseBgColor.push({"response_bg_color": responseBgColorRadio.value});
                }
            });
        }
        formData.append('responseBgColor', JSON.stringify(responseBgColor));


        // Include nonce field value
        formData.append('ai_app_onsite_app_properties_nonce_field', document.getElementById("ai_app_onsite_app_properties_nonce_field").value);

        xhr.send(formData);
    });
}

function smoothScrollToBottom(element, duration = 1800) {
    const start = element.scrollTop;
    const end = element.scrollHeight - element.clientHeight;
    const distance = end - start;
    const startTime = performance.now();

    function easeInOutCubic(t) {
      return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
    }

    function step(currentTime) {
      const elapsed = currentTime - startTime;
      const progress = Math.min(elapsed / duration, 1); // progress: 0 → 1

      const ease = easeInOutCubic(progress);
      element.scrollTop = start + distance * ease;

      if (progress < 1) {
        requestAnimationFrame(step);
      }
    }

    requestAnimationFrame(step);
  }

function ai_app_onsite_get_plugin_settings_from_properties(callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', myPluginAjax.ajaxurl, true); 
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            var response = JSON.parse(xhr.responseText);
            if (xhr.status === 200) {
                callback(response); 
            } else {
                console.error('Error fetching plugin settings');
                callback({ status: xhr.status, message: xhr.statusText }); 
            }
        }
    };
    xhr.send('action=ai_app_onsite_get_plugin_settings');
}

//=========End save app_properties JS======================
