(function($) {

    $(document).ready(function() {
        let myModal = '#na';
        let myForm = '#na';
        let mySubmit = '#na';

        // Open the modal
        $('.dicapModalButton').click(function() {
            // Get the data-id attribute value
            let myIDValue = Number.isInteger(parseInt($(this).data('id'), 10)) ? parseInt($(this).data('id'), 10) : 1;
            let myAttLabel = /^[a-zA-Z0-9_]+$/.test($(this).data('att')) ? $(this).data('att') : 'invalid';
            let myFormName = /^[a-zA-Z0-9_]+$/.test($(this).data('frm')) ? $(this).data('frm') : 'invalid';
            let myFormAction = /^[a-zA-Z0-9_]+$/.test($(this).data('act')) ? $(this).data('act') : 'invalid';
            var formattedString;
            //console.log('ID', myIDValue);
            myModal = '#' + myFormName;
            myForm = $(myModal).find('form');
            //mySubmit = myModal + '_submit';
            let myActionSet = myFormAction + '_frm_set';
            let myActionGet = myFormAction + '_frm_get';

            // Fetch transient data via AJAX
            $.ajax({
                url: varzd.ajax_url,
                type: 'POST',
                data: {
                    id: myIDValue,
                    att: myAttLabel,
                    action: myActionGet,
                    nonce: varzd.nonce,
                },
                success: function(response) {
                    // console.log('GET_RESPONSE', response);
                    if (response.success) {
                        //Clear all the form fields
                        $(myModal).find('form')[0].reset();
                        // Populate form fields with all values in response.data
                        $.each(response.data, function(key, value) {
                            if (key !== 'myID' && key !== 'myAct') {
                                if (Array.isArray(value)) {
                                    formattedString = value.join('\n');
                                } else {
                                    // Handle the case where arr is a single value
                                    formattedString = String(value); // Convert to string
                                }
                                let $input = $(myModal + ' [name="' + key + '"]');
                                $input.val(''); //clear the field to start
                                // Check if the element exists
                                if ($input.length !== 0) {
                                    let tagName = $input.prop('tagName').toLowerCase();
                                    if (tagName === 'input' && $input.attr('type') === 'text') {
                                        $input.val(formattedString.replace(/\n/g, ', ')); // Optionally replace newlines with commas for input
                                    } else if (tagName === 'textarea') {
                                        $input.val(formattedString);
                                    } else if (tagName === 'select') {
                                        // Set the value of the select element to the formattedString
                                        $input.val(formattedString);
                                        // Check if the value was set correctly
                                        if ($input.val() !== formattedString) {
                                            console.warn('Value not found in select options.');
                                        }
                                    } else {
                                        console.warn('Unsupported element type.');
                                    }
                                }
                                //myForm.find('input[name="' + key + '"]').val(value);
                            }
                        });
                    } else {
                        myForm.find('input, select, textarea').val('');
                    }
                    // Set the value of the hidden input field
                    $(myForm).find('input[name=myID]').remove(); // Remove any existing input field with the same name
                    $(myForm).append('<input type="hidden" name="myID" value="' + myIDValue + '">');
                    $(myForm).find('input[name=myAtt]').remove(); // Remove any existing input field with the same name
                    $(myForm).append('<input type="hidden" name="myAtt" value="' + myAttLabel + '">');
                    $(myForm).find('input[name=myAct]').remove(); // Remove any existing input field with the same name
                    $(myForm).append('<input type="hidden" name="myAct" value="' + myActionSet + '">');
                    // Show the modal
                    $(myModal).addClass('show').css('display', 'block').attr('aria-hidden', 'false');
                },
                error:  function(xhr, status, error) {
                    // alert('An error occurred while fetching transient data: ' + error);
                    // Set the value of the hidden input field
                    $(myForm).find('input[name=myID]').remove(); // Remove any existing input field with the same name
                    $(myForm).append('<input type="hidden" name="myID" value="' + myIDValue + '">');
                    $(myForm).find('input[name=myAtt]').remove(); // Remove any existing input field with the same name
                    $(myForm).append('<input type="hidden" name="myAtt" value="' + myAttLabel + '">');
                    $(myForm).find('input[name=myAct]').remove(); // Remove any existing input field with the same name
                    $(myForm).append('<input type="hidden" name="myAct" value="' + myActionSet + '">');
                    // Show the modal
                    $(myModal).addClass('show').css('display', 'block').attr('aria-hidden', 'false');
                }
            });
        });

        // Close the modal when the close button is clicked
        $('.close, .btn-secondary').click(function() {
            $(myModal).removeClass('show').css('display', 'none').attr('aria-hidden', 'true');
        });

        // Close the modal when clicking outside the modal content
        $(window).click(function(event) {
            if ($(event.target).is(myModal)) {
                $(myModal).removeClass('show').css('display', 'none').attr('aria-hidden', 'true');
            }
        });

        // Serialize form data to an object
        function serializeFormToObject(form) {
            var formArray = $(form).serializeArray();
            var formObject = {};
            $.map(formArray, function(n, i) {
                formObject[n['name']] = n['value'];
            });
            return formObject;
        }

        // Handle form submission
        $('.mySubmit').click(function() {
            let formData = serializeFormToObject($(myForm));
            // console.log('FORM', formData);
            let myActionSet = formData.myAct;
            //alert("Check: " + formData.myAct);
            //alert("You clicked me you swine!! " + formData.firstName);
            $(myModal).removeClass('show').css('display', 'none').attr('aria-hidden', 'true');
            $.ajax({
                url: varzd.ajax_url,
                type: 'POST',
                data: {
                    action: myActionSet,
                    nonce: varzd.nonce,
                    formData: formData,
                },
                dataType: 'json',
                success: function(response) {
                    // console.log('SET_RESPONSE', response);
                    let data = response.data;
                    let myID = formData['myID'];
                    let myActTag = '#' + formData['myAct'];
                    let outcome = 'Processing'
                    // console.log('DATA', formData);
                    if (response.success) {
                        // alert('Success: ' + JSON.stringify(data));
                        outcome = 'SUCCESS: Information updated';
                    } else {
                        outcome = 'ERROR: Information not updated';
                    }
                    if ($("#dcp_"+myID).length) {
                        $("#dcp_"+myID).html(outcome).fadeIn(300).fadeOut(9000);
                    }
                    if ($(myActTag).length) {
                        $(myActTag).html(outcome).fadeIn(300).fadeOut(9000);
                    }
                    $(myModal).removeClass('show').css('display', 'none').attr('aria-hidden', 'true');
                },
                error: function(xhr, status, error) {
                    alert('An error occurred: ' + error);
                }
            });
        });

    });

})(jQuery);