/* globals jQuery:true, ajaxurl:true, sn_unblock_ui:true, wf_sn_ms:true */
/*
 * Security Ninja - Malware Scanner add-on
 * (c) 2015. Web factory Ltd
 */

function pad(val) {
  var valString = val + "";
  if (valString.length < 2) {
    return "0" + valString;
  } else {
    return valString;
  }
}

var msminutesLabel = document.getElementById("mscounterminutes");
var mssecondsLabel = document.getElementById("mscounterseconds");
var totalSeconds = 0;
var timerInterval; // Variable to hold the timer interval

// FOR THE SECOND COUNTER ON THE OVERLAY
function updateTimeCounter() {
  ++totalSeconds;
  mssecondsLabel.innerHTML = pad(totalSeconds % 60);
  msminutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
}

var actions = [
  {msg1: 'Cleaning cache ... ', msg2: ' DONE!', action: 'clean_cache'},
  {msg1: 'Checking malware definitions', msg2: 'DONE!', action: 'update_samples'},
  {msg1: 'Checking plugins for modifications', msg2: 'DONE!', action: 'do_integrity_scan'},
  // {msg1: 'Scanning database for malicious code', msg2: 'DONE!', action: 'do_db_scan '},
  {msg1: 'Scanning website for malicious code', msg2: 'DONE!', action: 'do_mal_scan'},
  {msg1: 'Generating results ... ', msg2: 'DONE!', action: 'get_results'}
];

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

  // handle each individual ajax call
  function do_sn_ms_request(params) {
    jQuery('#sn_ms_timer').slideDown(500);
    return jQuery.ajax({
      type: 'POST',
      url: ajaxurl,
      data: {
        action: 'sn_ms_run_scan',
        what: params.action,
        _ajax_nonce: wf_sn_ms.nonce
      },
      dataType: 'json',
      success: function(response) {
        if (response !== null) {
          if (response.success !== null) {
            jQuery('#msg_' + params.action).removeClass('pending').removeClass('current').addClass('passed');
            jQuery('.badge', '#msg_' + params.action).html(params.msg2.replace('%d', parseInt(response.data.cnt, 10)));

            if (params.action === 'get_results') {
              clearInterval(timerInterval); // Stop the timer
              jQuery('#sn_ms_timer').fadeOut(500); // Fade out the timer div

              jQuery('#sn_ms_results').append(response.data);
              sn_unblock_ui('#sn-malware-scanner');

              jQuery('.loader').show();

              // Re-enable the scan button
              jQuery('#sn_ms_run_scan').prop('disabled', false);
            }

            // Check for matched items and append results
            if (response.data && response.data.matchedItems) {
              appendScannerResults(response.data.matchedItems);
            }
          } else {
            alert('Invalid option. Please reload');
            // Re-enable the scan button in case of error
            jQuery('#sn_ms_run_scan').prop('disabled', false);
          }
        }
      },
      error: function() {
        alert('An undocumented error has occurred. Please reload the page and try again.');
        // Re-enable the scan button in case of error
        jQuery('#sn_ms_run_scan').prop('disabled', false);
      }
    });
  }

  // run test
  jQuery('#sn_ms_run_scan').on('click', function(e) {
    e.preventDefault();
    jQuery('#sn_ms_run_scan').prop('disabled', true);

    $('#sn_ms_results').show().html('');
    $('#scanstatus').html('');
    totalSeconds = 0;
    updateTimeCounter();
    timerInterval = setInterval(updateTimeCounter, 1000);

    let startingpoint = $.Deferred();
    startingpoint.resolve();

    $('ul.malware-scan-list').html('');
    $('.wrap .error').hide();

    $.each(actions, function(i, action) {
      $('ul.malware-scan-list').append('<li id="msg_' + action.action + '" class="pending">' + action.msg1 + ' <span class="badge">Waiting ...</span></li>');
    });

    $('.loader').hide();

    $.each(actions, function(i, action) {
      startingpoint = startingpoint.pipe(function() {
        var $actionRow = $('<div class="action-row" data-action="' + action.action + '" style="display: flex; align-items: center;"></div>');
        var $actionMsg = $('<div id="msg_' + action.action + '" class="current" style="flex: 1;">' + action.msg1 + ' <span class="badge">Working ...</span></div>');
        var $responseMsg = $('<div class="response-msg" style="flex: 1; margin-left: 10px;"></div>');
        var $timer = $('<div class="action-timer" style="margin-left: 10px;">0s</div>');

        $actionRow.append($actionMsg).append($responseMsg).append($timer);
        $('#sn_ms_results').append($actionRow);

        var actionStartTime = Date.now();
        var actionTimerInterval = setInterval(function() {
          var elapsedSeconds = Math.floor((Date.now() - actionStartTime) / 1000);
          $timer.text(elapsedSeconds + 's');
        }, 1000);

        return do_sn_ms_request(action).always(function(response) {
          clearInterval(actionTimerInterval);
          $actionMsg.removeClass('current').addClass('passed');
          $timer.text('Completed in ' + Math.floor((Date.now() - actionStartTime) / 1000) + 's');

          if (response.data && response.data.msg) {
            $responseMsg.html( response.data.msg );
          }
        });
      });
    });

    startingpoint.done(function() {
      clearInterval(timerInterval);
      $('#sn_ms_timer').append('<div class="total-time" style="text-align: right;">Total Time: ' + pad(parseInt(totalSeconds / 60)) + ':' + pad(totalSeconds % 60) + '</div>');
    });

    $('.wf-sn-ms-not-run').hide();
  });

  // .sn-malware-title
  $('.secnin_content_wrapper').on('click', '.toggle-slide', function(e) {
    e.preventDefault();

    let content = $(this).parents('.sn-malware-filebox').find('.sn-malware-file-code');
    $(this).toggleClass('opened');
    $(content).slideToggle(500);
  });

  // reset files whitelist
  $('#sn-ms-reset-whitelist').on('click', function(e) {
    e.preventDefault();

    if (!confirm('Are you sure you want to reset the whitelisted files list?\nPlease rescan files after cleaning the whitelist.')) {
      return;
    }
    $.post(ajaxurl, {
      _ajax_nonce: wf_sn_ms.nonce,
      action: 'sn_ms_reset_whitelist'
    },
    function() {
      window.location.reload();
    });
  }); // reset files whitelist

  // whitelist file
  $('#sn_malware').on('click', 'button.sn_ms_whitelist', function(e) {
    e.preventDefault();

    let tmp = confirm('Are you sure you want to whitelist this file?\n\nPlease reload page to see all changes.');
    if (!tmp) {
      return;
    }

    $(this).parents('.sn-malware-filebox').slideUp(500);

    $.post(ajaxurl, {
      action: 'sn_ms_whitelist_file',
      hash: $(this).data('hash'),
      nonce: $(this).data('nonce'),
      filename: $(this).data('filename'),
      _ajax_nonce: wf_sn_ms.nonce
    },
    function(response) {
      if (response.success) {
        // Remove the whitelisted file from the UI
        $(this).parents('.sn-malware-filebox').slideUp(500, function() {
          $(this).remove();
        });
        
        // Update the results with fresh data
        updateMalwareScannerUI(response);
        
        // Show success message
        alert('The file has been successfully added to the whitelist. The list has been updated.');
      } else {
        alert('Error: ' + (response.data && response.data.message ? response.data.message : 'Could not add the file to the whitelist.'));
      }
    },
    'json');
  });

  // Revert whitelisting a file
  $('#sn_malware').on('click', 'button.sn_ms_revert_whitelist', function(e) {
    e.preventDefault();

    let tmp = confirm('Are you sure you want to no longer whitelist this file?\n\nPlease reload page to see all changes.');
    if (!tmp) {
      return;
    }

    $(this).parents('.sn-malware-filebox').slideUp(500);

    $.post(ajaxurl, {
      action: 'revert_whitelist_btn',
      hash: $(this).data('hash'),
      nonce: $(this).data('nonce'),
      filename: $(this).data('filename'),
      _ajax_nonce: wf_sn_ms.nonce
    },
    function(response) {
      if (response.success) {
        // Remove the reverted file from the UI
        $(this).parents('.sn-malware-filebox').slideUp(500, function() {
          $(this).remove();
        });
        
        // Update the results with fresh data
        updateMalwareScannerUI(response);
        
        // Show success message
        alert('The file has been successfully removed from the whitelist. The list has been updated.');
      } else {
        alert('Error: ' + (response.data && response.data.message ? response.data.message : 'Could not remove the file from the whitelist.'));
      }
    },
    'json').fail(function(jqXHR, textStatus, errorThrown) {
      alert('Request failed: ' + textStatus + '. ' + errorThrown);
    });
  });

  // delete file
  $('#sn_ms_results').on('click', 'button.sn_ms_delete', function(e) {
    e.preventDefault();

    let tmp = confirm('Are you sure you want to delete this file?\n\nThere is NO undo!\n\nThis can break functionality or your site from functioning.\n\n' + $(this).data('filename'));
    if (!tmp) {
      return;
    }

    let button = this;

    $.post(ajaxurl, {
      action: 'sn_ms_delete_file',
      filename: $(this).data('filename'),
      hash: $(this).data('hash'),
      nonce: $(this).data('nonce'),
      _ajax_nonce: wf_sn_ms.nonce
    },
    function(response) {
      if (typeof response.success == 'undefined') {
        alert('Undocumented error. File was not deleted. Please reload the page.');
      } else if (response.success == true) {
        // Remove the deleted file from the UI
        $(button).parents('.sn-malware-filebox').slideUp(500, function() {
          $(this).remove();
        });
        
        // Update the results with fresh data
        updateMalwareScannerUI(response);
        
        // Show success message
        alert('File deleted! The list has been updated.');
      } else {
        alert('Your file access properties do not allow us to delete the file (this is not a bad thing). Please delete it manually, via FTP.');   
      }
    },
    'json');
  }); // Delete a file

  // view file
  $('#sn_ms_results').on('click', '.sn_ms_view_file', function(e) {
    e.preventDefault();
    if (typeof $(this).data('href') !== 'undefined') {
      const href = $(this).data('href');
      try {
        new URL(href); // This will throw an error if the URL is invalid
        window.open(href);
      } catch (e) {
        console.error('Invalid URL:', href);
      }
      return;
    }
  });

  /**
   * Updates the malware scanner results UI with fresh data
   *
   * @param {Object} response - AJAX response containing fresh_output and suspicious_count
   */
  function updateMalwareScannerUI(response) {
    if (response.data && response.data.fresh_output) {
      // Find the results container and update it
      var $resultsContainer = $('#sn_ms_results');
      
      // Remove ALL existing scan results content to prevent duplicates
      // Keep only the scan controls and timer, remove everything else
      $resultsContainer.find('h3, .card, .sn-malware-filebox, .scanner-result-row').remove();
      
      // Insert the fresh output
      $resultsContainer.prepend(response.data.fresh_output);
      
      // Update the count if it exists
      if (response.data.suspicious_count !== undefined) {
        var $countHeader = $resultsContainer.find('h3.error');
        if ($countHeader.length > 0) {
          var countText = response.data.suspicious_count === 1 ? 
            '1 suspicious file found' : 
            response.data.suspicious_count + ' issues found';
          $countHeader.text(countText);
        }
      }
    }
  }

  /**
   * Generates HTML output for malware scanner results and appends it to the results list.
   *
   * @param {Array} results - Array of result objects from the malware scanner.
   * Each result object should have the following properties:
   * - scanner: The name of the scanner (e.g., 'File Scanner', 'DB Scanner').
   * - filename: The name of the file (if applicable).
   * - optionName: The name of the option (if applicable).
   * - value: A part of the value or file content.
   */
  function appendScannerResults(results) {
    results.forEach(function(result) {
      var resultDiv = jQuery('<div class="scanner-result-row"></div>');
      var scannerInfo = '<strong>Scanner:</strong> ' + result.scanner + '<br>';
      var filenameInfo = result.filename ? '<strong>Filename:</strong> ' + result.filename + '<br>' : ''; 
      var optionNameInfo = result.optionName ? '<strong>Option Name:</strong> ' + result.optionName + '<br>' : '';
      var valueInfo = result.value ? '<strong>Value:</strong> ' + result.value + '<br>' : '';

      resultDiv.html(scannerInfo + filenameInfo + optionNameInfo + valueInfo);
      jQuery('#sn_ms_results').append(resultDiv);
    });
  }



});