
jQuery(document).ready(function($) {
    
    $(document).on("click", ".remove-row", function() {
        $(this).closest("tr").remove();
        updatefwOptions();
    });
    jQuery(".integrazo_fwcrm_form-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 showIntegrationForm()
{
    jQuery("#integrazo_fwcrm_form-setup-popupOverlay").toggleClass("show");
    
}
function integrazo_fwcrm_form_handleFormChange() {
    // Function to reset fields
    const resetFields = () => {
        jQuery("#integrazo_fwcrm_form-setup-fieldMapping-area").hide(); // Hide field mapping area
        jQuery('#integrazo_fwcrm_form-setup-fieldMapping-table tbody').empty(); // Clear table content
        jQuery('input[name="crm_action"][value="add_ignore_existing"]').prop('checked', true); // Reset radio buttons
        jQuery('#integrazo_fwcrm_form-setup-accountName').val(""); // Reset account name
        jQuery('#integrazo_fwcrm_form-setup-moduleName').val(""); // Reset module name
    };

    // Reset fields initially
    resetFields();
    jQuery(".integrazo_fwcrm_form-setup-loading-text").show();

    // Get the value of the selected form
    const formValue = jQuery('#integrazo_fwcrm_form-setup-formName').val();

    // Check if a form is selected
    if (!formValue) {
        jQuery(".integrazo_fwcrm_form-setup-loading-text p").html(
            "Please select a <b>form</b> to continue."
        );
        return;
    }

    // Update the loading text for the next step
    jQuery(".integrazo_fwcrm_form-setup-loading-text p").html(
        "Please select an <b>account</b> to continue."
    );

    // Additional logic for form selection can go here
}

function integrazo_fwcrm_form_handleAccountChange() {
    // Function to reset fields
    const resetFields = () => {
        jQuery("#integrazo_fwcrm_form-setup-fieldMapping-area").hide(); // Hide field mapping area
        jQuery('#integrazo_fwcrm_form-setup-fieldMapping-table tbody').empty(); // Clear table content
        jQuery('input[name="crm_action"][value="add_ignore_existing"]').prop('checked', true); // Reset radio buttons
        jQuery('#integrazo_fwcrm_form-setup-moduleName').val(""); // Reset module name
    };

    // Reset fields initially
    resetFields();
    jQuery(".integrazo_fwcrm_form-setup-loading-text").show();

    // Check if a form is selected
    const formValue = jQuery('#integrazo_fwcrm_form-setup-formName').val();
    if (!formValue) {
        alert("Select a form to proceed.");
        integrazo_fwcrm_form_handleFormChange();
        return;
    }

    // Get the value of the selected account
    const accountId = jQuery('#integrazo_fwcrm_form-setup-accountName').val();

    // Check if an account is selected
    if (!accountId) {
        jQuery(".integrazo_fwcrm_form-setup-loading-text p").html(
            "Please select an <b>account</b> to continue."
        );
        return;
    }

    // Update the loading text for the next step
    jQuery(".integrazo_fwcrm_form-setup-loading-text p").html(
        "Please select a <b>module</b> to continue."
    );

    // Additional logic for account and module selection can go here
}

var fwFields = [];
var allFormFields = [];
function integrazo_fwcrm_form_handleModuleChange() {
  
    const resetFields = () => {
        jQuery("#integrazo_fwcrm_form-setup-fieldMapping-area").hide();
        jQuery('#integrazo_fwcrm_form-setup-fieldMapping-table tbody').empty();
        jQuery('input[name="crm_action"][value="add_ignore_existing"]').prop('checked', true);
    };

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

    const disableFields = () => {
        jQuery('#integrazo_fwcrm_form-setup-formName').prop('disabled', true);
        jQuery('#integrazo_fwcrm_form-setup-accountName').prop('disabled', true);
        jQuery('#integrazo_fwcrm_form-setup-moduleName').prop('disabled', true);
    };
    const formValue = jQuery('#integrazo_fwcrm_form-setup-formName').val();
    const accountId = jQuery('#integrazo_fwcrm_form-setup-accountName').val();
    const moduleValue = jQuery('#integrazo_fwcrm_form-setup-moduleName').val();

    if (!formValue || !accountId) {
        jQuery('#integrazo_fwcrm_form-setup-moduleName').val("");
        alert("Please select a form and account to proceed.");
        jQuery(".integrazo_fwcrm_form-setup-loading-text p").html(
            "Please select a <b>form</b>, <b>account</b>, and <b>module</b> to proceed to the next step."
        );
        enableFields(); // Ensure this function enables necessary fields
        resetFields();  // Ensure this function resets fields properly
        return;
    }
    if (!moduleValue) {
        jQuery(".integrazo_fwcrm_form-setup-loading-text p").html(
            "Please select a <b>module</b> to proceed to the next step."
        );
        enableFields(); // Ensure this function enables necessary fields
        resetFields();  // Ensure this function resets fields properly
        return;
    }

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


    jQuery.ajax({
        url: integrazo_fwcrm_form_field_mapping.ajax_url,
        type: 'POST',
        data: {
            action: 'integrazo_fwcrm_form_handle_request',
            account_id: accountId,
            form_value: formValue,
            module_api_name: moduleValue,
            action_key: "get_field",
            security: integrazo_fwcrm_form_field_mapping.field_mapping_nonce
        },
        success: function (response) {
            enableFields();
            if (response.success) {
                jQuery(".integrazo_fwcrm_form-setup-loading-text").hide();
                jQuery("#integrazo_fwcrm_form-setup-fieldMapping-area").show();
                
               // Assuming response.data contains the JSON with field details
                const crm_fields = response.data.crm_fields.fields;
                fwFields = crm_fields
                    .map(field => [
                        field.name,
                        field.label,
                        field.type,
                        field.system_mandatory,
                        field.integrazo_fwcrm_form_group,
                        field.integrazo_fwcrm_form_session,
                        field.choices
                    ]);
                  
                // Filter fwFields to include only system mandatory fields
                    const mandatoryfwFields = crm_fields
                    .filter(field => field.system_mandatory)
                    .map(field => [
                        field.name,
                        field.label,
                        field.type,
                        field.system_mandatory
                    ]);

                    // Load form fields
                    const form_fields = response.data.form_fields;
                    allFormFields = form_fields.map(field => [
                    field.key,
                    field.label,
                    field.type,
                    field.source,
                    ]);
                    // Loop through mandatoryfwFields to create a row for each
                    mandatoryfwFields.forEach(fwField => {
                        let newRow = `
                        <tr>
                            <td class='integrazo_fwcrm_form-setup-td'>
                               <select class="integrazo_fwcrm_form-fm-setup-select cf7-select">
                                <option value="">Select</option>
                                <optgroup label="Form Fields">
                                    ${allFormFields
                                        .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">
                                    ${allFormFields
                                        .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='integrazo_fwcrm_form-setup-td' data-ref='mandatory'>
                                <select class="integrazo_fwcrm_form-fm-setup-select fw-select" style="border-left: 3px solid #ff000094  !important;" disabled>
                                  <option value="${fwField[0]}" data-type="${fwField[2]}" style="color: blue;">
                                    ${fwField[1]} (${fwField[2]})
                                </option>
                                </select>
                            </td>
                            <td class='integrazo_fwcrm_form-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("#integrazo_fwcrm_form-setup-fieldMapping-table tbody").append(newRow);
                    });
                    // Enable the "add" button only for the last row
                    jQuery("#integrazo_fwcrm_form-setup-fieldMapping-table tbody tr:last-child .add-row").prop("disabled", false);
                    updatefwOptions();
            } else {
                jQuery('#integrazo_fwcrm_form-setup-moduleName').val("");
                enableFields();
                resetFields();
                jQuery(".integrazo_fwcrm_form-setup-loading-text p").html(
                   "Please select a <b>module</b> to proceed to the next step."
                );
                 alert(response.data.error);
            }
        },
        error: function () {
            jQuery('#integrazo_fwcrm_form-setup-moduleName').val("");
            enableFields();
            resetFields();
            jQuery(".integrazo_fwcrm_form-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 addRow(event) {
    // Ensure allFormFields and fwFields are defined before mapping

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

    let formFields = allFormFields
        .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 fwFields into groups
    // Categorize fwFields into groups
    let groupedfwFields = {
        "General Fields": fwFields.filter(field => field[4] === "General Fields"),
        "Custom Fields": fwFields.filter(field => field[4] === "Custom Fields"),
        "Premium Fields": fwFields.filter(field => field[4] === "Premium Fields")
    };
    // Generate options for fw fields with proper <optgroup> tags
    let fwOptions = '<option value="">Select</option>';
    for (let group in groupedfwFields) {
        if (groupedfwFields[group].length > 0) { // Check if the group is not empty
            let options = groupedfwFields[group]
                .map(field => `<option value="${field[0]}" data-type="${field[2]}" style="color: blue;">
                    ${field[1]} (${field[2]})
                </option>`).join('');
            fwOptions += `<optgroup label="${group}">${options}</optgroup>`;
        }
    }

    // Define the new row HTML with the options included
    let newRow = `
        <tr>
            <td class="integrazo_fwcrm_form-setup-td">
                <select class="integrazo_fwcrm_form-fm-setup-select cf7-select">
                    ${cf7Options}
                </select>
            </td>
            <td class="integrazo_fwcrm_form-setup-td">
                <select class="integrazo_fwcrm_form-fm-setup-select fw-select">
                    ${fwOptions}
                    
                </select>
            </td>
            <td class="integrazo_fwcrm_form-setup-td" style="border: none; background: none;">
                <button type="button" class="add-row">+</button>
                <button type="button" class="remove-row" title="Mandatory field, not able to remove">−</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 fw field select
    updatefwOptions();
}


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

    let formFields = allFormFields
        .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 fwFields into groups
    let groupedfwFields = {
        "General Fields": fwFields.filter(field => field[4] === "General Fields"),
        "Custom Fields": fwFields.filter(field => field[4] === "Custom Fields"),
        "Premium Fields": fwFields.filter(field => field[4] === "Premium Fields")
    };

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

    // Define the new row HTML with the options included
    let newRow = `
        <tr>
            <td class="integrazo_fwcrm_form-setup-td">
                <select class="integrazo_fwcrm_form-fm-setup-select cf7-select">
                    ${cf7Options}
                </select>
            </td>
            <td class="integrazo_fwcrm_form-setup-td">
                <select class="integrazo_fwcrm_form-fm-setup-select fw-select">
                    ${fwOptions}
                   
                </select>
            </td>
            <td class="integrazo_fwcrm_form-setup-td" style="border: none; background: none;">
                <button type="button" class="add-row">+</button>
                <button type="button" class="remove-row" title="Mandatory field, not able to remove">−</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("#integrazo_fwcrm_form-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 fw field select
    updatefwOptions();
}




// Function to update fw field options based on selections
function updatefwOptions() {
    let selectedfwFields = [];

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

    // Disable selected fw fields in each dropdown
jQuery(".fw-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 = fwFields.find(field => field[0] === optionValue); // Find the matching fwField entry

        if (matchingField) { // If a matching field is found
            if (
                !matchingField[5] // Check if the 5th index value is false
            ) {
                // 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 (
                selectedfwFields.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
                });
            }
        }
    });
});
}


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

// Function to dynamically handle showing input field for custom values
jQuery(document).on("change", ".cf7-select", function() {
    let selectedValue = jQuery(this).val();
    // Check if the selected value is "custom" (replace 'custom' with the actual custom value)
    if (selectedValue === "integrazo_fwcrm_form_custom_value") {
        // Add a text input right after the select element
        jQuery(this).after('<input type="text" class="integrazo_fwcrm_form-setup-fm-custom-input" placeholder="Enter custom value">');
    } else {
        // Remove the custom input field if it exists
        jQuery(this).siblings(".integrazo_fwcrm_form-setup-fm-custom-input").remove();
    }
});

function integrazo_fwcrm_form_handleButtonClick(button) {

   
    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("#integrazo_fwcrm_form-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(".fw-select");
        
        // Check if formFieldSelect is "custom value" and requires an additional input
        let customInput = jQuery(this).find(".integrazo_fwcrm_form-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() === "integrazo_fwcrm_form_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("#integrazo_fwcrm_form-setup-fieldMapping-table tbody tr").each(function() {
            let formFieldSelect = jQuery(this).find(".cf7-select");
            let crmFieldSelect = jQuery(this).find(".fw-select");
            let customInput = jQuery(this).find(".integrazo_fwcrm_form-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() === "integrazo_fwcrm_form_custom_value" ? "custom field" : "form field";
            let fieldValue = formFieldSelect.val() === "integrazo_fwcrm_form_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('#integrazo_fwcrm_form-setup-formName').val();
        var accountName = jQuery('#integrazo_fwcrm_form-setup-accountName').val();
        var moduleName = jQuery('#integrazo_fwcrm_form-setup-moduleName').val();
        var actonName = jQuery('input[name="crm_action"]:checked').val();
        var integrationName = jQuery("#integrazo_fwcrm_form-setup-integrationName").val();
        if(integrationName=="" || integrationName==null)
        {
            jQuery("#integrazo_fwcrm_form-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.");
            return;
        }
        if(formName=="" || formName==null)
            {
                jQuery("#integrazo_fwcrm_form-setup-formName").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.");
                return;
            }
        else
        {
            jQuery("#integrazo_fwcrm_form-setup-formName").css({
                "border": "", // Make the border red and visible
                "box-shadow": "" // Optional: Add a shadow to emphasize the element
            });
        }
        if(accountName=="" || accountName==null)
            {
                jQuery("#integrazo_fwcrm_form-setup-accountName").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.");
                return;
            }
        else
        {
            jQuery("#integrazo_fwcrm_form-setup-accountName").css({
                "border": "", // Make the border red and visible
                "box-shadow": "" // Optional: Add a shadow to emphasize the element
            });
        }
            button.textContent = "Please Wait...";
        //
        jQuery.ajax({
            url: integrazo_fwcrm_form_field_mapping.ajax_url, // WordPress AJAX URL
            type: 'POST',
            data: {
                action: 'integrazo_fwcrm_form_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,
                setup_id :  typeof setupID !== 'undefined' ? setupID : null,       // Corrected key name to match convention
                action_key : "save_mapping",
                security: integrazo_fwcrm_form_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 toggleIntegrationStatus(integrationId, checkbox) {
    // Determine the new status based on the current checkbox state
    const isActive = checkbox.checked;

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

function setExistingMapping()
{
    
    const crm_fields = crmFieldList.fields;
    fwFields = crm_fields
        .map(field => [
            field.name,
            field.label,
            field.type,
            field.system_mandatory,
            field.integrazo_fwcrm_form_group,
            field.integrazo_fwcrm_form_session,
            field.choices
        ]);
    // Filter fwFields to include only system mandatory fields
        const mandatoryfwFields = crm_fields
       
        .filter(field => field.system_mandatory)
        .map(field => [
            field.name,
            field.label,
            field.type,
            field.system_mandatory
        ]);
            // Load form fields
            allFormFields = formFieldList.map(field => [
                field.key,
                field.label,
                field.type,
                field.source,
                ]);
                 // Loop through mandatoryfwFields to create a row for each
            mandatoryfwFields.forEach(fwField => {
                let newRow = `
                <tr>
                    <td class='integrazo_fwcrm_form-setup-td'>
                       <select class="integrazo_fwcrm_form-fm-setup-select cf7-select">
                                <option value="">Select</option>
                                <optgroup label="Form Fields">
                                    ${allFormFields
                                        .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">
                                    ${allFormFields
                                        .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='integrazo_fwcrm_form-setup-td' data-ref='mandatory'>
                        <select class="integrazo_fwcrm_form-fm-setup-select fw-select" style="border-left: 3px solid #ff000094  !important;" disabled>
                          <option value="${fwField[0]}" data-type="${fwField[2]}" style="color: blue;">
                            ${fwField[1]} (${fwField[2]})
                        </option>
                        </select>
                    </td>
                    <td class='integrazo_fwcrm_form-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("#integrazo_fwcrm_form-setup-fieldMapping-table tbody").append(newRow);
            });
            // Enable the "add" button only for the last row
            jQuery("#integrazo_fwcrm_form-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 = fwFields.some(field => field[0] === crmFields && field[3]);
                
                if (isMandatory) {
                    jQuery('.integrazo_fwcrm_form-fm-setup-select.fw-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('.integrazo_fwcrm_form-fm-setup-select.cf7-select');
                            
                            if (fieldType === 'custom field') {
                                // Set the previous select element's value to "custom value"
                                previousSelect.val("integrazo_fwcrm_form_custom_value");
                                
                                let customInputContainer = previousSelect.find('.integrazo_fwcrm_form-setup-fm-custom-input');
                                if (customInputContainer.length === 0) {
                                    customInputContainer = jQuery('<input type="text" class="integrazo_fwcrm_form-setup-fm-custom-input" placeholder="Enter custom value">');
                                    previousSelect.after(customInputContainer); // Add it within the last row
                                }
                                
                                // Set the value of the custom input container
                                customInputContainer.val(fieldValue || ''); // Set the input value

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

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

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

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

                    // Retrieve specific details from the last row
                    fwFieldElement.val(crmFields);
                    fwFieldElement.val(crmFields).trigger("change");
                    if (fieldType === 'custom field') {
                        // Set the CF7 select element's value to "custom value"
                        cf7FieldElement.val("integrazo_fwcrm_form_custom_value");
                        
                        // Append a custom input container within the same row if it doesn't exist
                        let customInputContainer = lastRow.find('.integrazo_fwcrm_form-setup-fm-custom-input');
                        if (customInputContainer.length === 0) {
                            customInputContainer = jQuery('<input type="text" class="integrazo_fwcrm_form-setup-fm-custom-input" placeholder="Enter custom value">');
                            cf7FieldElement.after(customInputContainer); // Add it within the last row
                        }
                        
                        // Set the value of the custom input container
                        customInputContainer.val(fieldValue || ''); // Set the input value
                    }  
                    else {
                        // Set the fw 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
                    addRowWithoutEvent();
            
                    // Get the table body
                    const tableBody = jQuery("#integrazo_fwcrm_form-setup-fieldMapping-table tbody");
            
                    // Select the last row in the table body
                    const lastRow = tableBody.find('tr').last();
            
                    // Select the CF7 and fw field elements in the last row
                    const cf7FieldElement = lastRow.find('.cf7-select'); // Select element for CF7 fields
                    const fwFieldElement = lastRow.find('.fw-select'); // Select element for fw fields
            
                    // Set the values for the last row
                    fwFieldElement.val("attachment"); // Set the fw field to "attachment"
                    cf7FieldElement.val(value); // Set the CF7 field to the current value in the array
                });
            }
            updatefwOptions();
            
            jQuery("input[name='crm_action'][value='"+record_action+"']").prop("checked", true);


}
