
jQuery(document).ready(function($) {
    
    $(document).on("click", ".remove-row", function() {
        $(this).closest("tr").remove();
        iafwzcai_updateOptions();
    });
    jQuery(".iafwzcai-setup-loading-text p").html(
        "Please select a <b>form</b>, <b>account</b>, and <b>list</b> to proceed to the next step."
    );
    
});

function iafwzcai_showIntegrationForm()
{
    jQuery("#iafwzcai-setup-popupOverlay").toggleClass("show");
    
}
function iafwzcai_handleFormChange() {
    const resetFields = () => {
        jQuery('#iafwzcai-setup-accountName').val("");
        jQuery('#iafwzcai-setup-moduleName').val("");
        jQuery("#iafwzcai-setup-fieldMapping-area").hide();
        jQuery('#iafwzcai-setup-fieldMapping-table tbody').empty();
    };

    jQuery('.iafwzcai-setup-loading-text').show();

    const formName = jQuery('#iafwzcai-setup-formName').val();
    if (!formName) {
        jQuery(".iafwzcai-setup-loading-text p").html("Please select a <b>form</b> to continue.");
        resetFields();
        return;
    }

    jQuery(".iafwzcai-setup-loading-text p").html("Please select an <b>account</b> to continue.");
    resetFields();
}

function iafwzcai_handleAccountChange() {
    const resetFields = () => {
        const moduleSelect = jQuery('#iafwzcai-setup-moduleName');
        moduleSelect.empty(); // Clear existing options
        moduleSelect.append(jQuery('<option></option>')
            .attr('value', '')
            .text('Select')); // Add default "Select" option
        
        moduleSelect.val(""); // Set value to empty string
        jQuery("#iafwzcai-setup-fieldMapping-area").hide();
        jQuery('#iafwzcai-setup-fieldMapping-table tbody').empty();
    };

    const enableFields = () => {
        jQuery('#iafwzcai-setup-formName').prop('disabled', false);
        jQuery('#iafwzcai-setup-accountName').prop('disabled', false);
        jQuery('#iafwzcai-setup-moduleName').prop('disabled', false);
    };

    jQuery('.iafwzcai-setup-loading-text').show();

    const formName = jQuery('#iafwzcai-setup-formName').val();
    if (formName && formName !== "") {
        const account_id = jQuery('#iafwzcai-setup-accountName').val();

        if (account_id == "") {
            jQuery(".iafwzcai-setup-loading-text p").html("Please select an <b>account</b> to continue.");
            resetFields();
            return;
        }

        jQuery(".iafwzcai-setup-loading-text p").text("Loading...");
        resetFields();
        jQuery('#iafwzcai-setup-formName, #iafwzcai-setup-accountName, #iafwzcai-setup-moduleName').prop('disabled', true);

        // Make AJAX call to fetch module data
        jQuery.ajax({
            url: iafwzcai_field_mapping.ajax_url,
            type: 'POST',
            data: {
                action: 'iafwzcai_handle_request',
                account_id: account_id,
                form_value: formName,
                action_key: "get_mailchimp_list",
                security: iafwzcai_field_mapping.field_mapping_nonce
            },
            success: function (response) {
                enableFields();
                if (response.success) {
                    jQuery(".iafwzcai-setup-loading-text p").html("Please select a <b>list</b> to continue.");
                    
                    const modulesArray = response.data.contact_list || [];

                    const moduleSelect = jQuery('#iafwzcai-setup-moduleName');
                    moduleSelect.empty(); // Clear existing options
                    moduleSelect.append(jQuery('<option></option>')
                        .attr('value', '')
                        .text('Select')); // Add default "Select" option

                        modulesArray.forEach(list => {
                        const option = jQuery('<option></option>')
                        .attr('value', list.listkey) // Add '-premium' for custom modules
                        .text(list.listname);
                        moduleSelect.append(option);
                    });
                } else {
                    resetFields();
                    jQuery(".iafwzcai-setup-loading-text p").html("Please select an <b>account</b> to continue.");
                    alert(response.data.error);
                }
            },
            error: function () {
                enableFields();
                resetFields();
                jQuery(".iafwzcai-setup-loading-text p").html("Please select an <b>account</b> to continue.");
                alert("A network error occurred. Please check your connection or try again later.");
            }
        });
    } else {
        iafwzcai_handleFormChange();
        alert("Please choose a form name to proceed.");
    }
}

