/* globals jQuery:true, ajaxurl:true, secninja_mainwp:true, mainwpVars:true, mainwp_confirm:true,whiteLabelSettings:true */

function show_white_label_popup() {

  // Create the popup container
  var popup = jQuery('<div id="mainwp-popup" class="ui modal"></div>');

  // Add headline with prefix
  var headline = jQuery('<h3 class="ui dividing header">' + secninja_mainwp.texts.headline + '</h3>');
  
  var subline = jQuery('<p style="padding: 10px;">'+ secninja_mainwp.texts.subline +'</p>');
  popup.append(headline);
  popup.append(subline);

  // Create the form
  var form = jQuery('<form method="POST" action="" class="ui form" id="mainwp-whitelabel-form"></form>');

  // Add hidden form fields
  form.append('<input type="hidden" name="site_id" id="backup_site_id" value="">');
  form.append('<input type="hidden" name="backup_site_full_size" id="backup_site_full_size" value="">');
  form.append('<input type="hidden" name="backup_site_db_size" id="backup_site_db_size" value="">');

  // Add dropdown for enable/disable
  var statusGroup = jQuery('<div class="ui grid field"><label class="six wide column middle aligned">'+ secninja_mainwp.texts.whiteLabelStatus +':</label><div class="ten wide column"><select id="wl_active" name="wl_active" class="ui dropdown"><option value="1">'+ secninja_mainwp.texts.enableWhiteLabel +'</option><option value="0">'+ secninja_mainwp.texts.disableWhiteLabel +'</option></select></div></div>');
  form.append(statusGroup);

  // Add input fields with specific ids and prefilled defaults if available
  var wlDefaults = (secninja_mainwp && secninja_mainwp.whitelabelDefaults) ? secninja_mainwp.whitelabelDefaults : {};
  form.append(createInputField('wl_newname', secninja_mainwp.texts.pluginName, secninja_mainwp.texts.enterPluginName, wlDefaults.wl_newname, true));
  form.append(createInputField('wl_newdesc', secninja_mainwp.texts.pluginDescription, secninja_mainwp.texts.enterPluginDescription, wlDefaults.wl_newdesc, true));
  form.append(createInputField('wl_newauthor', secninja_mainwp.texts.authorName, secninja_mainwp.texts.enterAuthorName, wlDefaults.wl_newauthor, true));
  form.append(createInputField('wl_newurl', secninja_mainwp.texts.authorURL, secninja_mainwp.texts.enterAuthorURL, wlDefaults.wl_newurl, true));
  // Optional fields (not required)
  form.append(createInputField('wl_newiconurl', secninja_mainwp.texts.pluginIconURL, secninja_mainwp.texts.enterPluginIconURL, wlDefaults.wl_newiconurl, false));
  form.append(createInputField('wl_newmenuiconurl', secninja_mainwp.texts.pluginMenuIconURL, secninja_mainwp.texts.enterPluginMenuIconURL, wlDefaults.wl_newmenuiconurl, false));

  // Add message container with dynamic style
  var message = jQuery('<div id="message-container" style="margin-top: 20px; padding: 10px; display: none;"></div>');
  form.append(message);

  // Append form to popup
  popup.append(form);

  // Buttons for actions
  var closeButton = jQuery('<button class="ui button">'+ secninja_mainwp.texts.close+'</button>').click(function() {
      popup.modal('hide');
  });
  var sendButton = jQuery('<button class="ui green button" id="mainwp-submit-button">'+ secninja_mainwp.texts.sendToSelectedSites +'</button>').click(function() {
      if (validateForm()) {
          sendToSelectedSites();
      }
  });
  var actionsDiv = jQuery('<div class="actions"></div>').append(closeButton).append(sendButton);
  popup.append(actionsDiv);

  // Append popup to body
  jQuery('body').append(popup);

  // Initialize Semantic UI modal
  popup.modal({ closable: true }).modal('show');
  jQuery('.ui.dropdown').dropdown(); // Initialize dropdown instead of checkbox
  
  // Enable or disable input fields based on dropdown selection
  jQuery('#wl_active').on('change', function() {
      var enableValue = jQuery(this).val();
      
      if (enableValue === '0') { // Disable
          jQuery('#wl_newname, #wl_newdesc, #wl_newauthor, #wl_newurl, #wl_newiconurl, #wl_newmenuiconurl').closest('.field').hide().find('input').prop('disabled', true).removeAttr('required');
          message.text(secninja_mainwp.texts.warningDisable).css("background-color", "#ffe6e6").css("color", "#cc0000").show();
      } else { // Enable
          // Required fields
          jQuery('#wl_newname, #wl_newdesc, #wl_newauthor, #wl_newurl').closest('.field').show().find('input').prop('disabled', false).attr('required', 'required');
          // Optional fields (never required)
          jQuery('#wl_newiconurl, #wl_newmenuiconurl').closest('.field').show().find('input').prop('disabled', false).removeAttr('required');
          message.hide();
      }
  });
  
  // Manually set initial state without triggering change event
  jQuery('#wl_active').val('1'); // Default to enable
  
  // Manually show input fields since "Enable" is selected by default
  jQuery('#wl_newname, #wl_newdesc, #wl_newauthor, #wl_newurl').closest('.field').show().find('input').prop('disabled', false).attr('required', 'required');
  jQuery('#wl_newiconurl, #wl_newmenuiconurl').closest('.field').show().find('input').prop('disabled', false).removeAttr('required');
  
  // Only clear fields if we don't have any stored defaults (first time opening)
  // If we have defaults, use them; if not, start with empty fields
  if (!wlDefaults || Object.keys(wlDefaults).length === 0) {
      // First time opening - clear all fields
      jQuery('#wl_newname, #wl_newdesc, #wl_newauthor, #wl_newurl, #wl_newiconurl, #wl_newmenuiconurl').val('');
  }
  
  // Reset dropdown to ensure it's always "Enable" when modal opens
  setTimeout(function() {
      jQuery('#wl_active').dropdown('set selected', '1');
  }, 100);

  function createInputField(id, label, placeholder, defaultValue, isRequired) {
      var field = jQuery('<div class="ui grid field"><label class="six wide column middle aligned">' + label + ':</label><div class="ten wide column"><input type="text" id="' + id + '" name="' + id + '" placeholder="' + placeholder + '"></div></div>');
      var input = field.find('input');
      if (isRequired !== false) {
          input.attr('required', 'required');
      }
      if (typeof defaultValue !== 'undefined' && defaultValue !== null && String(defaultValue).length > 0) {
          input.val(defaultValue);
      }
      return field;
  }

  function validateForm() {
      var isValid = true;
      
      // If white label is being disabled, skip validation since we don't need the input fields
      var isDisabling = jQuery('#wl_active').val() === '0';
      if (isDisabling) {
          return true;
      }
      
      // Only validate fields that actually have the required attribute
      jQuery('input[required]').each(function() {
          if (!jQuery(this).val().trim()) {
              isValid = false;
              message.text(secninja_mainwp.texts.pleaseFillInAllRequiredFields).css("background-color", "#ffe6e6").css("color", "#cc0000").show();
              return false;
          }
      });
      return isValid;
  }

  function sendToSelectedSites() {
      var dropdownElement = jQuery('#wl_active');
      var dropdownValue = dropdownElement.val();
      
      var whiteLabelSettings = {
          wl_active: dropdownValue, // Use the selected dropdown value
          wl_newname: jQuery('#wl_newname').val(),
          wl_newdesc: jQuery('#wl_newdesc').val(),
          wl_newauthor: jQuery('#wl_newauthor').val(),
          wl_newurl: jQuery('#wl_newurl').val(),
          wl_newiconurl: jQuery('#wl_newiconurl').val(),
          wl_newmenuiconurl: jQuery('#wl_newmenuiconurl').val()
      };

      var selectedIds = jQuery.map(jQuery('#mainwp-manage-sites-body-table .check-column INPUT:checkbox:checked'), function (el) {
        return parseInt(jQuery(el).val(), 10);
    });
      
      if (selectedIds.length === 0) {
          message.text('No sites selected. Please select at least one site.').css("background-color", "#ffe6e6").css("color", "#cc0000").show();
          return;
      }
      
      jQuery.ajax({
          type: 'POST',
          url: ajaxurl,
          data: {
              '_ajax_nonce': secninja_mainwp.nonce_secnin,
              'action': 'secnin_run_update_white_label_module',
              'site_ids': selectedIds,
              'white_label_settings': whiteLabelSettings
          },
          dataType: "json",
          success: function (response) {
              popup.modal('hide');
              message.text(secninja_mainwp.texts.settingsUpdatedSuccessfully).css("background-color", "#e6ffe6").css("color", "#00cc00").show();
              
              // Simple solution: reload the page after successful submission
              // This ensures fresh state and no complex modal management
              setTimeout(function() {
                  window.location.reload();
              }, 1500); // Give user 1.5 seconds to see success message
          },
          error: function (xhr, status, error) {
              console.error('sendToSelectedSites: AJAX error:', {xhr: xhr, status: status, error: error});
              message.text(secninja_mainwp.texts.anErrorOccurred).css("background-color", "#ffe6e6").css("color", "#cc0000").show();
          }
      });
  }
}














