
jQuery(document).ready(function($) {
    
    $(document).on("click", ".remove-row", function() {
        $(this).closest("tr").remove();
        iafwzc_updateZohoOptions();
    });
    
    $(document).on('change', 'input[name="crm_action"]', function() {
        let actionName = $(this).val();
        
        if (actionName === "add_ignore_existing") {
            $("#iafwzc-setup-updateActionName-area").hide();
            $("#iafwzc-setup-updateActionName").val("");
        } else {
            $("#iafwzc-setup-updateActionName-area").show();
        }
    });

    $(document).on('change', 'input[name="note_value"]', function() {
        let noteValue = $(this).val();
        
        if (noteValue === "1") {
            $("#iafwzc-setup-note").show();
        } else {
            $("#iafwzc-setup-note").hide();
            $("#iafwzc-setup-note").val("");
        }
    });
    jQuery(".iafwzc-setup-loading-text p").html(
        "Please select a <b>form</b>, <b>account</b>, and <b>module</b> to proceed to the next step."
    );
});

function iafwzc_showIntegrationForm()
{
    jQuery("#iafwzc-setup-popupOverlay").toggleClass("show");
    
}
function iafwzc_handleFormChange() {
    const resetFields = () => {
        jQuery('#iafwzc-setup-accountName').val("");
        jQuery('#iafwzc-setup-moduleName').val("");
        jQuery('input[name="crm_action"][value="add_ignore_existing"]').prop('checked', true);
        jQuery('#iafwzc-setup-updateActionName').val("");
        jQuery('#iafwzc-setup-updateActionName-area').hide();
        jQuery('input[name="note_value"][value="0"]').prop('checked', true);
        jQuery("#iafwzc-setup-note").hide().val("");
        jQuery("#iafwzc-setup-fieldMapping-area").hide();
        jQuery('#iafwzc-setup-fieldMapping-table tbody').empty();
    };

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

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

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

function iafwzc_handleAccountChange() {
    const resetFields = () => {
        const moduleSelect = jQuery('#iafwzc-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('input[name="crm_action"][value="add_ignore_existing"]').prop('checked', true);
        jQuery('#iafwzc-setup-updateActionName').val("");
        jQuery('#iafwzc-setup-updateActionName-area').hide();
        jQuery('input[name="note_value"][value="0"]').prop('checked', true);
        jQuery("#iafwzc-setup-note").hide().val("");
        jQuery("#iafwzc-setup-fieldMapping-area").hide();
        jQuery('#iafwzc-setup-fieldMapping-table tbody').empty();
    };

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

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

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

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

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

        // Make AJAX call to fetch module data
        jQuery.ajax({
            url: iafwzc_field_mapping.ajax_url,
            type: 'POST',
            data: {
                action: 'iafwzc_handle_request',
                account_id: account_id,
                form_value: formName,
                action_key: "get_module",
                security: iafwzc_field_mapping.field_mapping_nonce
            },
            /*success: function (response) {
                enableFields();
                if (response.success) {
                    jQuery(".iafwzc-setup-loading-text p").html("Please select a <b>module</b> to continue.");
                    
                    const modulesArray = response.data.modules || [];
                    const validModules = modulesArray.filter(module => module.creatable && module.viewable);

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

                    validModules.forEach(module => {
                        const isCustom = module.generated_type === 'custom';
                        const option = jQuery('<option></option>')
                        .attr('value', module.api_name) // Add '-premium' for custom modules
                        .text(module.plural_label);
                        // if (isCustom) {
                        //     option.prop('disabled', true); // Disable option for custom modules
                        // }
                        moduleSelect.append(option);
                    });
                } else {
                    resetFields();
                    jQuery(".iafwzc-setup-loading-text p").html("Please select an <b>account</b> to continue.");
                    alert(response.data.error);
                }
            },*/
            success: function (response) {
            enableFields();
            if (response.success) {
                jQuery(".iafwzc-setup-loading-text p").html("Please select a <b>module</b> to continue.");
                
                const modulesArray = response.data.modules || [];
                const validModules = modulesArray.filter(module => module.creatable && module.viewable);

                // Group modules
                const generalModules = validModules.filter(module => module.generated_type !== 'custom');
                const customModules = validModules.filter(module => module.generated_type === 'custom');

                const moduleSelect = jQuery('#iafwzc-setup-moduleName');
                moduleSelect.empty();
                moduleSelect.append(jQuery('<option></option>').attr('value', '').text('Select'));

                // General Modules optgroup
                if (generalModules.length > 0) {
                    const generalGroup = jQuery('<optgroup></optgroup>').attr('label', 'General Modules');
                    generalModules.forEach(module => {
                        const option = jQuery('<option></option>')
                            .attr('value', module.api_name)
                            .text(module.plural_label);
                        generalGroup.append(option);
                    });
                    moduleSelect.append(generalGroup);
                }

                // Custom Modules optgroup
                if (customModules.length > 0) {
                    const customGroup = jQuery('<optgroup></optgroup>').attr('label', 'Custom Modules');
                    customModules.forEach(module => {
                        const isProEnabled = module.iafwzc_session === true;
                        const option = jQuery('<option></option>')
                            .attr('value', module.api_name)
                            .text(isProEnabled ? module.plural_label : module.plural_label + ' 🔒 Pro');
                        
                        if (!isProEnabled) {
                            option.prop('disabled', true).css('color', 'gray');
                        }
                        customGroup.append(option);
                    });
                    moduleSelect.append(customGroup);
                }

            } else {
                resetFields();
                jQuery(".iafwzc-setup-loading-text p").html("Please select an <b>account</b> to continue.");
                alert(response.data.error);
            }
        },
            error: function () {
                enableFields();
                resetFields();
                jQuery(".iafwzc-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 {
        iafwzc_handleFormChange();
        alert("Please choose a form name to proceed.");
    }
}

var zohoFields = [];
var cf7Fields = [];

function iafwzc_buildCf7Select() {
    const $select = jQuery('<select class="iafwzc-fm-setup-select cf7-select">');
    $select.append(jQuery('<option>').val('').text('Select'));
    const $formGroup = jQuery('<optgroup>').attr('label', 'Form Fields');
    cf7Fields.filter(f => f[3] !== 'custom').forEach(f => {
        $formGroup.append(jQuery('<option>').val(f[0]).text(f[1]).css('color', 'blue'));
    });
    $select.append($formGroup);
    const $sysGroup = jQuery('<optgroup>').attr('label', 'System Fields');
    cf7Fields.filter(f => f[3] === 'custom').forEach(f => {
        $sysGroup.append(jQuery('<option>').val(f[0]).text(f[1]).css('color', 'blue'));
    });
    $select.append($sysGroup);
    return $select;
}

function iafwzc_buildZohoSelect(extraAttrs) {
    const $select = jQuery('<select class="iafwzc-fm-setup-select zoho-select">');
    if (extraAttrs) {
        Object.entries(extraAttrs).forEach(([k, v]) => $select.attr(k, v));
    }
    $select.append(jQuery('<option>').val('').text('Select'));
    const groups = { 'General Fields': [], 'Custom Fields': [], 'Premium Fields': [] };
    zohoFields.forEach(f => { if (groups[f[4]]) groups[f[4]].push(f); });
    Object.entries(groups).forEach(([label, fields]) => {
        if (fields.length === 0) return;
        const $g = jQuery('<optgroup>').attr('label', label);
        fields.forEach(f => {
            $g.append(jQuery('<option>').val(f[0]).text(f[1] + ' (' + f[2] + ')').css('color', 'blue').attr('data-type', f[2]));
        });
        $select.append($g);
    });
    return $select;
}
function iafwzc_handleModuleChange() {
    const resetFields = () => {
        jQuery('input[name="crm_action"][value="add_ignore_existing"]').prop('checked', true);
        jQuery('#iafwzc-setup-updateActionName').val("");
        jQuery('#iafwzc-setup-updateActionName-area').hide();
        jQuery("#iafwzc-setup-fieldMapping-area").hide();
        jQuery('#iafwzc-setup-fieldMapping-table tbody').empty();
        jQuery('input[name="note_value"][value="0"]').prop('checked', true);
        jQuery("#iafwzc-setup-note").hide().val("");
    };

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

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

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

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

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

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

    jQuery.ajax({
        url: iafwzc_field_mapping.ajax_url,
        type: 'POST',
        data: {
            action: 'iafwzc_handle_request',
            account_id: accountId,
            form_value: formValue,
            module_api_name: moduleValue,
            action_key: "get_field",
            security: iafwzc_field_mapping.field_mapping_nonce
        },
        success: function (response) {
            enableFields();
            if (response.success) {
                jQuery(".iafwzc-setup-loading-text").hide();
                jQuery("#iafwzc-setup-fieldMapping-area").show();
                
               // Assuming response.data contains the JSON with field details
                const crm_fields = response.data.crm_fields.fields;
              
                zohoFields = crm_fields
                    .filter(field => !field.field_read_only) // Exclude fields with field_read_only: true
                    .filter(field => field.view_type?.edit) // Ensure the field supports editing
                    .map(field => [
                        field.api_name,
                        field.display_label,
                        field.data_type,
                        field.system_mandatory,
                        field.iafwzc_group,
                        field.iafwzc_session,
                        field.allowedValues   
                    ]);
                // Filter zohoFields to include only system mandatory fields
                    const mandatoryZohoFields = crm_fields
                    .filter(field => field.system_mandatory)
                    .map(field => [
                        field.api_name,
                        field.display_label,
                        field.data_type,
                        field.system_mandatory
                    ]);

                    // Load form fields
                    const form_fields = response.data.form_fields;
                    cf7Fields = form_fields.map(field => [
                    field.key,
                    field.label,
                    field.type,
                    field.source,
                    ]);
                    iafwzc_updateAvailableFields(form_fields);
                     //-------Render Filter Criteria
                     iafwzc_addList_to_filter();
                    // Loop through mandatoryZohoFields to create a row for each
                    mandatoryZohoFields.forEach(zohoField => {
                        const $cf7Td = jQuery('<td class="iafwzc-setup-td">').append(iafwzc_buildCf7Select());
                        const $zohoMandatorySelect = jQuery('<select class="iafwzc-fm-setup-select zoho-select">')
                            .attr({ title: 'Mandatory field', disabled: true })
                            .css('border-left', '3px solid #ff000094');
                        $zohoMandatorySelect.append(
                            jQuery('<option>').val(zohoField[0]).text(zohoField[1] + ' (' + zohoField[2] + ')').css('color', 'blue').attr('data-type', zohoField[2])
                        );
                        const $zohoTd = jQuery('<td class="iafwzc-setup-td">').attr('data-ref', 'mandatory').append($zohoMandatorySelect);
                        const $btnTd = jQuery('<td class="iafwzc-setup-td">').css({ border: 'none', background: 'none' })
                            .append(jQuery('<button type="button" class="add-row">').text('+').prop('disabled', true))
                            .append(jQuery('<button type="button">').text('−').prop('disabled', true).attr('title', 'Mandatory field, not able to remove'));
                        const $newRow = jQuery('<tr>').append($cf7Td).append($zohoTd).append($btnTd);

                    // Append the new row to the tbody
                    jQuery("#iafwzc-setup-fieldMapping-table tbody").append($newRow);
                     // Trigger the change event for the .zoho-select dropdown
                    jQuery("#iafwzc-setup-fieldMapping-table tbody tr:last-child .zoho-select").trigger("change");

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

function iafwzc_addRow(event) {
    const $btnTd = jQuery('<td class="iafwzc-setup-td">').css({ border: 'none', background: 'none' })
        .append(jQuery('<button type="button" class="add-row">').text('+'))
        .append(jQuery('<button type="button" class="remove-row">').text('−'));
    const $newRow = jQuery('<tr>')
        .append(jQuery('<td class="iafwzc-setup-td">').append(iafwzc_buildCf7Select()))
        .append(jQuery('<td class="iafwzc-setup-td">').append(iafwzc_buildZohoSelect()))
        .append($btnTd);

    // 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 Zoho field select
    iafwzc_updateZohoOptions();
}


function iafwzc_addRowWithoutEvent() {
    const $btnTd = jQuery('<td class="iafwzc-setup-td">').css({ border: 'none', background: 'none' })
        .append(jQuery('<button type="button" class="add-row">').text('+'))
        .append(jQuery('<button type="button" class="remove-row">').text('−'));
    const $newRow = jQuery('<tr>')
        .append(jQuery('<td class="iafwzc-setup-td">').append(iafwzc_buildCf7Select()))
        .append(jQuery('<td class="iafwzc-setup-td">').append(iafwzc_buildZohoSelect()))
        .append($btnTd);

    // Insert the new row as the last row if there are existing rows; otherwise, add it as the first row
    const tableBody = jQuery("#iafwzc-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 Zoho field select
    iafwzc_updateZohoOptions();
}




// Function to update Zoho field options based on selections
function iafwzc_updateZohoOptions() {
    let selectedZohoFields = [];

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

    // Disable selected Zoho fields in each dropdown
    jQuery(".zoho-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 = zohoFields.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 (
                    selectedZohoFields.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
                    });
                }
            }
        });
    });
    // Update primary key dropdown 
    let allowedDataTypes = ["text", "email", "phone", "number", "lookup", "picklist"];

    // Current selected value
    let currentSelectVal = jQuery("#iafwzc-setup-updateActionName").val();

    // Rebuild primary key dropdown using DOM methods
    const $pkSelect = jQuery("#iafwzc-setup-updateActionName");
    $pkSelect.empty();
    $pkSelect.append(jQuery('<option>').val('').text('Select'));
    zohoFields
        .filter(field => selectedZohoFields.includes(field[0]) && allowedDataTypes.includes(field[2].toLowerCase()))
        .forEach(field => {
            $pkSelect.append(jQuery('<option>').val(field[0]).text(field[1] + ' (' + field[2] + ')'));
        });

    // Retain the current selection if valid, otherwise reset
    if (selectedZohoFields.includes(currentSelectVal)) {
        jQuery("#iafwzc-setup-updateActionName").val(currentSelectVal);
    } else {
        jQuery("#iafwzc-setup-updateActionName").val("");
    }

}


// Attach event listener to dynamically handle selection changes and add row
jQuery(document).on("change", ".zoho-select", iafwzc_updateZohoOptions);
jQuery(document).on("click", ".add-row", iafwzc_addRow);


function iafwzc_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("#iafwzc-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(".zoho-select");
        
        // Check if formFieldSelect is "custom value" and requires an additional input
        let customInput = jQuery(this).find(".iafwzc-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() === "iafwzc_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("#iafwzc-setup-fieldMapping-table tbody tr").each(function() {
            let formFieldSelect = jQuery(this).find(".cf7-select");
            let crmFieldSelect = jQuery(this).find(".zoho-select");
            let customInput = jQuery(this).find(".iafwzc-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() === "iafwzc_custom_value" ? "custom field" : "form field";
            let fieldValue = formFieldSelect.val() === "iafwzc_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('#iafwzc-setup-formName').val();
        var accountName = jQuery('#iafwzc-setup-accountName').val();
        var moduleName = jQuery('#iafwzc-setup-moduleName').val();
        var actonName = jQuery('input[name="crm_action"]:checked').val();
        var integrationName = jQuery("#iafwzc-setup-integrationName").val();
        var primaryKey = jQuery("#iafwzc-setup-updateActionName").val();;
        var noteSts = jQuery('input[name="note_value"]:checked').val();
        var noteContent = jQuery("#iafwzc-setup-note").val();
        var filterCriteria = iafwzc_readFilterConditions();
        if(integrationName=="" || integrationName==null)
        {
            jQuery("#iafwzc-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("#iafwzc-setup-integrationName").css({
                "border": "", // Make the border red and visible
                "box-shadow": "" // Optional: Add a shadow to emphasize the element
            });
        }
        if(actonName!="add_ignore_existing" && (primaryKey=="" || primaryKey==null))
            {
                jQuery("#iafwzc-setup-updateActionName").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("#iafwzc-setup-updateActionName").css({
                    "border": "", // Make the border red and visible
                    "box-shadow": "" // Optional: Add a shadow to emphasize the element
                });
                
            }
        if(noteSts=="1" && (noteContent=="" || noteContent==null))
            {
                jQuery("#iafwzc-setup-note").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("#iafwzc-setup-note").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: iafwzc_field_mapping.ajax_url, // WordPress AJAX URL
            type: 'POST',
            data: {
                action: 'iafwzc_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,  
                record_action :  actonName,
                primary_key :  primaryKey,
                note_sts : noteSts,
                note_content : noteContent,
                filter_Criteria : filterCriteria,
                setup_id :  typeof setupID !== 'undefined' ? setupID : null,       // Corrected key name to match convention
                action_key : "save_mapping",
                security: iafwzc_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 iafwzc_toggleIntegrationStatus(integrationId, checkbox) {
    // Determine the new status based on the current checkbox state
    const isActive = checkbox.checked;

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

function iafwzc_setExistingMapping()
{
    const crm_fields = crmFieldList.fields;
    zohoFields = crm_fields
        .filter(field => !field.field_read_only) // Exclude fields with field_read_only: true
        .filter(field => field.view_type?.edit) // Ensure the field supports editing
        .map(field => [
            field.api_name,
            field.display_label,
            field.data_type,
            field.system_mandatory,
            field.iafwzc_group,
            field.iafwzc_session,
            field.allowedValues
        ]);
    // Filter zohoFields to include only system mandatory fields
        const mandatoryZohoFields = crm_fields
       
        .filter(field => field.system_mandatory)
        .map(field => [
            field.api_name,
            field.display_label,
            field.data_type,
            field.system_mandatory
        ]);
            // Load form fields
            cf7Fields = formFieldList.map(field => [
                field.key,
                field.label,
                field.type,
                field.source,
                ]);
                iafwzc_updateAvailableFields(formFieldList);
                 //-------Render Filter Criteria
                 iafwzc_addList_to_filter();
                 iafwzc_createFilterUI(filterCriteria);
                 // Loop through mandatoryZohoFields to create a row for each
            mandatoryZohoFields.forEach(zohoField => {
                const $cf7Td = jQuery('<td class="iafwzc-setup-td">').append(iafwzc_buildCf7Select());
                const $zohoMandatorySelect = jQuery('<select class="iafwzc-fm-setup-select zoho-select">')
                    .attr({ title: 'Mandatory field', disabled: true })
                    .css('border-left', '3px solid #ff000094');
                $zohoMandatorySelect.append(
                    jQuery('<option>').val(zohoField[0]).text(zohoField[1] + ' (' + zohoField[2] + ')').css('color', 'blue').attr('data-type', zohoField[2])
                );
                const $zohoTd = jQuery('<td class="iafwzc-setup-td">').attr('data-ref', 'mandatory').append($zohoMandatorySelect);
                const $btnTd = jQuery('<td class="iafwzc-setup-td">').css({ border: 'none', background: 'none' })
                    .append(jQuery('<button type="button" class="add-row">').text('+').prop('disabled', true))
                    .append(jQuery('<button type="button">').text('−').prop('disabled', true).attr('title', 'Mandatory field, not able to remove'));
                const $newRow = jQuery('<tr>').append($cf7Td).append($zohoTd).append($btnTd);

            // Append the new row to the tbody
            jQuery("#iafwzc-setup-fieldMapping-table tbody").append($newRow);
             jQuery("#iafwzc-setup-fieldMapping-table tbody tr:last-child .zoho-select").trigger("change");
            });
            // Enable the "add" button only for the last row
            jQuery("#iafwzc-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 = zohoFields.some(field => field[0] === crmFields && field[3]);
                
                if (isMandatory) {
                    jQuery('.iafwzc-fm-setup-select.zoho-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('.iafwzc-fm-setup-select.cf7-select');
                            
                            if (fieldType === 'custom field') {
                                // Set the previous select element's value to "custom value"
                                previousSelect.val("iafwzc_custom_value");
                                
                                let customInputContainer = previousSelect.find('.iafwzc-setup-fm-custom-input');
                                if (customInputContainer.length === 0) {
                                    customInputContainer = jQuery('<div style="position: relative;"><input type="text" class="iafwzc-setup-fm-custom-input" placeholder="Enter text or choose from options"> <div class="iafwzc-setup-fm-dropdownSuggestions"></div> </div>');
                                    previousSelect.after(customInputContainer); // Add it within the last row
                                }
                                
                                // Set the value of the custom input container
                                customInputContainer.find('.iafwzc-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
                     iafwzc_addRowWithoutEvent(); // Assuming addRowWithoutEvent() creates a new row

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

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

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

                    // Retrieve specific details from the last row
                    zohoFieldElement.val(crmFields);

                    if (fieldType === 'custom field') {
                        // Set the CF7 select element's value to "custom value"
                        cf7FieldElement.val("iafwzc_custom_value");
                        
                        // Append a custom input container within the same row if it doesn't exist
                        let customInputContainer = lastRow.find('.iafwzc-setup-fm-custom-input');
                        if (customInputContainer.length === 0) {
                            customInputContainer = jQuery('<div style="position: relative;"><input type="text" class="iafwzc-setup-fm-custom-input" placeholder="Enter text or choose from options"> <div class="iafwzc-setup-fm-dropdownSuggestions"></div> </div>');
                            cf7FieldElement.after(customInputContainer); // Add it within the last row
                        }
                        
                        // Set the value of the custom input container
                        customInputContainer.find('.iafwzc-setup-fm-custom-input').val(fieldValue || '');  // Set 
                    }  
                    else {
                        // Set the Zoho 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
                    iafwzc_addRowWithoutEvent();
            
                    // Get the table body
                    const tableBody = jQuery("#iafwzc-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('.zoho-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
                });
            }
            iafwzc_updateZohoOptions();
            jQuery("input[name='crm_action'][value='"+record_action+"']").prop("checked", true);

            if(record_action!="add_ignore_existing")
            {
                jQuery("#iafwzc-setup-updateActionName").val(primary_key_name);
                jQuery("#iafwzc-setup-updateActionName-area").show()
               
            }
            else
            {
                jQuery("#iafwzc-setup-updateActionName-area").hide()
            }
            jQuery("input[name='note_value'][value='"+noteSts+"']").prop("checked", true);
            if(noteSts!="0")
                {
                    jQuery("#iafwzc-setup-note").val(noteContent);
                    jQuery("#iafwzc-setup-note").show();
                }
                else
                {
                    jQuery("#iafwzc-setup-note").hide();
                }

}


//-----------------------
jQuery(document).on("change", ".zoho-select", function () {
    var selectedValue = jQuery(this).val().trim(); // Get selected value
    var $numberList = jQuery('<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 zohoFields to find matching values
    zohoFields.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;
                        var $item = jQuery('<div class="copy-item">').attr('data-text', item.value).text(item.value).append(' <span class="copy-icon">📋</span>');
                        $numberList.append($item);
                    });
                }
            }
        }
    });

    if(optionStatus)
    {
    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(".zoho-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)
    iafwzc_updateZohoOptions();
});