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

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

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

  <script src="/js/jquery-3.6.1.min.js"></script>
  <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>
  <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/global.php";

  // NOUVEAU : Gérer les filtres
  // Par défaut, tout est coché (true)
  // On vérifie si un paramètre est passé dans l'URL pour décocher une case
  $show_aix = isset($_GET['show_aix']) ? $_GET['show_aix'] === '1' : true;
  $show_linux = isset($_GET['show_linux']) ? $_GET['show_linux'] === '1' : true;

  // Construction de la requête SQL
  $base_sql = "SELECT * FROM x_inventory WHERE type IS NOT NULL and hostname not in ('DUNAPPDNIM51','DUNAPPDNIM52') ";
  $conditions = [];

  if ($show_aix) {
    // La condition pour AIX est simple
    $conditions[] = "type = 'AIX'";
  }
  if ($show_linux) {
    // D'après votre code, tout ce qui n'est pas 'AIX' est considéré comme Linux
    $conditions[] = "type <> 'AIX'";
  }

  if (!empty($conditions)) {
    // On ajoute les conditions à la requête de base
    $sql = $base_sql . " AND (" . implode(' OR ', $conditions) . ")";
  } else {
    // Si rien n'est coché, on ne retourne aucun résultat
    $sql = $base_sql . " AND 1=0";
  }


  // DATA
  $servers = Invoke_Infra($sql); // On utilise la nouvelle requête
  $UTDS1 = (Invoke_Infra("select max(Ver) as utd from X_cmdb_Product where Name = 's1'"))[0]['utd'];
  $UTDNessus = (Invoke_Infra("select max(Ver) as utd from X_cmdb_Product where Name = 'nessus'"))[0]['utd'];
  $UTDZabbix = (Invoke_Infra("select max(Ver) as utd from X_cmdb_Product where Name = 'zabbix'"))[0]['utd'];
  $rows = Invoke_Infra("SELECT DISTINCT(Ver) FROM X_cmdb_Product WHERE Name='bes'");
  $versions = array_map(fn ($r) => $r['Ver'] ?? null, $rows);
  $versions = array_values(array_filter($versions));
  usort($versions, 'version_compare');
  $UTDBES = end($versions);
  $UTDFI = (Invoke_Infra("select max(Ver) as utd from X_cmdb_Product where Name = 'fi'"))[0]['utd'];
?>


