
jQuery( document ).ready( function($) {

  // Initiate the Extension menu
  $( '#mainwp-vulnerability-checker-menu .item' ).tab();

  // Close modal and reload screen after
  $(document).on('click', '.close-reload-modal', function() {
    jQuery('#mainwp-vulnerability-checker-modal').modal( 'hide' );
    window.location.reload();
  });

  // Trigger the recheck action for a specific site
  $(document).on('click', '.vulner_action_recheck', function () {
    var obj = $( this ).closest( 'tr' );
    mainwp_vulner_results_recheck_start_specific( obj, false, false );
    return false;
  });

  // Filter groups
  $(document).on('click', '#vulner_btn_display', function () {
      $( this ).closest( 'form' ).submit();
  });

  // Trigger the recheck process for all sites
  $(document).on('click', '#vulner_recheck_all_sites', function () {

    var data = {
  		action: 'mainwp_vulner_load_sites',
      nonce: mainwp_vulner_loca.nonce,
      what: 'recheck'
	  };

    var statusEl = jQuery( '#mainwp-message-zone' );

    statusEl.html( '' ).hide();
    statusEl.removeClass( 'red green' );
    statusEl.html( 'Rechecking sites. Please wait...' ).show();

  	jQuery.post( ajaxurl, data, function (response) {
  		statusEl.html( '' );
      if ( response ) {
        if ( response['error'] ) {
          statusEl.addClass( 'red' );
          statusEl.html( response['error'] );
        } else if ( response['result'] ) {
          statusEl.html( '' ).hide();
          statusEl.removeClass( 'red green' );
          jQuery('#mainwp-vulnerability-checker-modal').find( '.content' ).html( response['result'] );
          jQuery('#mainwp-vulnerability-checker-modal').modal( 'show' );
          vulner_bulkTotalThreads = jQuery('.siteItemProcess[status=queue]').length;
          mainwp_vulner_recheck_all_sites_start_next();
        } else {
          statusEl.addClass( 'red' );
          statusEl.html( 'Undefined error. Please try again.' );
        }
      } else {
        statusEl.addClass( 'red' );
        statusEl.html( 'Undefined error. Please try again.' );
      }

  	}, 'json');

	  return false;
  });


  // Trigger bulk actions
  $(document).on('click', '#vulner_results_doaction_btn', function () {
    var bulk_act = $( '#vulner_results_action' ).find( ':selected' ).val();
    mainwp_vulner_results_do_bulk_action( bulk_act );
  });

  // Recheck on the Individual Vulnerabilities page
  $(document).on('click', '#vulner_recheck_site', function () {
    var button = this;
    var site_id = $( button ).attr( 'website-id' );

  	var data = {
  		action: 'mainwp_vulner_result_recheck',
  		websiteId: site_id,
  		force: 0,
      nonce: mainwp_vulner_loca.nonce
  	}

    $( button ).attr( 'disabled', 'disabled' );

    var statusEl = jQuery( '#mainwp-message-zone' );

    statusEl.html('');
    statusEl.removeClass( 'red green' );
    statusEl.html( '<i class="notched circle loading icon"></i> ' + __( 'Rechecking. Please wait...' ) ).show();

    jQuery.post(ajaxurl, data, function (response) {
      $(button).removeAttr( 'disabled' );
		  statusEl.html( '' );
      if ( response ) {
        if ( response['error'] ) {
          statusEl.addClass( 'red' );
          statusEl.html( response['error'] );
        } else if (response['ok']) {
          statusEl.addClass( 'green' );
          statusEl.html( '<i class="check icon"></i>' + __( "Rechecked successfully!" ) );
          window.location = "admin.php?page=ManageSitesVulnerabilities&id=" + site_id;
        } else {
          statusEl.addClass( 'red' );
          statusEl.html( '<i class="close icon"></i>' + __( 'Undefined error. Please try again.' ) );
        }
      } else {
        statusEl.addClass( 'red' );
        statusEl.html( '<i class="close icon"></i>' + __( 'Undefined error. Please try again.' ) );
      }
	  }, 'json');
	return false;
  });

  // Trigger the Update/Delete action on indivisual site page
  $(document).on('click', 'a.vulner-detail-action-btn', function () {
    mainwp_vulner_upgrade_delete_plugintheme( $( this ) );
    return false;
  });
});

