<?php
  function decypher(string $name): ?string {
    $openssl = 'C:\Program Files\FireDaemon OpenSSL 3\bin\openssl.exe';
    $cmsFile = "F:\\Include\\dat\\$name.p7m";
    $certPem = "F:\\Include\\certs\\cert_only.pem";
    $keyPem  = "F:\\Include\\certs\\key_only.pem";

    foreach ([$openssl,$cmsFile,$certPem,$keyPem] as $p) {
      if (!is_file($p)) { error_log("Missing file: $p"); return null; }
    }

    $cmd = '"' . $openssl . '" cms -decrypt -inform PEM'
      . ' -in '    . escapeshellarg($cmsFile)
      . ' -recip ' . escapeshellarg($certPem)
      . ' -inkey ' . escapeshellarg($keyPem)
      . ' -out -';

    $spec = [
      0 => ['pipe','r'],   // stdin (unused)
      1 => ['pipe','w'],   // stdout -> texte déchiffré
      2 => ['pipe','w'],   // stderr -> erreurs OpenSSL
    ];
    $proc = proc_open($cmd, $spec, $pipes);
    if (!is_resource($proc)) { error_log('proc_open failed'); return null; }
    fclose($pipes[0]); // rien à envoyer en stdin

    $stdout = stream_get_contents($pipes[1]); fclose($pipes[1]);
    $stderr = stream_get_contents($pipes[2]); fclose($pipes[2]);
    $code = proc_close($proc);

    if ($code !== 0) {
      error_log("OpenSSL failed (code $code): $stderr");
      return null;
    }
    return $stdout;
  }
  function DB_ZABBIX()
  {
    $host = 'aztprdzabbix52.armony.net';
    $dbname = 'zabbix';
    $user = 'patrick';
    $pass = decypher( 'zabbix');
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
    return $pdo;
  }
  $pdo = DB_ZABBIX();


  $server = strtolower($_GET['c']);
$now = time();
$past_24h = $now - 86400; // 24H

//Get Host ID
$hostQuery = "SELECT hostid, name FROM hosts WHERE name = :server";
$hostStmt = $pdo->prepare($hostQuery);
$hostStmt->execute(['server' => $server]);
$host = $hostStmt->fetch();
$hostId = $host['hostid'];
    
// Récupération des identifiants d'items pour CPU et mémoire
$itemQuery = "SELECT itemid, name, value_type FROM items 
              WHERE hostid = :hostid
              AND (name LIKE '%Memory utilization%' OR name LIKE '%CPU utilization%')";
$itemStmt = $pdo->prepare($itemQuery);
$itemStmt->execute(['hostid' => $hostId]);
$items = $itemStmt->fetchAll();
    
$data = [];
// Get CPU & Memory Items
foreach ($items as $item) {
  $isMemory = strpos(strtolower($item['name']), 'memory') !== false;
  $valueType = $item['value_type'] ?? ($isMemory ? 3 : 0);
  $tableMap = [0 => 'history', 1 => 'history_str', 2 => 'history_log', 3 => 'history_uint', 4 => 'history_text'];
  $table = $tableMap[$valueType] ?? ($isMemory ? 'history_uint' : 'history');
  // Get History Data
  $sql = "SELECT FROM_UNIXTIME(FLOOR(clock / 600) * 600) AS datetime, 
          AVG(value) AS avg_value 
          FROM $table 
          WHERE itemid = :itemid AND clock BETWEEN :start AND :end 
          GROUP BY FLOOR(clock / 600) 
          ORDER BY clock";
  $stmt = $pdo->prepare($sql);
  $stmt->execute(['itemid' => $item['itemid'], 'start' => $past_24h, 'end' => $now]);
  $results = $stmt->fetchAll();
  // Format Data
    foreach ($results as &$row) {
      $row['avg_value'] = $isMemory ? 
      floatval($row['avg_value']) : 
      round(floatval($row['avg_value']), 2);
    }
    $data[$item['name']] = $results;
}
// Send JSON back
echo json_encode($data, JSON_NUMERIC_CHECK);