var productFields = [];
var cf7Fields = [];
function iafwzcai_handleModuleChange() {
    const resetFields = () => {
        jQuery("#iafwzcai-setup-fieldMapping-area").hide();
        jQuery('#iafwzcai-setup-fieldMapping-table tbody').empty();
    };

    const enableFields = () => {
        jQuery('#iafwzcai-setup-formName').prop('disabled', false);
        jQuery('#iafwzcai-setup-accountName').prop('disabled', false);
        jQuery('#iafwzcai-setup-moduleName').prop('disabled', false);
    };

    const disableFields = () => {
        jQuery('#iafwzcai-setup-formName').prop('disabled', true);
        jQuery('#iafwzcai-setup-accountName').prop('disabled', true);
        jQuery('#iafwzcai-setup-moduleName').prop('disabled', true);
    };

    const moduleValue = jQuery('#iafwzcai-setup-moduleName').val();

    jQuery(".iafwzcai-setup-loading-text").show();
    if (moduleValue=="") {
        jQuery(".iafwzcai-setup-loading-text p").html("Please select a <b>list</b> to proceed to the next step.");
        enableFields();
        resetFields();
        return;
    }

    
    jQuery(".iafwzcai-setup-loading-text p").text("Loading...");
    disableFields();
    resetFields();

    const formValue = jQuery('#iafwzcai-setup-formName').val();
    const accountId = jQuery('#iafwzcai-setup-accountName').val();

    jQuery.ajax({
        url: iafwzcai_field_mapping.ajax_url,
        type: 'POST',
        data: {
            action: 'iafwzcai_handle_request',
            account_id: accountId,
            form_value: formValue,
            module_api_name: moduleValue,
            action_key: "get_field",
            security: iafwzcai_field_mapping.field_mapping_nonce
        },
        success: function (response) {
            enableFields();
            if (response.success) {
                jQuery(".iafwzcai-setup-loading-text").hide();
                jQuery("#iafwzcai-setup-fieldMapping-area").show();
                
               // Assuming response.data contains the JSON with field details
                const crm_fields = response.data.crm_fields;
                productFields = crm_fields
                    .map(field => [
                        field.DISPLAY_NAME,
                        field.DISPLAY_NAME,
                        field.UITYPE,
                        field.IS_MANDATORY,
                        field.iafwzcai_group,
                        field.iafwzcai_session,
                        field.options
                    ]);
                // Filter to include only system mandatory fields
                    const mandatoryProductFields = crm_fields
                    .filter(field => field.IS_MANDATORY)
                    .map(field => [
                        field.DISPLAY_NAME,
                        field.DISPLAY_NAME,
                        field.UITYPE,
                        field.IS_MANDATORY
                    ]);

                    // Load form fields
                    const form_fields = response.data.form_fields;
                    cf7Fields = form_fields.map(field => [
                    field.key,
                    field.label,
                    field.type,
                    field.source,
                    ]);
                    iafwzcai_updateAvailableFields(form_fields);
                     //-------Render Filter Criteria
                     iafwzcai_addList_to_filter();
                    // Loop through mandatory to create a row for each
                    mandatoryProductFields.forEach(productField => {
                        let newRow = `
                        <tr>
                            <td class='iafwzcai-setup-td'>
                               <select class="iafwzcai-fm-setup-select cf7-select">
                                <option value="">Select</option>
                                <optgroup label="Form Fields">
                                    ${cf7Fields
                                        .filter(cf7Field => cf7Field[3] !== 'custom') // Non-custom fields
                                        .map(cf7Field => `
                                            <option value="${cf7Field[0]}" style="color: blue;">
                                                ${cf7Field[1]} 
                                            </option>`).join('')}
                                </optgroup>
                                <optgroup label="System Fields">
                                    ${cf7Fields
                                        .filter(cf7Field => cf7Field[3] === 'custom') // Custom fields
                                        .map(cf7Field => `
                                            <option value="${cf7Field[0]}" style="color: blue;">
                                                ${cf7Field[1]}
                                            </option>`).join('')}
                                </optgroup>
                            </select>

                            </td>
                            <td class='iafwzcai-setup-td' data-ref='mandatory'>
                                <select class="iafwzcai-fm-setup-select product-fields-select" title="Mandatory field" style="border-left: 3px solid #ff000094  !important;" disabled>
                                  <option value="${productField[0]}" data-type="${productField[2]}" style="color: blue;">
                                    ${productField[1]} 
                                </option>
                                </select>
                            </td>
                            <td class='iafwzcai-setup-td' style="border: none; background: none;">
                                 <button type="button" class="add-row" disabled>+</button>
                               <button type="button" disabled title="Mandatory field, not able to remove">−</button>
                            </td>
                        </tr>
                    `;
                    

                    // Append the new row to the tbody
                    jQuery("#iafwzcai-setup-fieldMapping-table tbody").append(newRow);
                    });
                    // Enable the "add" button only for the last row
                    jQuery("#iafwzcai-setup-fieldMapping-table tbody tr:last-child .add-row").prop("disabled", false);
                    iafwzcai_updateOptions();
            } else {
                enableFields();
                resetFields();
                jQuery(".iafwzcai-setup-loading-text p").html("Please select a <b>list</b> to proceed to the next step.");
                alert(response.data.error);
            }
        },
        error: function () {
            enableFields();
            resetFields();
            jQuery(".iafwzcai-setup-loading-text p").html("Please select a <b>list</b> to proceed to the next step.");
            alert("A network error occurred. Please check your connection or try again later.");
        }
    });
}