var vulner_bulkMaxThreads = 3;
var vulner_bulkTotalThreads = 0;
var vulner_bulkCurrentThreads = 0;
var vulner_bulkFinishedThreads = 0;

// Bulk action selection Force or Not to force
mainwp_vulner_results_do_bulk_action = function (act) {
  jQuery( '#mainwp-vulnerabilities-list tr' ).addClass( 'queue' );
	switch ( act ) {
    case 'recheck':
      mainwp_vulner_results_recheck_start_next( false );
      break;
    case 'force-recheck':
      mainwp_vulner_results_recheck_start_next( true );
      break;
	}
}

// Loop trugh the selected sites
mainwp_vulner_results_recheck_start_next = function ( force ) {
  var selector = '#mainwp-vulnerabilities-list tr';
	while ((objProcess = jQuery(selector + '.queue:first')) && (objProcess.length > 0) && (vulner_bulkCurrentThreads < vulner_bulkMaxThreads)) { // NOSONAR -- modified out side the function.
    objProcess.removeClass( 'queue' );
    if ( objProcess.find( 'td input[type="checkbox"]:checked' ).length == 0 )
      continue;
    mainwp_vulner_results_recheck_start_specific( objProcess, true, force );
  }
}

// Recheck a specific site
mainwp_vulner_results_recheck_start_specific = function ( pObj, bulk, force ) {

  var statusEl = pObj

	var data = {
		action: 'mainwp_vulner_result_recheck',
		websiteId: pObj.attr( 'website-id' ),
		force: force ? 1 : 0,
    nonce: mainwp_vulner_loca.nonce
	}

	if ( bulk ) {
    vulner_bulkCurrentThreads++;
  }

  statusEl.html( '<td colspan="9"><i class="notched circle loading icon"></i> ' + __( 'Rechecking. Please wait...' ) + '</td>' );
	jQuery.post( ajaxurl, data, function (response) {
		statusEl.html( '<td colspan="9"><i class="times circle red icon"></i></td>' );
		pObj.removeClass( 'queue' );
    if ( response ) {
      if ( response['error'] ) {
        statusEl.html( '<td colspan="9">' + response['error'] + '</td>' );
      } else if ( response['ok'] ) {
        statusEl.html( '<td colspan="9"><i class="check circle green icon"></i> ' + __( 'Checked successfully!' ) + '</td>' );
      } else {
        statusEl.html( '<td colspan="9"><i class="times circle red icon"></i> ' + __( 'Undefined error. Please try again.' ) + '</td>' );
      }
    } else {
      statusEl.html( '<td colspan="9"><i class="times circle red icon"></i> ' + __( 'Undefined error. Please try again.' ) + '</td>' );
    }

    if ( !bulk ) {
      window.location.reload();
    }

		if ( bulk ) {
      vulner_bulkCurrentThreads--;
      vulner_bulkFinishedThreads++;
      mainwp_vulner_results_recheck_start_next( force );
		}

    if ( vulner_bulkCurrentThreads == 0 ) {
      //window.location.reload();
    }

	}, 'json');

	return false;
}

// Loop throug all sites
mainwp_vulner_recheck_all_sites_start_next = function () {
  while ( ( objProcess = jQuery( '.item[status=queue]:first' ) ) && ( objProcess.length > 0 ) && ( vulner_bulkCurrentThreads < vulner_bulkMaxThreads ) ) {
    objProcess.attr( 'status', 'processed' );
    mainwp_vulner_recheck_all_sites_start_specific( objProcess );
  }
}

