<?php
require_once(dirname(__FILE__) . '/../includes/base.inc.php');

block_non_admins();
// block_demo(_('Manage Users'));


global $fused_servers;
global $users;

route_request();
function route_request()
{
  global $fused_servers;
  $fused_servers = get_fused_servers();

  $pageopt = get_pageopt();

  // if we chose a multi button, we just redirect the page opt based on the value
  $multi = grab_request_var('multi');
  $valid_multi_values = array('delete', 'unlock', 'enable', 'disable', 'email');
  if (in_array($multi, $valid_multi_values)) {
    $pageopt = $multi;
  }


  switch ($pageopt) {
    default:
      show_centralized_management();
      break;
  }
}

function show_centralized_management()
{
  global $fused_servers;
  global $users;

  $title = _('Centralized Management');
  child_page($title);
  echo well_top_page_header($title);
  $fused_servers = json_decode($fused_servers, true);
}

?>

<script type="text/javascript">
  $(function() {
    $("#centralized_users_tabs").tabs().css({
      "min-height": "400px",
      "overflow": "auto"
    }).show();
  });

  var available_users = [];
  var selected_users = [];
  var target_server_ids = [];

  var current_page = 1;
  var users_per_page = 5;
  var total_pages = 1;

  var users_loading = false;

  // toggle the users loading div
  function toggle_users_loading() {
    if (users_loading) {
      $("#users_loading_div").show();
    } else {
      $("#users_loading_div").hide();
    }
  }

  // toggle the push users button
  function toggle_push_users_button() {
    if (selected_users.length > 0 && target_server_ids.length > 0) {
      $("#push_users_button").prop("disabled", false);
    } else {
      $("#push_users_button").prop("disabled", true);
    }
  }

  // toggle the select all checkbox
  function toggle_select_all() {
    if ($("#select_all").prop("checked")) {
      // Select all users on current page
      var start_index = (current_page - 1) * users_per_page;
      var end_index = start_index + users_per_page;
      var page_users = available_users.slice(start_index, end_index);

      // Add page users to selected_users (avoid duplicates)
      page_users.forEach(user => {
        if (!selected_users.find(selected => selected.user_id == user.user_id)) {
          selected_users.push(user);
        }
      });

      $("input[name='user_id[]']").prop("checked", true);
    } else {
      // Deselect all users on current page
      var start_index = (current_page - 1) * users_per_page;
      var end_index = start_index + users_per_page;
      var page_users = available_users.slice(start_index, end_index);

      // Remove page users from selected_users
      page_users.forEach(user => {
        selected_users = selected_users.filter(selected => selected.user_id != user.user_id);
      });

      $("input[name='user_id[]']").prop("checked", false);
    }

    update_clear_selections_button();

    toggle_push_users_button();
  }

  // push the users to the target server
  function push_users() {
    // Show loading state
    $("#push_users_button").prop("disabled", true).text("<?php echo _('Pushing...'); ?>");

    $.ajax({
      url: "<?php echo get_base_url(); ?>/ajaxhelper.php",
      type: "GET",
      data: {
        cmd: "test_push_users",
        users: JSON.stringify(selected_users),
        target_server_ids: JSON.stringify(target_server_ids)
      },
      success: function(response) {
        try {
          var result = JSON.parse(response);

          console.group('push_users');
          console.log(result);
          console.groupEnd();

          if (result.success) {

            // Display detailed results
            display_push_results(result.target_servers_responses);

            // Clear user selections
            selected_users = [];
            $("#select_all").prop("checked", false);
            $("input[name='user_id[]']").prop("checked", false);

            // Clear target server selections
            target_server_ids = [];
            $("input[name='target_server_id[]']").prop("checked", false);

            // Update clear buttons
            update_clear_selections_button();
            update_target_server_clear_button();
          }
        } catch (e) {
          // Handle non-JSON response
          flash_message("<?php echo _('Unexpected response from server.'); ?>", "error", true);
        }
      },
      error: function(xhr, status, error) {
        // Show network/connection error
        flash_message("<?php echo _('Network error: '); ?>" + error, "error", true);
      },
      complete: function() {
        // Reset button state
        $("#push_users_button").prop("disabled", false).text("<?php echo _('Push Users'); ?>");
        toggle_push_users_button();
      }
    });
  }

  // Display detailed push results organized by server
  function display_push_results(target_servers_responses) {
    // Remove any existing results
    $("#push_results_div").remove();

    var resultsHtml = '<div id="push_results_div" style="margin-top: 20px;">';
    resultsHtml += '<h5><?php echo _('Push Results'); ?></h5>';

    // Get server names for display
    var serverNames = {};
    <?php foreach ($fused_servers['servers'] as $server) { ?>
      <?php if ($server['server_type'] == SERVER_TYPE_XI) { ?>
        serverNames[<?php echo $server['server_id']; ?>] = "<?php echo htmlspecialchars($server['name'], ENT_QUOTES); ?>";
      <?php } ?>
    <?php } ?>

    // Process each server's results
    for (var serverId in target_servers_responses) {
      var serverResults = target_servers_responses[serverId];
      var serverName = serverNames[serverId] || "<?php echo _('Server'); ?> " + serverId;

      // Count successes and errors
      var successCount = 0;
      var errorCount = 0;
      var successUsers = [];
      var errorUsers = [];

      // Process each username in the server results
      for (var username in serverResults) {
        var result = serverResults[username];

        if (result.success) {
          successCount++;
          successUsers.push({
            username: username,
            message: result.success
          });
        } else if (result.error) {
          errorCount++;
          errorUsers.push({
            username: username,
            message: result.error
          });
        }
      }

      resultsHtml += '<div class="server-result" style="margin-bottom: 15px; border: 1px solid #ddd; border-radius: 4px; padding: 10px;">';
      resultsHtml += '<h6 style="margin: 0 0 10px 0;">' + serverName + '</h6>';

      // Summary
      resultsHtml += '<div style="margin-bottom: 10px;">';
      if (successCount > 0) {
        resultsHtml += '<span class="label label-success" style="margin-right: 10px;">' + successCount + ' <?php echo _('Success'); ?></span>';
      }
      if (errorCount > 0) {
        resultsHtml += '<span class="label label-danger" style="margin-right: 10px;">' + errorCount + ' <?php echo _('Failed'); ?></span>';
      }
      resultsHtml += '</div>';

      // Detailed results
      if (successUsers.length > 0) {
        resultsHtml += '<div style="margin-bottom: 8px;">';
        resultsHtml += '<strong style="color: #5cb85c;"><?php echo _('Successful:'); ?></strong><br>';
        successUsers.forEach(function(result) {
          var formattedMessage = '[' + result.username + '] - ' + result.message;
          resultsHtml += '<span style="color: #5cb85c; margin-left: 15px;"> ' + formattedMessage + '</span><br>';
        });
        resultsHtml += '</div>';
      }

      if (errorUsers.length > 0) {
        resultsHtml += '<div>';
        resultsHtml += '<strong style="color: #d9534f;"><?php echo _('Failed:'); ?></strong><br>';
        errorUsers.forEach(function(result) {
          var formattedMessage = '[' + result.username + '] - ' + result.message;
          resultsHtml += '<span style="color: #d9534f; margin-left: 15px;"> ' + formattedMessage + '</span><br>';
        });
        resultsHtml += '</div>';
      }

      resultsHtml += '</div>';
    }

    resultsHtml += '</div>';

    // Insert results after the push button
    $("#push_users_button").parent().after(resultsHtml);
  }

  // update the selected users array
  function update_selected_users(user_id) {
    var target_user = available_users.find(user => user.user_id == user_id);


    if (selected_users.find(user => user.user_id == user_id)) {
      selected_users = selected_users.filter(user => user.user_id != user_id);
    } else {
      selected_users.push(target_user);
    }

    if (selected_users.length == available_users.length) {
      $("#select_all").prop("checked", true);
    } else {
      $("#select_all").prop("checked", false);
    }
    update_clear_selections_button();

    toggle_push_users_button();
  }

  // update the select all state
  function update_select_all_state() {
    var start_index = (current_page - 1) * users_per_page;
    var end_index = start_index + users_per_page;
    var page_users = available_users.slice(start_index, end_index);

    // Check if all users on current page are selected
    var all_page_users_selected = page_users.every(user =>
      selected_users.find(selected => selected.user_id == user.user_id)
    );

    $("#select_all").prop("checked", all_page_users_selected);
  }

  // clear all selected users
  function clear_all_selected_users() {
    selected_users = [];
    $("#select_all").prop("checked", false);
    $("input[name='user_id[]']").prop("checked", false);

    $("#clear_selections_button").remove();

    toggle_push_users_button();
  }

  // update the clear selections button
  function update_clear_selections_button() {
    if (selected_users.length > 0) {
      if ($("#clear_selections_button").length === 0) {
        // Add the button in the top right of the table area
        var clear_button = `
          <div style="position: absolute; top: 0; right: 0; z-index: 10;">
            <a href="javascript:void(0);" 
               id="clear_selections_button" 
               onclick="clear_all_selected_users();"
               style="color: #007bff; text-decoration: underline; background: none; border: none; padding: 0; font-size: 13px; cursor: pointer; font-weight: 500;"
               onmouseover="this.style.textDecoration='underline'; this.style.color='#0056b3';"
               onmouseout="this.style.textDecoration='underline'; this.style.color='#007bff';">
              Clear All Selections (${selected_users.length})
            </a>
          </div>`;

        $("#users_table_div").append(clear_button);
      } else {
        // Update the button text with current count
        $("#clear_selections_button").text('Clear All Selections (' + selected_users.length + ')');
      }
    } else {
      // Remove the button if no selections
      $("#clear_selections_button").parent().remove();
    }
  }

  // get the users from the source server
  function get_server_users(server_id) {
    if (server_id == "" || users_loading) {
      return;
    }

    users_loading = true;
    toggle_users_loading();

    $.ajax({
      url: "<?php echo get_base_url(); ?>/ajaxhelper.php",
      type: "GET",
      data: {
        server_id: server_id,
        cmd: "get_fused_server_users"
      },
      success: function(response) {
        var server_data = JSON.parse(response);

        $("#select_all").prop("checked", false);
        $("input[name='user_id[]']").prop("checked", false);

        available_users = server_data.users.filter(user => user.user_id != 1 || user.username == 'autoLogin');

        // Reset pagination
        current_page = 1;
        total_pages = Math.ceil(available_users.length / users_per_page);

        // Display the first page
        display_users_page();

        users_loading = false;
        toggle_users_loading();
      }
    });
  }

  // display the users page
  function display_users_page() {
    var start_index = (current_page - 1) * users_per_page;
    var end_index = start_index + users_per_page;
    var page_users = available_users.slice(start_index, end_index);

    var html = "";
    page_users.forEach(user => {
      // Check if this user is already selected
      var is_selected = selected_users.find(selected => selected.user_id == user.user_id);
      var checked_attr = is_selected ? ' checked' : '';

      html += `<tr>
        <td>
          <input type="checkbox" name="user_id[]" value="${user.user_id}" onclick="update_selected_users(${user.user_id});"${checked_attr} />
        </td>
        <td>${user.username}</td>
        <td>${user.name}</td>
        <td>${user.email}</td>
        <td>${user.auth_level}</td>
      </tr>`;
    });
    $("#users_table_body").html(html);

    // Update the "select all" checkbox state based on current page selections
    update_select_all_state();

    // Update pagination controls
    update_pagination_controls();

    update_clear_selections_button();
  }

  // update the pagination controls
  function update_pagination_controls() {
    var pagination_html = "";

    if (total_pages > 1) {
      pagination_html = '<div class="pagination-controls" style="text-align: center;">';
      pagination_html += '<span style="margin-right: 15px;">Page ' + current_page + ' of ' + total_pages + '</span>';

      // Previous button - always visible, disabled if on first page
      var prev_disabled = current_page <= 1 ? ' disabled' : '';
      pagination_html += '<button onclick="go_to_page(' + (current_page - 1) + ')" class="btn btn-xs btn-default" style="margin-right: 5px;"' + prev_disabled + '>Previous</button>';

      // Next button - always visible, disabled if on last page
      var next_disabled = current_page >= total_pages ? ' disabled' : '';
      pagination_html += '<button onclick="go_to_page(' + (current_page + 1) + ')" class="btn btn-xs btn-default"' + next_disabled + '>Next</button>';

      pagination_html += '</div>';
    }

    // Remove existing pagination controls and add new ones
    $(".pagination-controls").remove();
    $("#users_table_div").append(pagination_html);
  }

  // go to the page
  function go_to_page(page) {
    if (page >= 1 && page <= total_pages) {
      current_page = page;
      display_users_page();

      toggle_push_users_button();
    }
  }

  // target server functions
  function update_target_server_selection(server_id) {
    if (target_server_ids.includes(server_id)) {
      target_server_ids = target_server_ids.filter(id => id != server_id);
    } else {
      target_server_ids.push(server_id);
    }

    update_target_server_clear_button();
    toggle_push_users_button();
  }

  // clear all target servers
  function clear_all_target_servers() {
    target_server_ids = [];
    $("input[name='target_server_id[]']").prop("checked", false);
    $("#clear_target_servers_button").parent().remove();
    toggle_push_users_button();
  }

  // update the target server clear button
  function update_target_server_clear_button() {
    if (target_server_ids.length > 0) {
      if ($("#clear_target_servers_button").length === 0) {
        var clear_button = `
        <div style="position: absolute; top: 0; right: 0; z-index: 10;">
          <a href="javascript:void(0);" 
             id="clear_target_servers_button" 
             onclick="clear_all_target_servers();"
             style="color: #007bff; text-decoration: underline; background: none; border: none; padding: 0; font-size: 13px; cursor: pointer; font-weight: 500;"
             onmouseover="this.style.textDecoration='underline'; this.style.color='#0056b3';"
             onmouseout="this.style.textDecoration='underline'; this.style.color='#007bff';">
            Clear All Target Servers (${target_server_ids.length})
          </a>
        </div>`;

        $("#target_servers_table_div").append(clear_button);
      } else {
        $("#clear_target_servers_button").text('Clear All Target Servers (' + target_server_ids.length + ')');
      }
    } else {
      $("#clear_target_servers_button").parent().remove();
    }
  }

  // update the target servers table
  function update_target_servers_table() {
    var source_server_id = $("#source_server_select").val();
    var html = "";

    <?php foreach ($fused_servers['servers'] as $server) { ?>
      <?php if ($server['server_type'] == SERVER_TYPE_XI) { ?>
        var server_id = <?php echo $server['server_id']; ?>;
        var server_name = "<?php echo htmlspecialchars($server['name'], ENT_QUOTES); ?>";
        var server_address = "<?php echo htmlspecialchars($server['address'], ENT_QUOTES); ?>";

        // Skip the currently selected source server
        if (server_id != source_server_id) {
          var is_selected = target_server_ids.includes(server_id);
          var checked_attr = is_selected ? ' checked' : '';

          html += '<tr>' +
            '<td>' +
            '<input type="checkbox" name="target_server_id[]" value="' + server_id + '" onclick="update_target_server_selection(' + server_id + ');"' + checked_attr + ' />' +
            '</td>' +
            '<td>' + server_name + '</td>' +
            '<td>' + server_address + '</td>' +
            '<td><?php echo _('Nagios XI'); ?></td>' +
            '</tr>';
        }
      <?php } ?>
    <?php } ?>

    $("#target_servers_table_body").html(html);
    update_target_server_clear_button();
  }

  $("document").ready(function() {
    // hide the server selected div until a server is indeed selected
    $("#server_selected_div").hide();

    // Initialize target servers table (empty initially)
    update_target_servers_table();

    // get the users from the currently selected source server
    $("#source_server_select").change(function() {
      var server_id = $(this).val();
      get_server_users(server_id);

      // Clear any previously selected target servers
      target_server_ids = [];
      $("input[name='target_server_id[]']").prop("checked", false);

      // Update the target servers table to exclude the selected source server
      update_target_servers_table();

      $("#server_selected_div").show();
    });
  });
