
jQuery(document).ready(function($) {
    
    $(document).on("click", ".remove-row", function() {
        $(this).closest("tr").remove();
        iafwzdesk_updateOptions();
    });
    jQuery(".iafwzdesk-setup-loading-text p").html(
        "Choose all items above to continue to the next step."
    );
    
});

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

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

    const formName = jQuery('#iafwzdesk-setup-formName').val();
    if (!formName) {
        jQuery(".iafwzdesk-setup-loading-text p").html("Choose all items above to continue to the next step.");
        resetFields();
        return;
    }

    jQuery(".iafwzdesk-setup-loading-text p").html("Choose all items above to continue to the next step.");
    resetFields();
}

function iafwzdesk_handleAccountChange() {
    const resetFields = () => {
        const moduleSelect = jQuery('#iafwzdesk-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("#iafwzdesk-setup-fieldMapping-area").hide();
        jQuery('#iafwzdesk-setup-fieldMapping-table tbody').empty();
    };

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

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

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

        if (account_id == "") {
            jQuery(".iafwzdesk-setup-loading-text p").html("Choose all items above to continue to the next step.");
            resetFields();
            return;
        }

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

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

                    const moduleSelect = jQuery('#iafwzdesk-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.id) // Add '-premium' for custom modules
                        .text(list.name);
                        moduleSelect.append(option);
                    });
                } else {
                    resetFields();
                    jQuery(".iafwzdesk-setup-loading-text p").html("Choose all items above to continue to the next step.");
                    alert(response.data.error);
                }
            },
            error: function () {
                enableFields();
                resetFields();
                jQuery(".iafwzdesk-setup-loading-text p").html("Choose all items above to continue to the next step.");
                alert("A network error occurred. Please check your connection or try again later.");
            }
        });
    } else {
        iafwzdesk_handleFormChange();
        alert("Please choose a form name to proceed.");
    }
}

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

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

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

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

    jQuery(".iafwzdesk-setup-loading-text").show();
    if (moduleValue=="") {
        jQuery(".iafwzdesk-setup-loading-text p").html("Choose all items above to continue to the next step.");
        enableFields();
        resetFields();
        return;
    }

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

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

    jQuery.ajax({
        url: iafwzdesk_field_mapping.ajax_url,
        type: 'POST',
        data: {
            action: 'iafwzdesk_handle_request',
            account_id: accountId,
            form_value: formValue,
            module_api_name: moduleValue,
            action_key: "get_field",
            security: iafwzdesk_field_mapping.field_mapping_nonce
        },
        success: function (response) {
            enableFields();
            if (response.success) {
                jQuery(".iafwzdesk-setup-loading-text").hide();
                jQuery("#iafwzdesk-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.apiName,
                        field.displayLabel,
                        field.type,
                        field.isMandatory,
                        field.iafwzdesk_group,
                        field.iafwzdesk_session,
                        field.allowedValues
                    ]);
                // Filter to include only system mandatory fields
                    const mandatoryProductFields = crm_fields
                    .filter(field => field.isMandatory)
                    .map(field => [
                        field.apiName,
                        field.displayLabel,
                        field.type,
                        field.isMandatory
                    ]);
                    // Load form fields
                    const form_fields = response.data.form_fields;
                    cf7Fields = form_fields.map(field => [
                    field.key,
                    field.label,
                    field.type,
                    field.source,
                    ]);
                    iafwzdesk_updateAvailableFields(form_fields);
                     //-------Render Filter Criteria
                     iafwzdesk_addList_to_filter();
                    // Loop through mandatory to create a row for each
                    mandatoryProductFields.forEach(productField => {
                        let newRow = `
                        <tr>
                            <td class='iafwzdesk-setup-td'>
                               <select class="iafwzdesk-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='iafwzdesk-setup-td' data-ref='mandatory'>
                                <select class="iafwzdesk-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='iafwzdesk-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
                    let $newRow = jQuery(newRow);
                    jQuery("#iafwzdesk-setup-fieldMapping-table tbody").append($newRow);

                    // Trigger the change event for the .product-fields-select dropdown
                    $newRow.find(".product-fields-select").trigger("change");

                    });
                    // Enable the "add" button only for the last row
                    jQuery("#iafwzdesk-setup-fieldMapping-table tbody tr:last-child .add-row").prop("disabled", false);
                    iafwzdesk_updateOptions();
            } else {
                enableFields();
                resetFields();
                jQuery(".iafwzdesk-setup-loading-text p").html("Choose all items above to continue to the next step.");
                alert(response.data.error);
            }
        },
        error: function () {
            enableFields();
            resetFields();
            jQuery(".iafwzdesk-setup-loading-text p").html("Choose all items above to continue to the next step.");
            alert("A network error occurred. Please check your connection or try again later.");
        }
    });
}

function iafwzdesk_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="iafwzdesk-setup-td">
                <select class="iafwzdesk-fm-setup-select cf7-select">
                    ${cf7Options}
                </select>
            </td>
            <td class="iafwzdesk-setup-td">
                <select class="iafwzdesk-fm-setup-select product-fields-select">
                    ${productOptions}
                    
                </select>
            </td>
            <td class="iafwzdesk-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
    iafwzdesk_updateOptions();
}


function iafwzdesk_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="iafwzdesk-setup-td">
                <select class="iafwzdesk-fm-setup-select cf7-select">
                    ${cf7Options}
                </select>
            </td>
            <td class="iafwzdesk-setup-td">
                <select class="iafwzdesk-fm-setup-select product-fields-select">
                    ${productOptions}
                   
                </select>
            </td>
            <td class="iafwzdesk-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("#iafwzdesk-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
    iafwzdesk_updateOptions();
}




// Function to update field options based on selections
function iafwzdesk_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();
    this.style.setProperty("width", "100%", "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.value + '">' + item.value + ' <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);

    this.style.setProperty("width", "85%", "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)
    iafwzdesk_updateOptions();
});


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



function iafwzdesk_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("#iafwzdesk-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(".iafwzdesk-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() === "iafwzdesk_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("#iafwzdesk-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(".iafwzdesk-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() === "iafwzdesk_custom_value" ? "custom field" : "form field";
            let fieldValue = formFieldSelect.val() === "iafwzdesk_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('#iafwzdesk-setup-formName').val();
        var accountName = jQuery('#iafwzdesk-setup-accountName').val();
        var moduleName = jQuery('#iafwzdesk-setup-moduleName').val();
        var integrationName = jQuery("#iafwzdesk-setup-integrationName").val();
        var filterCriteria = iafwzdesk_readFilterConditions();
        if(integrationName=="" || integrationName==null)
        {
            jQuery("#iafwzdesk-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("#iafwzdesk-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: iafwzdesk_field_mapping.ajax_url, // WordPress AJAX URL
            type: 'POST',
            data: {
                action: 'iafwzdesk_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: iafwzdesk_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 iafwzdesk_toggleIntegrationStatus(integrationId, checkbox) {
    // Determine the new status based on the current checkbox state
    const isActive = checkbox.checked;

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

function iafwzdesk_setExistingMapping()
{
    const crm_fields = crmFieldList;
    productFields = crm_fields
        .map(field => [
            field.apiName, 
            field.displayLabel,
            field.type,
            field.isMandatory,
            field.iafwzdesk_group,
            field.iafwzdesk_session,
            field.allowedValues
        ]);
    // Filter to include only system mandatory fields
        const mandatoryProductFields = crm_fields
       
        .filter(field => field.isMandatory)
        .map(field => [
            field.apiName,
            field.displayLabel,
            field.type,
            field.isMandatory
        ]);
            // Load form fields
            cf7Fields = formFieldList.map(field => [
                field.key,
                field.label,
                field.type,
                field.source,
                ]);
                iafwzdesk_updateAvailableFields(formFieldList);
                 //-------Render Filter Criteria
                 iafwzdesk_addList_to_filter();
                 iafwzdesk_createFilterUI(filterCriteria);
                // Loop through  to create a row for each
            mandatoryProductFields.forEach(productField => {
                let newRow = `
                <tr>
                    <td class='iafwzdesk-setup-td'>
                       <select class="iafwzdesk-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='iafwzdesk-setup-td' data-ref='mandatory'>
                        <select class="iafwzdesk-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='iafwzdesk-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
              let $newRow = jQuery(newRow);
              jQuery("#iafwzdesk-setup-fieldMapping-table tbody").append($newRow);

              // Trigger the change event for the .product-fields-select dropdown
              $newRow.find(".product-fields-select").trigger("change");
            });
            // Enable the "add" button only for the last row
            jQuery("#iafwzdesk-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('.iafwzdesk-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('.iafwzdesk-fm-setup-select.cf7-select');
                            if (fieldType === 'custom field') {
                                // Set the previous select element's value to "custom value"
                                previousSelect.val("iafwzdesk_custom_value");
                                
                                let customInputContainer = previousSelect.find('.iafwzdesk-setup-fm-custom-input');
                                if (customInputContainer.length === 0) {
                                    customInputContainer = jQuery('<div style="position: relative;"><textarea type="text" class="iafwzdesk-setup-fm-custom-input" placeholder="Enter text or choose from options"> </textarea><div class="iafwzdesk-setup-fm-dropdownSuggestions"></div> </div>');
                                    previousSelect.after(customInputContainer); // Add it within the last row
                                }
                                
                                // Set the value of the custom input container
                                customInputContainer.find('.iafwzdesk-setup-fm-custom-input').val(fieldValue || '');  

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

                    // Get the table body
                    const tableBody = jQuery("#iafwzdesk-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("iafwzdesk_custom_value");
                        
                        // Append a custom input container within the same row if it doesn't exist
                        let customInputContainer = lastRow.find('.iafwzdesk-setup-fm-custom-input');
                        if (customInputContainer.length === 0) {
                            customInputContainer = jQuery('<div style="position: relative;"><textarea type="text" class="iafwzdesk-setup-fm-custom-input" placeholder="Enter text or choose from options"></textarea> <div class="iafwzdesk-setup-fm-dropdownSuggestions"></div> </div>');
                            cf7FieldElement.after(customInputContainer); // Add it within the last row
                        }
                        
                        // Set the value of the custom input container
                        customInputContainer.find('.iafwzdesk-setup-fm-custom-input').val(fieldValue || '');  // Set 
                    }  
                    else {
                        // Set the select element's value directly
                        cf7FieldElement.val(fieldValue);
                    }
                }
                
            });
            if (existingFieldMapping.hasOwnProperty("attachment")) {
                // Loop through each value in the attachment array
                existingFieldMapping["attachment"].forEach((value, index) => {
            
                    // Add a new row without triggering the default event
                    iafwzdesk_addRowWithoutEvent();
            
                    // Get the table body
                    const tableBody = jQuery("#iafwzdesk-setup-fieldMapping-table tbody");
            
                    // Select the last row in the table body
                    const lastRow = tableBody.find('tr').last();
            
                    // Select the CF7 and Zoho field elements in the last row
                    const cf7FieldElement = lastRow.find('.cf7-select'); // Select element for CF7 fields
                    const zohoFieldElement = lastRow.find('.product-fields-select'); // Select element for Zoho fields
            
                    // Set the values for the last row
                    zohoFieldElement.val("attachment"); // Set the Zoho field to "attachment"
                    cf7FieldElement.val(value); // Set the CF7 field to the current value in the array
                });
            }
            iafwzdesk_updateOptions();
}