function iafwzcai_addRow(event) {
    // Group the CF7 options into System Fields and Form Fields
    let systemFields = cf7Fields
        .filter(cf7Field => cf7Field[3] === 'custom')
        .map(cf7Field => `<option value="${cf7Field[0]}" style="color: blue;">
            ${cf7Field[1]} 
        </option>`).join('');

    let formFields = cf7Fields
        .filter(cf7Field => cf7Field[3] !== 'custom')
        .map(cf7Field => `<option value="${cf7Field[0]}" style="color: blue;">
            ${cf7Field[1]} 
        </option>`).join('');

    var cf7Options = `
        <option value="">Select</option>
        <optgroup label="Form Fields">
            ${formFields}
        </optgroup>
        <optgroup label="System Fields">
            ${systemFields}
        </optgroup>
    `;
   
    // Categorize into groups
    let groupedProductFields = {
        "General Fields": productFields.filter(field => field[4] === "General Fields"),
        "Address Fields": productFields.filter(field => field[4] === "Address Fields"),
        "Custom Fields": productFields.filter(field => field[4] === "Custom Fields"),
        "Premium Fields": productFields.filter(field => field[4] === "Premium Fields")
    };

    // Generate options for fields with proper <optgroup> tags
    let productOptions = '<option value="">Select</option>';
    for (let group in groupedProductFields) {
        if (groupedProductFields[group].length > 0) { // Check if the group is not empty
            let options = groupedProductFields[group]
                .map(field => `<option value="${field[0]}" data-type="${field[2]}" style="color: blue;">
                    ${field[1]}
                </option>`).join('');
            productOptions += `<optgroup label="${group}">${options}</optgroup>`;
        }
    }

    // Define the new row HTML with the options included
    let newRow = `
        <tr>
            <td class="iafwzcai-setup-td">
                <select class="iafwzcai-fm-setup-select cf7-select">
                    ${cf7Options}
                </select>
            </td>
            <td class="iafwzcai-setup-td">
                <select class="iafwzcai-fm-setup-select product-fields-select">
                    ${productOptions}
                    
                </select>
            </td>
            <td class="iafwzcai-setup-td" style="border: none; background: none;">
                <button type="button" class="add-row">+</button>
                <button type="button" class="remove-row">−</button>
            </td>
        </tr>
    `;

    // Insert the new row immediately after the current row where the add button was clicked
    jQuery(event.currentTarget).closest('tr').after(newRow);

    // Reapply the disable function for each row's field select
    iafwzcai_updateOptions();
}