</script>

<div id="centralized_users_tabs" class="hide">
  <!-- tab list -->
  <ul>
    <!-- users tab -->
    <li>
      <a href="#centralized_users_tab_users">
        <i class="fa fa-user"></i>&nbsp;<?php echo _('Users'); ?>
      </a>
    </li>
  </ul>

  <!-- users tab content -->
  <div id="settings_tab_users">
    <div style="margin-top: 12px; display: flex; gap: 12px; flex-direction: column;">

      <div style="display: flex; gap: 12px; flex-direction: column;">
        <h5><?php echo _('Centralized Users Management'); ?></h5>
        <div class="subtext" style="color: red;"><em><?php echo _('Note: Nagios XI version 2026R1.0.1+ required for both source and target servers.'); ?></em></div>
        <p><?php echo _('Copy user accounts from one Nagios XI server to another to maintain consistent user access across your monitoring infrastructure.'); ?></p>
      </div>

      <!-- Source Server -->
      <div style="display: flex; gap: 12px; align-items: center;">
        <span><?php echo _('Source Server'); ?></span>
        <select class="form-control" id="source_server_select">
          <option value="" selected disabled hidden><?php echo _('Select a server to begin'); ?></option>
          <?php foreach ($fused_servers['servers'] as $server) { ?>
            <?php if ($server['server_type'] == SERVER_TYPE_XI) { ?>
              <option value="<?php echo $server['server_id']; ?>"><?php echo $server['name']; ?></option>
            <?php } ?>
          <?php } ?>
        </select>
        <div id="users_loading_div" style="display: none;">
          <i class="fa fa-spinner fa-spin"></i> <?php echo _('Loading...'); ?>
        </div>
      </div>

      <div id="server_selected_div" style="display: flex; gap: 12px; flex-direction: column;">
        <!-- Users Table -->
        <div id="users_table_div" style="display: flex; flex-direction: column; position: relative;">
          <span style="margin-bottom: 8px;"><?php echo _('Select the users you want to push to the target server from the table below.'); ?></span>
          <table class="table table-bordered table-striped">
            <thead>
              <tr>
                <th><input type="checkbox" id="select_all" onclick="toggle_select_all();" /></th>
                <th><?php echo _('Username'); ?></th>
                <th><?php echo _('Name'); ?></th>
                <th><?php echo _('Email'); ?></th>
                <th><?php echo _('Authentication Type'); ?></th>
              </tr>
            </thead>
            <tbody id="users_table_body">
            </tbody>
          </table>
        </div>

        <!-- Target Servers Table -->
        <div id="target_servers_table_div" style="display: flex; flex-direction: column; position: relative;">
          <span style="margin-bottom: 8px;"><?php echo _('Select the target servers you want to push the users to.'); ?></span>
          <table class="table table-bordered table-striped">
            <thead>
              <tr>
                <th><?php echo _('Select'); ?></th>
                <th><?php echo _('Server Name'); ?></th>
                <th><?php echo _('Address'); ?></th>
                <th><?php echo _('Type'); ?></th>
              </tr>
            </thead>
            <tbody id="target_servers_table_body">
              <!-- Target servers will be populated dynamically -->
            </tbody>
          </table>
        </div>

        <!-- Push Users Button -->
        <div style="display: flex; justify-content: flex-end;">
          <button class="btn btn-primary" style="min-width: 100px;" disabled id="push_users_button" onclick="push_users();"><?php echo _('Push Users'); ?></button>
        </div>
      </div>
    </div>
  </div>
</div>