// Check all sites
mainwp_vulner_recheck_all_sites_start_specific = function (pObj) {

	var statusEl = objProcess.find( '.status' );

	vulner_bulkCurrentThreads++;

	var data = {
		action: 'mainwp_vulner_result_recheck',
		websiteId: pObj.attr( 'website-id' ),
    nonce: mainwp_vulner_loca.nonce
	};

  statusEl.html( '' );
	statusEl.html( '<span data-tooltip="Checking..." data-position="left center" data-inverted=""><i class="notched circle loading icon"></i></span>');

	jQuery.post( ajaxurl, data, function ( response ) {
    if ( response) {
      if ( response.error ) {
        let errorMessage = response.error;
        if ( errorMessage.startsWith( "MainWP Child" ) ) {
          errorMessage = "MainWP Child plugin not detected or could not be reached! Ensure the MainWP Child plugin is installed and activated on the child site, and there are no security rules blocking requests."
        }
        statusEl.html( '<span data-tooltip="' + errorMessage + '" data-position="left center" data-inverted=""><i class="times red icon"></i></span>' );
      } else if ( response.ok ) {
        statusEl.html( '<span data-tooltip="Checked successfully!" data-position="left center" data-inverted=""><i class="check green icon"></i></span>' );
      } else {
        statusEl.html( '<span data-tooltip="Undefined error. Please try again." data-position="left center" data-inverted=""><i class="times red icon"></i></span>' );
      }
    } else {
      statusEl.html( '<span data-tooltip="Undefined error. Please try again." data-position="left center" data-inverted=""><i class="times red icon"></i></span>' );
    }

		vulner_bulkCurrentThreads--;
		vulner_bulkFinishedThreads++;
		mainwp_vulner_recheck_all_sites_start_next();
	}, 'json' );
	return false;
}

// Update/Delete vulnerable instances
mainwp_vulner_upgrade_delete_plugintheme = function (pObj) {
  var action = pObj.attr( 'what' );
	var parent = pObj.closest( '.vulner-detail-actions' );
	var type   = parent.attr( 'action-type' );
  var slug   = parent.attr( 'slug' );

  if ( action == 'delete' ) {
    if ( !confirm( __( 'Are you sure?' ) ) ) {
      return false;
    }
  }

  var data = false;

  if ( action == 'update' ) {
    data = {
      action: 'mainwp_vulner_upgrade_plugintheme',
      websiteId: parent.attr( 'website-id' ),
      type: type,
      'slugs[]': [slug],
      nonce: mainwp_vulner_loca.nonce
    }
	} else if ( action == 'delete' ) {
    if (type == 'plugin') {
      data = {
        action: 'mainwp_vulner_delete_plugin',
        websiteId: parent.attr( 'website-id' ),
        plugins: [slug],
        nonce: mainwp_vulner_loca.nonce
      }
    } else {
      var name = parent.attr( 'theme-name' ),
      data = {
        action: 'mainwp_vulner_delete_theme',
        websiteId: parent.attr( 'website-id' ),
        themes: [name],
        nonce: mainwp_vulner_loca.nonce
      }
    }
  }

  parent.find( '.vulner-detail-action-btn' ).each(function(){
    jQuery( this ).attr( 'disabled', 'disabled' );
  });

	statusEl = jQuery( '#mainwp-message-zone' );

  statusEl.html( '' );
  statusEl.removeClass( 'red green' );
  statusEl.html( '<i class="notched circle loading icon"></i> ' + __( 'Action in progress. Please wait...') ).show();

	jQuery.post(ajaxurl, data, function (response) {
		statusEl.html( '' );
    if ( response ) {
      if ( response['error'] ) {
        if ( response['error'] == 'IsActivatedTheme' ) {
          statusEl.html( '<i class="close icon"></i> ' +  __( 'Active theme could not be deleted. Please deactivate the theme first.' ) );
          statusEl.addClass( 'red' );
        } else {
          statusEl.html( '<i class="close icon"></i> ' + response['error'] );
          statusEl.addClass( 'red' );
        }
      } else if ( (action == 'delete' && response['result'] ) || ( action == 'update' && response['upgrades'][slug] ) ) {
        statusEl.html( '<i class="close icon"></i> ' + __( 'Action completed successfully!' ) );
        statusEl.addClass( 'green' );
        scrollToElement();
        jQuery( '#vulner_recheck_site' ).trigger( "click" );
      } else {
        statusEl.html( '<i class="close icon"></i> ' + __( "Undefined error" ) );
        statusEl.addClass( 'red' );
      }
    } else {
      statusEl.html( '<i class="close icon"></i> ' + __( "Undefined error" ) );
      statusEl.addClass( 'red' );
    }
	}, 'json');
	return false;
}