<div class="container-fluid" id="content">
  <div class="row flex-nowrap">
    <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>
    <div class="col py-3">
      <h1><span class="badge text-bg-secondary font-weight-bold" style="width:100%;">AIX / Linux inventory</span></h1>

      <div class="container-fluid">
        <div class="d-flex justify-content-start align-items-center mb-2 p-2 rounded bg-secondary-subtle">
          <form class="form-inline d-flex gap-4">
            <div class="form-check form-switch">
              <input class="form-check-input" type="checkbox" role="switch" id="showAix" <?php echo $show_aix ? 'checked' : ''; ?>>
              <label class="form-check-label" for="showAix"><strong>AIX</strong></label>
            </div>
            <div class="form-check form-switch">
              <input class="form-check-input" type="checkbox" role="switch" id="showLinux" <?php echo $show_linux ? 'checked' : ''; ?>>
              <label class="form-check-label" for="showLinux"><strong>Linux</strong></label>
            </div>
          </form>
        </div>

        <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>
            <tr>
              <th data-field="Name" data-sortable="true">Name</th>
              <th data-field="Heartbeat" data-sortable="true" data-visible="false">Heartbeat</th>
              <th data-field="Host" data-sortable="true">Host</th>
              <th data-field="OS" data-sortable="true">OS Type</th>
              <th data-field="distrib" data-sortable="true">Distrib</th>
              <th data-field="Last Boot" data-sortable="true">Last reboot</th>
              <th data-field="Last Backup" data-sortable="true">Last backup</th>
              <th data-field="Auth" data-sortable="true">Auth</th>
              <th data-field="SentinelOne" data-sortable="true">SentinelOne</th>
              <th data-field="Nessus" data-sortable="true">Nessus</th>
              <th data-field="Zabbix" data-sortable="true">Zabbix</th>
              <th data-field="BES" data-sortable="true" data-visible="false">BES</th>
              <th data-field="FI" data-sortable="true" data-visible="false">Fusion Inv.</th>
            </tr>
            </thead>

            <tbody>
            <?php
              $total = 0;
              foreach ($servers as $s) {
                $total++;
                echo "<tr>";
                //name
                $name = $s['hostname'];
                $heartbeat = $s['Heartbeat'];
                $statusClass = '';
                $heartbeatDate = new DateTime($heartbeat);
                $now = new DateTime();
                $interval = $now->diff($heartbeatDate);
                $diffInMinutes = ($interval->days * 24 * 60) + ($interval->h * 60) + $interval->i;
                if ($diffInMinutes < 10) {
                  $statusClass = 'table-success';
                } elseif ($diffInMinutes <= 30) {
                  $statusClass = 'table-warning';
                } else {
                  $statusClass = 'table-danger';
                }
                echo "<td class='$statusClass'>";
                echo "  <a href='/inventory/server-detail.php?s={$name}' target='_blank'>{$name}</a>";
                echo "</td>";

                //heartbeat
                echo "<td>" . $s["Heartbeat"] . "</td>";

                //Host
                echo "<td>" . $s['Owner'] . "</td>";
                //OS Type
                $typ = match ($s['type'] ?? null) {
                  'AIX'    => 'AIX',
                  null, '' => '',
                  default  => 'LINUX',
                };
                echo "<td>" . $s['type'] . "</td>";

                //Distrib
                $Distrib = "";
                if ($typ == "AIX") {
                  $Distrib = $s['osversion'];
                }
                if ($typ == "LINUX") {
                  $Distrib = $s['osversion'] . " <small>(" . str_replace(".x86_64", "", $s['kernel']) . ")</small>";
                }
                echo "<td>$Distrib</td>";

                //LastReboot
                $lr = $s['lastboot'] ?? "";
                $lrDate = "";
                try {
                  $lrDate = new DateTime($lr);
                } catch (DateMalformedStringException $e) {
                }
                $interval = (new DateTime())->diff($lrDate);
                if ($interval->days > 60) {
                  echo "<td class='table-danger'>$lr</td>";
                } else {
                  if ($interval->days > 1) {
                    echo "<td>$lr</td>";
                  } else {
                    echo "<td class='table-success'>$lr</td>";
                  }
                }

                //LastBackup
                $lr = explode(".", $s['backuplast'] ?? "")[0];
                if(str_contains(strtolower($s['backuplog']), 'progress')){
                  $size = "<span class='text-warning'>In Progress</span>";
                }elseif (str_contains(strtolower($s['backuplog']), 'waiting')){
                  $size = "<span class='text-warning'><br>".$s['backuplog']."</span>";
                }elseif (str_contains(strtolower($s['backuplog']), 'error')){
                  $size = "<span class='text-danger'><b> ERROR !!!</b></span>";
                }else {
                  $size = 0;
                  if ($s['backuplog'] != "") {
                    if (str_contains($s['backuplog'], "Length")) {
                      $size = explode(" ", $s['backuplog'])[1];
                    } else {
                      $size = explode(" ", $s['backuplog'])[3];
                    }
                    $size = floor($size / 1024 / 1024 / 1024);
                  }
                  if ($size >= 15) {
                    $size = "<span class='text-danger'><b>$size GB</b></span>";
                  } else {
                    $size = "$size GB";
                  }
                }
                try {
                  $lrDate = new DateTime($lr);
                } catch (DateMalformedStringException $e) {
                }
                $interval = (new DateTime())->diff($lrDate);
                if ($interval->days > 7 || $s['backuplast'] == "") {
                  echo "<td class='table-danger'>$lr" . " " . $size . "</td>";
                } else {
                  if ($interval->days > 1) {
                    echo "<td>" . date_format($lrDate, "Y-m-d H:i:s") . " - " . $size . "</td>";
                  } else {
                    echo "<td class='table-success'>$lr" . " - " . $size . "</td>";
                  }
                }

                //Auth
                echo "<td>" . $s['auth'] . "</td>";

                //SentinelOne
                $s1s = $s['S1State'];
                $s1v = $s['S1Version'];
                if ($typ == "LINUX") {
                  if ($s1s == "YY") {
                    if ($s1v == $UTDS1) {
                      echo "<td class='table-success'>$s1v $s1s</td>";
                    } else {
                      echo "<td class='table-warning'><b>$s1v</b> $s1s</td>";
                    }
                  } else {
                    if ($s1v == "") {
                      echo "<td class='table-danger text-center'>MISSING</td>";
                    } else {
                      echo "<td class='table-danger'>$s1v <b>$s1s</b></td>";
                    }
                  }
                } else {
                  echo "<td></td>";
                }

                //Nessus
                $s1s = $s['NessusState'];
                $s1v = $s['NessusVersion'];
                if ($typ == "LINUX") {
                  if ($s1s == "YYY_YYY") {
                    if ($s1v == $UTDNessus) {
                      echo "<td class='table-success'>$s1v $s1s</td>";
                    } else {
                      echo "<td class='table-warning'><b>$s1v</b> $s1s</td>";
                    }
                  } else {
                    if ($s1v == "") {
                      echo "<td class='table-danger text-center'>MISSING</td>";
                    } else {
                      echo "<td class='table-danger'>$s1v <b>$s1s</b></td>";
                    }
                  }
                } else {
                  echo "<td></td>";
                }

                //Zabbix
                $s1s = $s['ZabbixState'];
                $s1v = $s['ZabbixVersion'];
                if ($typ == "AIX" && str_starts_with($s['osversion'], '6')) {
                  echo "<td></td>";
                } else {
                  if ($s1s == "Y") {
                    if ($s1v == $UTDZabbix) {
                      echo "<td class='table-success'>$s1v $s1s</td>";
                    } else {
                      echo "<td class='table-warning'><b>$s1v</b> $s1s</td>";
                    }
                  } else {
                    if ($s1v == "") {
                      echo "<td class='table-danger text-center'>MISSING</td>";
                    } else {
                      echo "<td class='table-danger'>$s1v <b>$s1s</b></td>";
                    }
                  }
                }

                //BES
                $s1s = $s['BESState'];
                $s1v = $s['BESVersion'];
                if ($s1s == "Y") {
                  if ($s1v == $UTDBES) {
                    echo "<td class='table-success'>$s1v $s1s</td>";
                  } else {
                    echo "<td class='table-warning'><b>$s1v</b> $s1s</td>";
                  }
                } else {
                  if ($s1v == "") {
                    echo "<td class='table-danger text-center'>MISSING</td>";
                  } else {
                    echo "<td class='table-danger'>$s1v <b>$s1s</b></td>";
                  }
                }

                //FI
                $s1s = $s['FIState'];
                $s1v = $s['FIVersion'];
                if ($typ == "LINUX") {
                  if ($s1s == "Y") {
                    if ($s1v == $UTDFI) {
                      echo "<td class='table-success'>$s1v $s1s</td>";
                    } else {
                      echo "<td class='table-warning'><b>$s1v</b> $s1s</td>";
                    }
                  } else {
                    if ($s1v == "") {
                      echo "<td class='table-danger text-center'>MISSING</td>";
                    } else {
                      echo "<td class='table-danger'>$s1v <b>$s1s</b></td>";
                    }
                  }
                } else {
                  echo "<td></td>";
                }

                echo "</tr>";
              }

            ?>
            </tbody>
          </table><br>
          <h5 class="text-center"><?php echo $total; ?> servers</h5>
        </div>
      </div>
    </div>
  </div>
</div>
</body>
<script src="/js/switch.js"></script>

<script>
  // This function will be executed when the document is ready
  $(function() {
    // Add an event listener to both checkboxes
    $('#showAix, #showLinux').on('change', function() {
      // Get the current state of the checkboxes (checked or not)
      // '1' for checked, '0' for unchecked
      const showAix = $('#showAix').is(':checked') ? '1' : '0';
      const showLinux = $('#showLinux').is(':checked') ? '1' : '0';

      // Create a URL object to easily manipulate query parameters
      const url = new URL(window.location.href);

      // Set the parameters based on checkbox states
      url.searchParams.set('show_aix', showAix);
      url.searchParams.set('show_linux', showLinux);

      // Reload the page with the new URL
      window.location.href = url.toString();
    });
  });
</script>

</HTML>
<script src="/js/tableResize.js"></script>