<?php
  include $_SERVER['DOCUMENT_ROOT']."/../../include/db_connect.php" ;
  $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);