function iafwzcai_addRowWithoutEvent() {
    // Group the CF7 options into System Fields and Form Fields
    let systemFields = cf7Fields
        .filter(cf7Field => cf7Field[3] === 'custom')
        .map(cf7Field => `<option value="${cf7Field[0]}" style="color: blue;">
            ${cf7Field[1]} 
        </option>`).join('');

    let formFields = cf7Fields
        .filter(cf7Field => cf7Field[3] !== 'custom')
        .map(cf7Field => `<option value="${cf7Field[0]}" style="color: blue;">
            ${cf7Field[1]} 
        </option>`).join('');

    var cf7Options = `
        <option value="">Select</option>
        <optgroup label="Form Fields">
            ${formFields}
        </optgroup>
        <optgroup label="System Fields">
            ${systemFields}
        </optgroup>
    `;

  // Categorize into groups
    let groupedProductFields = {
        "General Fields": productFields.filter(field => field[4] === "General Fields"),
        "Address Fields": productFields.filter(field => field[4] === "Address Fields"),
        "Custom Fields": productFields.filter(field => field[4] === "Custom Fields"),
        "Premium Fields": productFields.filter(field => field[4] === "Premium Fields")
    };

    // Generate options for fields with proper <optgroup> tags
    let productOptions = '<option value="">Select</option>';
    for (let group in groupedProductFields) {
        if (groupedProductFields[group].length > 0) { // Check if the group is not empty
            let options = groupedProductFields[group]
                .map(field => `<option value="${field[0]}" data-type="${field[2]}" style="color: blue;">
                    ${field[1]}
                </option>`).join('');
            productOptions += `<optgroup label="${group}">${options}</optgroup>`;
        }
    }

    // Define the new row HTML with the options included
    let newRow = `
        <tr>
            <td class="iafwzcai-setup-td">
                <select class="iafwzcai-fm-setup-select cf7-select">
                    ${cf7Options}
                </select>
            </td>
            <td class="iafwzcai-setup-td">
                <select class="iafwzcai-fm-setup-select product-fields-select">
                    ${productOptions}
                   
                </select>
            </td>
            <td class="iafwzcai-setup-td" style="border: none; background: none;">
                <button type="button" class="add-row">+</button>
                <button type="button" class="remove-row">−</button>
            </td>
        </tr>
    `;

    // Insert the new row as the last row if there are existing rows; otherwise, add it as the first row
    const tableBody = jQuery("#iafwzcai-setup-fieldMapping-table tbody");
    if (tableBody.find('tr').length > 0) {
        tableBody.append(newRow); // Add as last row
    } else {
        tableBody.prepend(newRow); // Add as first row if no rows exist
    }

    // Reapply the disable function for each row's field select
    iafwzcai_updateOptions();
}




// Function to update field options based on selections
function iafwzcai_updateOptions() {
    let selectedProductFields = [];

    // Get all selected values from each row
    jQuery(".product-fields-select").each(function () {
        let selectedValue = jQuery(this).val();
        if (selectedValue && selectedValue !== "attachment") {
            selectedProductFields.push(selectedValue);
        }
    });

    // Disable selected fields in each dropdown
    jQuery(".product-fields-select").each(function () {
        let currentDropdown = jQuery(this); // Reference to the current dropdown

        currentDropdown.find("option").each(function () {
            let optionValue = this.value; // Get the value of the current option
            let matchingField = productFields.find(field => field[0] === optionValue); // Find the matching fwField entry
            if (matchingField) {
                if (!matchingField[5]) {
                    // Disable the option and style it
                    jQuery(this).attr("disabled", true).css({
                        "color": "gray", // Simple gray for disabled
                        "text-shadow": "none", // Remove shadow for clarity
                    });
                }
                else if (
                    selectedProductFields.includes(this.value) && 
                    this.value !== currentDropdown.val()
                ) {
                    // Disable the option and style it if selected in another dropdown
                    jQuery(this).attr("disabled", true).css({
                        "color": "gray", // Simple gray for disabled
                        "text-shadow": "none", // Remove shadow for clarity
                    });
                }
                else {
                    // Enable the option and reset styles
                    jQuery(this).removeAttr("disabled").css({
                        "color": "blue", // Default blue for enabled options
                        "text-shadow": "", // Clear any applied shadow
                    });
                }
            }
        });
    });
    

}


