<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Page Title -->
  <title>Web Infra Reports IT</title>
  <link rel="shortcut icon" type="image/png" href="/include/favicon-32x32.png">

  <!-- JQuery -->
  <script src="/js/jquery-3.6.1.min.js"></script>
  <!-- Bootstrap -->
  <link rel="stylesheet" href="/css/bootstrap.min.css">
  <link rel="stylesheet" href="/css/bootstrap-icons/bootstrap-icons.css">
  <link rel="stylesheet" href="/css/preloader.css">
  <script src="/js/bootstrap.bundle.min.js"></script>
  <!-- Bootstrap-tables -->
  <link rel="stylesheet" href="/css/bootstrap-table.min.css">
  <script src="/js/bootstrap-table.min.js"></script>
  <script src="/js/bootstrap-table-fr-FR.min.js"></script>
  <script src="/js/tableExport.min.js"></script>
  <script src="/js/bootstrap-table-export.min.js"></script>
  <script src="/js/libs/js-xlsx/xlsx.core.min.js"></script>


</head>

<body class="bg-light text-dark">
<?php include $_SERVER['DOCUMENT_ROOT'] . "/include/all.php"; ?> <!-- Include All -->

<!-- HTML -->
<div class="container-fluid" id="content">
  <div class="row flex-nowrap">
    <!-- Left NAVBAR -->
    <div class="col-auto col-md-2 col-xl-2 px-sm-2 px-0 bg-dark vh-100 position-sticky top-0" style="-ms-flex: 0 0 230px;flex: 0 0 230px;">
      <?php include $_SERVER['DOCUMENT_ROOT'] . "/navbar.html"; ?>
    </div>
    <!-- Display -->
    <div class="col py-3">
      <!-- Page Title -->
      <h2><span class="badge text-bg-secondary " style="width:100%;" >VM Storage (migration phase)</span></h2>

      <!-- Main content -->
      <div class="container-fluid">
        <!-- MODAL WAIT -->
        <div class="modal fade bs-example-modal-sm" id="wait" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" style="padding-top: 15%;">
          <div class="modal-dialog modal-sm">
            <div class="modal-content">
              <div class="modal-header">
                <h4 class="modal-title mb-1 text-dark text-uppercase text-center">
                  <i class="bi bi-hourglass-split"></i><br> Work in progress ...
                </h4>
              </div>
              <div class="modal-body">
                <div class="progress">
                  <div class="progress-bar progress-bar-secondary progress-bar-striped progress-bar-animated" style="width: 100%"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- TABLE -->
        <div>
          <table class='table table-bordered table-hover table-sm' id='t1' data-height="620" data-toggle="table" data-search="true" data-show-columns="true" data-export-types="['xlsx','csv','json']" data-show-export="true" data-sortable="true" data-sort-name="vm">
            <thead> <!-- Header -->
            <tr>
              <th data-field='vm' data-sortable='true'>VM</th>
              <th data-field='Last Backup' data-sortable='true'>Legacy Host</th>
              <th data-field='Last Result' data-sortable='true'>Destination Host</th>
              <th data-field='Last Good' data-sortable='true'>VHDX Storage</th>
              <th data-field='Size' data-sortable='true'>VNX Luns</th>
              <th data-field='Host' data-sortable='true'>SVC Luns</th>
            </tr>
            </thead>

            <tbody> <!-- Body -->
            <tbody> <!-- Body -->
            <?php
              // --- STEP 1: DATA FETCHING ---
              // Fetch all necessary data with the minimum number of queries.

              // Fetch all VMs
              $vms = Invoke_Infra("SELECT Name, Owner, VHDXs, WWPNs FROM cmdb_vms WHERE (owner LIKE '%DUN%' OR owner LIKE '%mdk%') AND owner NOT LIKE '%VMH-WM%' AND owner NOT LIKE '%WKG%' AND DecomTime IS NULL ORDER BY name");

              // Fetch all relevant LUNs (both VNX and SVC) in a SINGLE query.
              // This is much more efficient than fetching them separately and then querying again in a loop.
              $all_luns = Invoke_WebInfraTools("SELECT hostname, baie, name, size FROM storage_lun WHERE baie IN ('VNX', 'SVC')");


              // --- STEP 2: DATA PROCESSING ---
              // Organize the LUNs into an associative array for very fast lookups.
              // The key will be the hostname, and the value will be an array of its LUNs.
              $luns_by_hostname = [];
              foreach ($all_luns as $lun) {
                $hostname = $lun['hostname'];
                // Initialize the array for this hostname if it's the first time we see it.
                if (!isset($luns_by_hostname[$hostname])) {
                  $luns_by_hostname[$hostname] = [
                    'VNX' => [],
                    'SVC' => []
                  ];
                }
                // Add the LUN to the correct category (VNX or SVC) for its host.
                $luns_by_hostname[$hostname][$lun['baie']][] = $lun;
              }

              // Get the list of cluster hostnames from the LUNs we already fetched.
              // This avoids an extra database query for clusters.
              $cluster_hostnames = [];
              foreach ($luns_by_hostname as $hostname => $luns) {
                if (str_contains($hostname, '-c1')) {
                  $cluster_hostnames[] = $hostname;
                }
              }
              sort($cluster_hostnames); // Sort them alphabetically


              // --- STEP 3: RENDERING ---
              // Now, loop through the prepared data and render the HTML.
              // Use htmlspecialchars() on all output to prevent XSS attacks.

              /**
               * Helper function to render LUNs for a specific host, avoiding duplicates.
               * This avoids code duplication and handles redundant data from the DB.
               * @param array $luns The array of LUNs for a specific host.
               * @param string $type 'VNX' or 'SVC'.
               * @return string The generated HTML for the table cell.
               */
              function renderLuns(array $luns, string $type): string {
                $html = "<td>";
                $rendered_luns = []; // Array to track what has been rendered

                if (!empty($luns)) {
                  foreach ($luns as $lun) {
                    $lun_name = ($type === 'VNX' && str_contains($lun['name'], '_')) ? explode("_", $lun['name'])[1] : $lun['name'];
                    $lun_size = $lun['size'];

                    // Create a unique key for this LUN to detect duplicates
                    $unique_key = $lun_name . ':' . $lun_size;

                    // If we have already rendered this exact LUN, skip it
                    if (in_array($unique_key, $rendered_luns)) {
                      continue;
                    }

                    // Render the LUN and add its key to our tracking array
                    $html .= htmlspecialchars($lun_name) . " : " . htmlspecialchars($lun_size) . "GB<br>\n";
                    $rendered_luns[] = $unique_key;
                  }
                }
                $html .= "</td>";
                return $html;
              }

              // Render rows for VMs
              foreach ($vms as $vm) {
                echo "<tr>";
                echo "<td>" . htmlspecialchars($vm['Name']) . "</td>";

                if (str_contains($vm['Owner'], "SYN") || str_contains($vm['Owner'], "MIG")) {
                  echo "<td></td><td>" . htmlspecialchars($vm['Owner']) . "</td>";
                } else {
                  echo "<td>" . htmlspecialchars($vm['Owner']) . "</td><td></td>";
                }

                // --- CORRECTED VHDX RENDERING ---
                $vhdx_parts = [];
                if (!empty($vm['VHDXs'])) {
                  // 1. Split the string into an array of individual VHDX entries
                  $vhdx_entries = explode('|', $vm['VHDXs']);

                  foreach ($vhdx_entries as $entry) {
                    // 2. Replace the first comma (after .vhdx) with " : " and add "GB"
                    // The limit parameter '2' ensures we only replace the first occurrence.
                    $formatted_entry = preg_replace('/\.vhdx,/', ' : ', $entry, 1) . 'GB';
                    $vhdx_parts[] = $formatted_entry;
                  }
                }
                // 3. Join all formatted parts with a comma and a space
                echo "<td>" . implode('<br>', $vhdx_parts) . "</td>";

                if ($vm['WWPNs'] != "") {
                  $hostname = $vm['Name'];
                  $vnx_luns = $luns_by_hostname[$hostname]['VNX'] ?? [];
                  $svc_luns = $luns_by_hostname[$hostname]['SVC'] ?? [];
                  echo renderLuns($vnx_luns, 'VNX');
                  echo renderLuns($svc_luns, 'SVC');
                } else {
                  echo "<td></td><td></td>";
                }
                echo "</tr>";
              }

              // Render rows for Clusters
              foreach ($cluster_hostnames as $hostname) {
                echo "<tr>";
                echo "<td>" . htmlspecialchars($hostname) . " (Cluster)</td>";
                echo "<td></td><td></td><td></td>"; // Empty cells for Legacy, Destination, VHDX

                $vnx_luns = $luns_by_hostname[$hostname]['VNX'] ?? [];
                $svc_luns = $luns_by_hostname[$hostname]['SVC'] ?? [];
                echo renderLuns($vnx_luns, 'VNX');
                echo renderLuns($svc_luns, 'SVC');

                echo "</tr>";
              }
            ?>
            </tbody>
            </tbody>
          </table>
          <br>
        </div>
      </div>
      <!-- End of main content -->
    </div>
  </div>
</div>
</body>
<script src="/js/switch.js"></script>
</HTML>

<SCRIPT>
  const table = $('#t1');
  $(document).ready(function() {
    table.DataTable({
      scrollY: '50vh',
      scrollCollapse: true,
      paging: false,
    });
  });

  $(function () {
    const options = table.bootstrapTable('getOptions');
    options.height= document.getElementById('content').clientHeight-170;
    table.bootstrapTable('refreshOptions',options);
  });

  function tableresize() {
    const options = table.bootstrapTable('getOptions');
    options.height= document.getElementById('content').clientHeight-170;
    table.bootstrapTable('refreshOptions',options);
  }
  window.addEventListener("resize", tableresize);
</script>