jQuery(document).ready(function () {

  jQuery(document).on('click', '#mainwp-do-sites-bulk-actions', function () {
    var action = jQuery("#mainwp-sites-bulk-actions-menu").dropdown("get value");
    if (action == '')
      return false;




    // *** Run security tests
    if (action == 'secnin_runtests' || action == '...') {
      if (mainwpVars.bulkManageSitesTaskRunning) {
        return;
      }

      var confirmRunAllTestsMsg = secninja_mainwp.texts.runAllSecurityTests;
      mainwp_confirm(confirmRunAllTestsMsg, _callback = function () {
        var selectedIds = jQuery.map(jQuery('#mainwp-manage-sites-body-table .check-column INPUT:checkbox:checked'), function (el) {
          return parseInt(jQuery(el).val(), 10);
        });


        jQuery.ajax({
          type: 'POST',
          url: ajaxurl,
          data: {
            '_ajax_nonce': secninja_mainwp.nonce_secnin,
            'action': 'secnin_run_remote_security_tests',
            'site_ids': selectedIds
          },
          dataType: "json",
          success: function () {

          },
          error: function () {
          }
        });

      });
      return false; 

    }


    // *** Run malware scan @todo - in plugin?
    if (action == 'secnin_runmalware' || action == '...') {
      if (mainwpVars.bulkManageSitesTaskRunning) {
        return;
      }

      var confirmMsg = secninja_mainwp.texts.runMalwareScansOnSelectedSites; 

      mainwp_confirm(confirmMsg, _callback = function () {

        var selectedIds = jQuery.map(jQuery('#mainwp-manage-sites-body-table .check-column INPUT:checkbox:checked'), function (el) {
          return parseInt(jQuery(el).val(), 10);
        });



        jQuery.ajax({
          type: 'POST',
          url: ajaxurl,
          data: {
            '_ajax_nonce': secninja_mainwp.nonce_secnin,
            'action': 'secnin_run_remote_malwarescan',
            'site_ids': selectedIds
          },
          dataType: "json",
          success: function () {
          },
          error: function () {
          }
        });

      });
      return false; 

    }



    

    // *** Configure White Label
if (action == 'secnin_update_white_label' || action == '...') {
  if (mainwpVars.bulkManageSitesTaskRunning) {
    return;
  }

  if (action == 'secnin_update_white_label') {
    show_white_label_popup();
    return false;
  }

    var selectedIds = jQuery.map(jQuery('#mainwp-manage-sites-body-table .check-column INPUT:checkbox:checked'), function (el) {
      return parseInt(jQuery(el).val(), 10);
    });

    jQuery.ajax({
      type: 'POST',
      url: ajaxurl,
      data: {
          '_ajax_nonce': secninja_mainwp.nonce_secnin,
          'action': 'secnin_run_update_white_label_module',
          'site_ids': selectedIds,
          'white_label_settings': whiteLabelSettings
      },
      dataType: "json",
      success: function () {
          jQuery('#mainwp-popup').remove();
      },
      error: function () {
      }
    });


  return false;
}

  });

  

  // Collapsible sections
  jQuery('#mainwp-site-mode-wrap .collapsible').click(function () {
    jQuery(this).next('.section-content').slideToggle('fast');
  });

  // Initialize DataTable
  var eventsTable = jQuery('#security-ninja-events').DataTable({

    "processing": true,
    "serverSide": true,
    "autoWidth": true,
    "stateSave": true,
    "search": true,
    "ajax": {
      "url": ajaxurl,
      "type": "POST",
      "data": function (d) {
        return jQuery.extend({}, d, {
          'action': 'secnin_get_latest_events',
          '_ajax_nonce': secninja_mainwp.nonce_secnin,
          'site_filter': jQuery('#site-filter').val(),
          'action_filter': jQuery('#action-filter').val()
        });
      },
      "dataSrc": function (json) {
        return json.data;
      }
    },
    "order": [[0, 'desc']],
    "select": {
      style: 'multi'
    },
    "columns": [
      { "data": "timestamp" },
      { "data": "site_id" },
      { "data": "ip" },
      // { "data": "user_agent" },
      { "data": "action" },
      { "data": "description" }
    ],
    "pageLength": 25,
    "rowCallback": function (row) {
      jQuery(row).addClass('wp-list-table widefat fixed striped table-view-list');
    },
    "pagingType": "full_numbers",
    "scrollX": true,
    "lengthMenu": [[10, 25, 50, 100, 250, 500], [10, 25, 50, 100, 250, 500]],
    "language": {
      "emptyTable": secninja_mainwp.texts.no_events
  }

  });

  // Filter event handlers
  jQuery('#site-filter, #action-filter').on('change', function() {
    updateFilterSummary();
    // Show loading indicator
    jQuery('#mainwp-security-ninja-events .secnin-content-wrapper').addClass('loading');
    eventsTable.ajax.reload(function() {
      // Hide loading indicator when reload is complete
      jQuery('#mainwp-security-ninja-events .secnin-content-wrapper').removeClass('loading');
    });
  });

  // Function to update filter summary
  function updateFilterSummary() {
    var siteFilter = jQuery('#site-filter').val();
    var actionFilter = jQuery('#action-filter').val();
    var searchTerm = eventsTable.search();
    var summaryContent = [];
    var hasFilters = false;

    if (siteFilter) {
      summaryContent.push(secninja_mainwp.texts.site + ': ' + jQuery('#site-filter option:selected').text());
      hasFilters = true;
    }

    if (actionFilter) {
      summaryContent.push(secninja_mainwp.texts.action + ': ' + jQuery('#action-filter option:selected').text());
      hasFilters = true;
    }

    if (searchTerm) {
      summaryContent.push(secninja_mainwp.texts.search + ': "' + searchTerm + '"');
      hasFilters = true;
    }

    if (hasFilters) {
      // Securely create and append content to prevent XSS
      var summaryElement = jQuery('#filter-summary-content');
      summaryElement.empty(); // Clear existing content
      summaryElement.text(summaryContent.join(', ')); // Use .text() instead of .html() for security
      jQuery('#filter-summary').show();
    } else {
      jQuery('#filter-summary').hide();
    }
  }

  jQuery('#clear-filters').on('click', function() {
    // Reset dropdown values
    jQuery('#site-filter').val('').trigger('change');
    jQuery('#action-filter').val('').trigger('change');
    
    // Reset Semantic UI dropdowns visually
    jQuery('#site-filter').dropdown('clear');
    jQuery('#action-filter').dropdown('clear');
    
    updateFilterSummary();
    // Show loading indicator
    jQuery('#mainwp-security-ninja-events .secnin-content-wrapper').addClass('loading');
    eventsTable.ajax.reload(function() {
      // Hide loading indicator when reload is complete
      jQuery('#mainwp-security-ninja-events .secnin-content-wrapper').removeClass('loading');
    });
  });

  // Initialize Semantic UI dropdowns
  jQuery('.ui.dropdown').dropdown();

  // Listen for DataTable search changes
  eventsTable.on('search.dt', function() {
    updateFilterSummary();
  });


});