jQuery(document).on("change", ".product-fields-select", function () {
    var selectedValue = jQuery(this).val().trim(); // Get selected value
    var numberList = '<div class="number-list">';
    var optionStatus=false;
    // Remove existing info-icon and popup-message if they exist
    jQuery(this).nextAll(".info-icon, .popup-message").remove();
    jQuery(this).css("width", "100%").attr("style", "width: 100% !important;"); // Apply width with !important
    // Iterate through productFields to find matching values
    productFields.forEach(function (field) {        
        // Ensure 'field' is an array and has at least one element
        if (Array.isArray(field) && field.length > 1) {
            // Check if first element matches selectedValue
            if (field[0] === selectedValue) {
                let lastElement = field[field.length - 1]; // Get last element
                
                // Ensure last element is an array and has values
                if (Array.isArray(lastElement) && lastElement.length > 0) {
                    lastElement.forEach(function (item) {
                        optionStatus = true;
                        numberList += '<div class="copy-item" data-text="' + item + '">' + item + ' <span class="copy-icon">📋</span></div>';
                    });
                }
            }
        }
    });
    
    if(optionStatus)
    {
    numberList += '</div>';
    var infoIcon = jQuery('<span class="info-icon"> ℹ️</span>'); // Info icon element
    var popupDiv = jQuery('<div class="popup-message"><p style="padding:2px;margin:0px;"><strong>Allowed Values:</strong> Click to copy and use.<p></div>').hide();
   
   

    popupDiv.append(numberList);

    jQuery(this).css("width", "85%").attr("style", "width: 85% !important;"); // Apply width with !important
    jQuery(this).after(infoIcon); // Insert info icon after select
    infoIcon.after(popupDiv); // Insert popup div after the icon

    // Show popup when hovering over icon
    infoIcon.on("mouseenter", function () {
        var selectedOption = jQuery(this).prev(".product-fields-select").find(":selected");
        var selectedText = selectedOption.text().trim();
    
        if (selectedText) {
            popupDiv.find('.popup-header').remove(); // Remove any previous header
            popupDiv.fadeIn(200);
    
            // Get the position of the info icon relative to the document
            var iconOffset = jQuery(this).offset();
            var iconWidth = jQuery(this).outerWidth();
            var iconHeight = jQuery(this).outerHeight();
            var popupWidth = popupDiv.outerWidth();
    
            // Position popup dynamically centered below the info-icon
            popupDiv.css({
                position: "fixed",
                top: iconOffset.top + iconHeight - jQuery(window).scrollTop() + 5 + "px", // Below the icon
                left: (iconOffset.left + iconWidth / 2) - (popupWidth / 2) + "px", // Center align with icon
                minWidth: "150px",
                maxWidth: "300px",
                zIndex: 9999,
                textAlign: "center"
            });
        }
    });
    
    

    // Keep the popup open when hovering over it
    popupDiv.on("mouseenter", function () {
        jQuery(this).stop(true, true).fadeIn(200);
    });

    // Hide popup when mouse leaves both the icon and popup
    infoIcon.add(popupDiv).on("mouseleave", function () {
        setTimeout(function () {
            if (!popupDiv.is(":hover")) {
                popupDiv.fadeOut(200);
            }
        }, 300);
    });

    // Copy text on click
    // Copy text on click (Fixed issue of multiple "Copied!" messages)
    jQuery(document).off("click", ".copy-item").on("click", ".copy-item", function () {
        var textToCopy = jQuery(this).attr("data-text");
        var tempInput = jQuery("<input>");
        jQuery("body").append(tempInput);
        tempInput.val(textToCopy).select();
        document.execCommand("copy");
        tempInput.remove();

        // Remove any existing "Copied!" text before adding a new one
        jQuery(".copied-text").remove();

        // Show copied feedback
        var copiedText = jQuery('<span class="copied-text"> Copied!</span>');
        jQuery(this).append(copiedText);

        setTimeout(function () {
            copiedText.fadeOut(300, function () {
                copiedText.remove();
            });
        }, 1000);
    });
    }
    // Call the function to update options (Ensure it's defined somewhere)
    iafwzcai_updateOptions();
});


jQuery(document).on("click", ".add-row", iafwzcai_addRow);