mainwp_vulner_issues_ignore_detail = function ( what, type, obj ) {
  var msg = __( 'Are you sure you want to ignore the issue?' );
  if ( 'global' == what ) {
    msg = __( 'Are you sure you want to ignore the issue globally?' );
  }
  mainwp_confirm(msg, function(){
      return mainwp_vulner_ignore_issue_item( what, type, obj );
  }, false, 1 );
  return false;
};

mainwp_vulner_ignore_issue_item = function ( what, type, pObj ) {
  var parent = jQuery(pObj).closest('tr');
  var data = {
      action: 'mainwp_vulner_ignore_issue',
      what: what,
      type: type,
      cve_id: parent.attr('cve-id'),
      detail: parent.attr('cve-detail'),
      datetime: parent.attr('cve-datetime'),
      nonce: mainwp_vulner_loca.nonce,
  };

  if ( 'global' != what ) {
    data['site_id'] =  parent.attr('site-id');
  }

  jQuery.post( ajaxurl, data, function ( response ) {
      parent.find('td:last-child').html( __('Ignoring...') );
      if ( response.result ) {
           parent.find('td:last-child').html(__( 'Ignored' ));
      } else
      {
          parent.find('td:last-child').html( getErrorMessage( response.error ) );
      }
  }, 'json' );
  return false;
};

mainwp_vulner_unignore_issues_all = function ( what, type, pObj ) {
      var tblParent = jQuery(pObj).closest('table');
      var data = {
          action: 'mainwp_vulner_unignore_sites_issue',
          type: type,
          what: what,
          nonce: mainwp_vulner_loca.nonce,
      };

      if ( 'site' == what ) {
        var site_ids = [];
        jQuery( tblParent ).find('tr').each( function () {
            var siteid = jQuery( this ).attr( 'site-id' );
            var cveid = jQuery( this ).attr( 'cve-id' );
            site_ids.push({
                'site_id': siteid,
                'cve_id':  cveid
            });
        } );
        data.all_site_ids = site_ids;
      } else {
        var cve_ids = [];
        jQuery( tblParent ).find('tr').each( function () {
            var cveid = jQuery( this ).attr( 'cve-id' );
            cve_ids.push(cveid);
        } );
        data.all_cve_ids = cve_ids;
      }

      jQuery.post( ajaxurl, data, function ( response ) {
          if ( response.result ) {
              tblParent.find( 'tr' ).remove();
              jQuery( pObj ).addClass( 'disabled' );
              tblParent.append( '<tr><td colspan="999">' + __( 'No ignored issues.' ) + '</td></tr>' );
          }
      }, 'json' );
      return false;
};


mainwp_vulner_unignore_issue_item = function ( what, type, pObj ) {
  var parent = jQuery(pObj).closest('tr');

  var data = {
      action: 'mainwp_vulner_unignore_item_issue',
      what: what,
      type: type,
      cve_id: parent.attr('cve-id'),
      nonce: mainwp_vulner_loca.nonce,
  };

  if ( 'global' != type ) {
    data['site_id'] = parent.attr('site-id');
  }

  jQuery.post( ajaxurl, data, function ( response ) {
      parent.find('td:last-child').html( __('Unignoring...') );
      if ( response.result ) {
           parent.find('td:last-child').html(__( 'Unignored' ));
      } else
      {
          parent.find('td:last-child').html( getErrorMessage( response.error ) );
      }
  }, 'json' );
  return false;
};

