jQuery(document).ready(function () {
    
/**
 * verify the auth manual api code
 * @since 1.0
 */
jQuery(document).on('click', '#save-gscfrmdform-manual', function (event) {
    event.preventDefault();
     jQuery('#error_spread').html('');
    var clientId = jQuery('#gscfrmdform-client-id').val();
    var secretId = jQuery('#gscfrmdform-secret-id').val();

    if(clientId !="" && secretId !=""){
    jQuery(".loading-sign-gscfrmdform").addClass("loading");
    var data = {
        action: 'save_client_id_sec_id_gapi_gscfrmdform',
        client_id: jQuery('#gscfrmdform-client-id').val(),
        secret_id: jQuery('#gscfrmdform-secret-id').val(),
        gs_frmgsc_client_token: jQuery('#gscfrmdform-client-token').val(),
        security: jQuery('#gs-ajax-nonce').val()
    };
    jQuery.post(ajaxurl, data, function (response) {
        if (!response.success) {
            jQuery(".loading-sign-gscfrmdform").removeClass("loading");
            jQuery("#gscfrmdform-validation-message").empty();
            jQuery("<span class='error-message'>Access code Can't be blank.</span>").appendTo('#gscfrmdform-validation-message');
        } else {
            jQuery(".loading-sign").removeClass("loading");
            jQuery("#gscfrmdform-validation-message").empty();
            jQuery("<span class='frmgsc-valid-message'>Your Google Access Code is Authorized and Saved.</span> ").appendTo('#gscfrmdform-validation-message');

            setTimeout(function () {
                window.location.href = jQuery("#redirect_auth_gscfrmdform").val();
            }, 1000);
           
        }
    });
}
else{
  jQuery('#error_spread').html('Please Enter Client ID and Client Secret Value.');
}
});

    /**
    * verify the api code
    * @since 1.0
    */
    jQuery(document).on('click', '#save-frmdform-gs-code', function (event) {
        event.preventDefault();
        jQuery( ".loading-sign-gscfrmdform" ).addClass( "loading" );
        var data = {
        action: 'verify_frmdforms_gs_integation',
        code: jQuery('#ffforms-setting-google-access-code').val(),
        security: jQuery('#gs-ajax-nonce').val()
      };
      jQuery.post(ajaxurl, data, function (response ) {
         if (!response.success) {
            jQuery(".loading-sign-gscfrmdform").removeClass("loading");
            jQuery("#gscfrmdform-validation-message").empty();
            jQuery("<span class='error-message'>Access code Can't be blank.</span>").appendTo('#gscfrmdform-validation-message');
        } else {
            jQuery(".loading-sign-gscfrmdform").removeClass("loading");
            jQuery("#gscfrmdform-validation-message").empty();
            jQuery("<span class='frmgsc-valid-message'>Your Google Access Code is Authorized and Saved.</span> ").appendTo('#gscfrmdform-validation-message');

            setTimeout(function () {
                window.location.href = jQuery("#redirect_auth_gscfrmdform").val();
            }, 1000);
          }
      });
      
    }); 

/**
 * verify the deactivate manual api code
 * @since 1.0
 */
jQuery(document).on('click', '#gscfrmdform-deactivate-auth', function (event) {
    event.preventDefault();
    jQuery(".loading-sign-gscfrmdform").addClass("loading");
     var txt;
     var r = confirm("Are you sure you want to deactivate Google Sheet Integration ?");
     if (r == true) {
    var data = {
        action: 'deactivate_auth_token_gapi_manual_gscfrmdform',
        security: jQuery('#gs-ajax-nonce').val()
    };
    jQuery.post(ajaxurl, data, function (response) {
        if ( response == -1 ) {
                    return false; // Invalid nonce
        }
        if (!response.success) {
            jQuery(".loading-sign-gscfrmdform").removeClass("loading");
            jQuery("#deactivate-message").empty();
            
            } else {
            jQuery(".loading-sign-gscfrmdform").removeClass("loading");
            jQuery("#deactivate-message").empty();
            jQuery("<span class='frmgsc-valid-message'>Your account is removed. Reauthenticate again to integrate Contact Form with Google Sheet.</span>").appendTo('#deactivate-message');
            setTimeout(function () {
                location.reload();
            }, 1000);
        }
    });
  }else {
            jQuery( ".loading-sign-gscfrmdform" ).removeClass( "loading" );
        }

});

    /**
    * deactivate the api code
    * @since 1.0
    */
    jQuery(document).on('click', '#wp-deactivate-log', function (event) {
       event.preventDefault();
        jQuery(".loading-sign-gscfrmdform-deactive").addClass( "loading" );
        var txt;
        var r = confirm("Are you sure you want to deactivate Google Sheet Integration ?");
        if (r == true) {
            var data = {
                action: 'deactivate_wp_integation',
                security: jQuery('#gs-ajax-nonce').val()
            };
            jQuery.post(ajaxurl, data, function (response ) {
                if ( response == -1 ) {
                    return false; // Invalid nonce
                }
             
                if (!response.success) {
                    jQuery(".loading-sign-gscfrmdform-deactive").removeClass("loading");
                    jQuery("#deactivate-message").empty();
                    
                    } else {
                    jQuery(".loading-sign-gscfrmdform-deactive").removeClass("loading");
                    jQuery("#deactivate-message").empty();
                    jQuery("<span class='frmgsc-valid-message'>Your account is removed. Reauthenticate again to integrate Contact Form with Google Sheet.</span>").appendTo('#deactivate-message');
                    setTimeout(function () {
                        location.reload();
                    }, 1000);
                }
            });
        } else {
          
            jQuery( ".loading-sign-gscfrmdform-deactive" ).removeClass( "loading" );
        }
    });
   
    /**
     * reset form
     @since 1.0
     */
    jQuery(document).on('click', '#save-gscfrmdform-reset', function (event) {
        jQuery("#gscfrmdform-client-id").val('');
        jQuery("#gscfrmdform-secret-id").val('');
        jQuery("#gscfrmdform-client-token").val('');
        jQuery("#gscfrmdform-client-id").removeAttr('disabled');
        jQuery("#gscfrmdform-secret-id").removeAttr('disabled');
        jQuery("#save-gscfrmdform-manual").removeAttr('disabled');

    });

    /* drop down event for Google API */
       
       /* drop down event for Google API */


	function html_decode(input) {
      var doc = new DOMParser().parseFromString(input, "text/html");
      return doc.documentElement.textContent;
   }

  /**
    * Clear debug for system status tab
    */
   jQuery(document).on('click', '.clear-content-logs-frm', function () {

      jQuery(".clear-loading-sign-logs-frm").addClass("loading");
      var data = {
         action: 'gscfrmdform_clear_debug_logs',
         security: jQuery('#gs-ajax-nonce').val()
      };
      jQuery.post(ajaxurl, data, function ( response ) {
         if (response == -1) {
            return false; // Invalid nonce
         }
         
         if (response.success) {
            jQuery(".clear-loading-sign-logs-frm").removeClass("loading");
            jQuery('.clear-content-logs-msg-frm').html('Logs are cleared.');
            setTimeout(function () {
                        location.reload();
                    }, 1000);
         }
      });
   });

   /**
     * Display Error logs
     */
    jQuery(document).ready(function($) {
       // Hide .frm-system-Error-logs initially
       $('.frm-system-Error-logs').hide();

       // Add a variable to track the state
       var isOpen = false;

       // Function to toggle visibility and button text
       function toggleLogs() {
           $('.frm-system-Error-logs').toggle();
           // Change button text based on visibility
           $('.fmdgsc-logs').text(isOpen ? 'View' : 'Close');
           isOpen = !isOpen; // Toggle the state
       }

       // Toggle visibility and button text when clicking .fmdgsc-logs button
       $('.fmdgsc-logs').on('click', function() {
           toggleLogs();
       });

       // Toggle visibility and button text when clicking .frm-system-Error-logs element
       $('.frm-system-Error-logs').on('click', function() {
           toggleLogs();
       });
   });

    /**
     * Clear debug
     */
    jQuery(document).on('click', '.debug-clear-kk', function () {
    jQuery( ".clear-loading-sign-gscfrmdform" ).addClass( "loading" );
    var data = {
        action: 'gscfrmd_forms_clear_logs',
        security: jQuery('#gs-ajax-nonce').val()
    };
        jQuery.post(ajaxurl, data, function (response ) {
            if (response == -1) {
                return false; // Invalid nonce
            }
            var clear_msg = response.data;
            if( response.success ) { 
               jQuery( ".clear-loading-sign-gscfrmdform" ).removeClass( "loading" );
               jQuery( "#gscfrmdform-validation-message" ).empty();
               jQuery("<span class='gs-valid-message'>"+clear_msg+"</span>").appendTo('#gscfrmdform-validation-message'); 
               setTimeout(function () {
                     location.reload();
                 }, 1000);
            }
        });
    }); 

    jQuery(document).on('click', '.formidable-gs-sub-btn', function () {
        var feed_name = jQuery('.feedName').val();
        var formidableForms = jQuery('.formidableForms').val();

        if (feed_name != '' && formidableForms != '') {
            // Show loading indicator
            jQuery(".fld-fetch-load").addClass("loading");

            var data = {
                action: 'save_formidable_feed',
                security: jQuery('#gs-ajax-nonce').val(),
                feed_name: feed_name,
                formidableForms: formidableForms,
            };

            jQuery.post(ajaxurl, data, function (response) {
               
                if (response.success) {
                    jQuery(".fld-fetch-load").removeClass("loading");

                    if (response.data === 'Feed name already exists in the list, Please enter unique name of feed.') {
                        jQuery('.feed-error-message').html(response.data);
                        jQuery(".feed-error-message").show();
                        jQuery(".feed-success-message").hide();
                    } else if (response.data === 'Feed has been successfully created.') {
                        jQuery('.feed-success-message').html(response.data);
                        jQuery(".feed-error-message").hide();
                        jQuery(".feed-success-message").show();

                        // Update UI without page refresh
                        // You can optionally update the table or form here

                        // Example: Clear input fields
                        jQuery('.feedName').val('');
                        jQuery('.formidableForms').val('');

                       setTimeout(function () {
                            location.reload();
                        }, 1000);
                    }
                }
            }, 'json');
        } else {
            alert('Please Enter Feed Name and Select Form.');
        }
    });

    jQuery(document).ready(function($) {
        $('.delete-feed').click(function() {
            var feedId = $(this).data('feed-id');
            var confirmDelete = confirm('Are you sure you want to delete this feed?');
            if (confirmDelete) {
                jQuery(".loading-sign-delete-feed-elegs" + feedId).addClass("loading");

                // Submit a POST request to delete the feed
                $.post(ajaxurl, {
                    action: 'delete_feed',
                    feed_id: feedId, // Send the correct feed_id
                    security: jQuery('#gs-ajax-nonce').val()
                }, function(response) {
                    jQuery(".loading-sign-delete-feed-elegs" + feedId).removeClass("loading");

                    if (response === 'success') {
                        // Show success message
                        jQuery('.success-message').text('Feed deleted successfully!').fadeIn().delay(3000).fadeOut();
                        
                        // Reload the page after successful deletion (optional)
                        location.reload();
                    } else {
                        // Handle error here
                        console.log('Error deleting feed');
                    }
                });
            } else {
                jQuery(".loading-sign-delete-feed-elegs" + feedId).removeClass("loading");
            }
        });
    });
});