function iafwzcai_handleButtonClick(button) {

    button.textContent = "Please Wait...";
    let allFieldsFilled = true; // Flag to track if all fields are filled
    let fieldMapping = {}; // Object to store the JSON structure
    // Loop through each row in the table
    jQuery("#iafwzcai-setup-fieldMapping-table tbody tr").each(function() {
        // Get the select elements for Form Fields and CRM Fields
        let formFieldSelect = jQuery(this).find(".cf7-select");
        let crmFieldSelect = jQuery(this).find(".product-fields-select");
        
        // Check if formFieldSelect is "custom value" and requires an additional input
        let customInput = jQuery(this).find(".iafwzcai-setup-fm-custom-input");

        // Check if the current cell is marked as mandatory
        let formFieldTd = formFieldSelect.closest('td');
        let crmFieldTd = crmFieldSelect.closest('td');

        // Validate Form Field select
        if (formFieldSelect.val() === "") {
            formFieldSelect.attr("style", "border: 0.5px solid #ff00005e !important");
            allFieldsFilled = false;
        } else if (formFieldTd.data('ref') !== 'mandatory') {
            formFieldSelect.removeAttr("style"); // Reset border if valid and not mandatory
        }

        // Check for "custom value" and validate the custom input field
        if (formFieldSelect.val() === "iafwzcai_custom_value" && customInput.length && customInput.val().trim() === "") {
            customInput.attr("style", "border: 1px solid #ff00005e !important; box-shadow: 0 0 1px #ff00005e !important;");
            allFieldsFilled = false;
        } else if (formFieldTd.data('ref') !== 'mandatory') {
            customInput.removeAttr("style"); // Reset border if valid and not mandatory
        }

        // Validate CRM Field select
        if (crmFieldSelect.val() === "") {
            crmFieldSelect.attr("style", "border: 1px solid #ff00005e !important; box-shadow: 0 0 1px #ff00005e !important;");
            allFieldsFilled = false;
        } else if (crmFieldTd.data('ref') !== 'mandatory') {
            crmFieldSelect.removeAttr("style"); // Reset border if valid and not mandatory
        }
    });

    // If any field is empty, show an alert message
    if (allFieldsFilled) {

        // Loop through each row again to create the JSON structure
        jQuery("#iafwzcai-setup-fieldMapping-table tbody tr").each(function() {
            let formFieldSelect = jQuery(this).find(".cf7-select");
            let crmFieldSelect = jQuery(this).find(".product-fields-select");
            let customInput = jQuery(this).find(".iafwzcai-setup-fm-custom-input");

            let crmFieldKey = crmFieldSelect.val();
            let crmFieldType = crmFieldSelect.find("option:selected").data("type"); // Get the data-type attribute
            let fieldType = formFieldSelect.val() === "iafwzcai_custom_value" ? "custom field" : "form field";
            let fieldValue = formFieldSelect.val() === "iafwzcai_custom_value" ? customInput.val().trim() : formFieldSelect.val();

            if (crmFieldKey) {
                if (crmFieldKey === "attachment") {
                    // If key is "attachment", handle it as a list of values
                    if (!fieldMapping[crmFieldKey]) {
                        fieldMapping[crmFieldKey] = []; // Initialize as an empty list
                    }
                    // Add only the field_value to the list
                    fieldMapping[crmFieldKey].push(fieldValue);
                } else {
                fieldMapping[crmFieldKey] = {
                    field_type: fieldType,
                    field_value: fieldValue,
                    data_type: crmFieldType // Add data-type to the mapping
                };
            }
            }
        });
        var jsonOutput = JSON.stringify(fieldMapping, null, 2);
        var formName = jQuery('#iafwzcai-setup-formName').val();
        var accountName = jQuery('#iafwzcai-setup-accountName').val();
        var moduleName = jQuery('#iafwzcai-setup-moduleName').val();
        var integrationName = jQuery("#iafwzcai-setup-integrationName").val();
        var filterCriteria = iafwzcai_readFilterConditions();
        if(integrationName=="" || integrationName==null)
        {
            jQuery("#iafwzcai-setup-integrationName").css({
                "border": "1px solid #ff00005e", // Make the border red and visible
                "box-shadow": "0 0 1px #ff00005e" // Optional: Add a shadow to emphasize the element
            });
            alert("Oops! It looks like some required fields are missing. Please fill in the fields highlighted in red and try saving again.");
            button.textContent = "Save Mapping";
            return;
        }
        else
        {
            jQuery("#iafwzcai-setup-integrationName").css({
                "border": "", // Make the border red and visible
                "box-shadow": "" // Optional: Add a shadow to emphasize the element
            });
        }
            if(filterCriteria==false)
                {
                    alert("Oops! It looks like some required fields are missing. Please fill in the fields highlighted in red and try saving again.");
                    button.textContent = "Save Mapping";
                    return;
                }
                if (filterCriteria !== null && Array.isArray(filterCriteria)) {
                    filterCriteria = JSON.stringify(filterCriteria);
                }                
        //
        jQuery.ajax({
            url: iafwzcai_field_mapping.ajax_url, // WordPress AJAX URL
            type: 'POST',
            data: {
                action: 'iafwzcai_handle_request', // Action name registered in PHP
                integration_name: integrationName,
                form_value: formName,
                account_id: accountName,               // Data to send to PHP
                module_api_name: moduleName, 
                field_mapping : jsonOutput,  
                filter_Criteria : filterCriteria,
                setup_id :  typeof setupID !== 'undefined' ? setupID : null,       // Corrected key name to match convention
                action_key : "save_mapping",
                security: iafwzcai_field_mapping.field_mapping_nonce // Send nonce for security
            },
            success: function(response) {
                button.textContent = "Save Mapping";
                if (response.success) {
                    
                       // Get the current URL
                    let url = new URL(window.location.href);

                    // Remove the specific parameters
                    url.searchParams.delete('action');
                    url.searchParams.delete('setup_id');

                    // Reload the page with the updated URL
                    window.location.href = url.href;

                        
                } else {
                    alert(response.data.error);
                }
            },
            error: function() {
                button.textContent = "Save Mapping";
                alert("A network error occurred. Please check your connection or try again later.");
            }
        });
    }
    else
    {
        button.textContent = "Save Mapping";
        alert("Oops! It looks like some required fields are missing. Please fill in the fields highlighted in red and try saving again.");
    }
}

function iafwzcai_toggleIntegrationStatus(integrationId, checkbox) {
    // Determine the new status based on the current checkbox state
    const isActive = checkbox.checked;

    jQuery.ajax({
        url: iafwzcai_field_mapping.ajax_url, // WordPress AJAX URL
        type: 'POST',
        data: {
            action: 'iafwzcai_integration_status', // Action name registered in PHP
            integration_id: integrationId, // Pass the integration ID
            integration_status: isActive, // Send the current status
            security: iafwzcai_field_mapping.field_mapping_nonce // Send nonce for security
        },
        success: function(response) {
        //    
        },
        error: function() {
            // 
        }
    });
}

function iafwzcai_setExistingMapping()
{
    const crm_fields = crmFieldList;
    productFields = crm_fields
        .map(field => [
            field.DISPLAY_NAME,
            field.DISPLAY_NAME,
            field.UITYPE,
            field.IS_MANDATORY,
            field.iafwzcai_group,
            field.iafwzcai_session,
            field.options
        ]);
    // Filter to include only system mandatory fields
        const mandatoryProductFields = crm_fields
       
        .filter(field => field.IS_MANDATORY)
        .map(field => [
            field.DISPLAY_NAME,
            field.DISPLAY_NAME,
            field.UITYPE,
            field.IS_MANDATORY
        ]);
            // Load form fields
            cf7Fields = formFieldList.map(field => [
                field.key,
                field.label,
                field.type,
                field.source,
                ]);
                iafwzcai_updateAvailableFields(formFieldList);
                 //-------Render Filter Criteria
                 iafwzcai_addList_to_filter();
                 iafwzcai_createFilterUI(filterCriteria);
                // Loop through  to create a row for each
            mandatoryProductFields.forEach(productField => {
                let newRow = `
                <tr>
                    <td class='iafwzcai-setup-td'>
                       <select class="iafwzcai-fm-setup-select cf7-select">
                                <option value="">Select</option>
                                <optgroup label="Form Fields">
                                    ${cf7Fields
                                        .filter(cf7Field => cf7Field[3] !== 'custom') // Non-custom fields
                                        .map(cf7Field => `
                                            <option value="${cf7Field[0]}" style="color: blue;">
                                                ${cf7Field[1]}
                                            </option>`).join('')}
                                </optgroup>
                                <optgroup label="System Fields">
                                    ${cf7Fields
                                        .filter(cf7Field => cf7Field[3] === 'custom') // Custom fields
                                        .map(cf7Field => `
                                            <option value="${cf7Field[0]}" style="color: blue;">
                                                ${cf7Field[1]}  
                                            </option>`).join('')}
                                </optgroup>
                            </select>
                    </td>
                    <td class='iafwzcai-setup-td' data-ref='mandatory'>
                        <select class="iafwzcai-fm-setup-select product-fields-select" title="Mandatory field" style="border-left: 3px solid #ff000094  !important;" disabled>
                          <option value="${productField[0]}" data-type="${productField[2]}" style="color: blue;">
                            ${productField[1]} 
                        </option>
                        </select>
                    </td>
                    <td class='iafwzcai-setup-td' style="border: none; background: none;">
                         <button type="button" class="add-row" disabled>+</button>
                       <button type="button" disabled title="Mandatory field, not able to remove">−</button>
                    </td>
                </tr>
            `;
            

            // Append the new row to the tbody
            jQuery("#iafwzcai-setup-fieldMapping-table tbody").append(newRow);
            });
            // Enable the "add" button only for the last row
            jQuery("#iafwzcai-setup-fieldMapping-table tbody tr:last-child .add-row").prop("disabled", false);
            //
            Object.keys(existingFieldMapping).forEach((crmFields) => {
                const fieldType = existingFieldMapping[crmFields].field_type || '';
                const fieldValue = existingFieldMapping[crmFields].field_value || '';
                // Check if the field is mandatory
                const isMandatory = productFields.some(field => field[0] === crmFields && field[3]);
                
                if (isMandatory) {
                    jQuery('.iafwzcai-fm-setup-select.product-fields-select').each(function() {
                        // Check if the current select element has crmFields as the selected value
                        if (jQuery(this).val() === crmFields) {
                            // Find the previous select element within the same row
                            var previousSelect = jQuery(this).closest('tr').find('.iafwzcai-fm-setup-select.cf7-select');
                            if (fieldType === 'custom field') {
                                // Set the previous select element's value to "custom value"
                                previousSelect.val("iafwzcai_custom_value");
                                
                                let customInputContainer = previousSelect.find('.iafwzcai-setup-fm-custom-input');
                                if (customInputContainer.length === 0) {
                                    customInputContainer = jQuery('<div style="position: relative;"><input type="text" class="iafwzcai-setup-fm-custom-input" placeholder="Enter text or choose from options"> <div class="iafwzcai-setup-fm-dropdownSuggestions"></div> </div>');
                                    previousSelect.after(customInputContainer); // Add it within the last row
                                }
                                
                                // Set the value of the custom input container
                                customInputContainer.find('.iafwzcai-setup-fm-custom-input').val(fieldValue || '');  

                            } else {
                                previousSelect.val(fieldValue);
                            }
                        }
                    });
                } else
                {                       
                     // Only add a new row for non-mandatory fields if no empty row is available
                     iafwzcai_addRowWithoutEvent(); // Assuming addRowWithoutEvent() creates a new row

                    // Get the table body
                    const tableBody = jQuery("#iafwzcai-setup-fieldMapping-table tbody");

                    // Select the last row in the table body
                    const lastRow = tableBody.find('tr').last();

                    // Select the actual CF7 and field elements in the last row
                    const cf7FieldElement = lastRow.find('.cf7-select'); // Select element for CF7 fields
                    const productFieldElement = lastRow.find('.product-fields-select'); // Select element for fields

                    // Retrieve specific details from the last row
                    productFieldElement.val(crmFields);
                    productFieldElement.val(crmFields).trigger("change");
                    if (fieldType === 'custom field') {
                        // Set the CF7 select element's value to "custom value"
                        cf7FieldElement.val("iafwzcai_custom_value");
                        
                        // Append a custom input container within the same row if it doesn't exist
                        let customInputContainer = lastRow.find('.iafwzcai-setup-fm-custom-input');
                        if (customInputContainer.length === 0) {
                            customInputContainer = jQuery('<div style="position: relative;"><input type="text" class="iafwzcai-setup-fm-custom-input" placeholder="Enter text or choose from options"> <div class="iafwzcai-setup-fm-dropdownSuggestions"></div> </div>');
                            cf7FieldElement.after(customInputContainer); // Add it within the last row
                        }
                        
                        // Set the value of the custom input container
                        customInputContainer.find('.iafwzcai-setup-fm-custom-input').val(fieldValue || '');  // Set 
                    }  
                    else {
                        // Set the select element's value directly
                        cf7FieldElement.val(fieldValue);
                    }
                }
                
            });
            iafwzcai_updateOptions();
}
