<?php
require __DIR__ . "/../api/monitoring/koneksi.php";

$data = [];

$sql = "
SELECT 
    c.id,
    c.hostname,
    c.ip_address,
    c.os,
    c.last_seen,
    m.cpu_usage,
    m.ram_percent
FROM pc_clients c
LEFT JOIN pc_monitoring m ON m.id = (
    SELECT id FROM pc_monitoring
    WHERE pc_client_id = c.id
    ORDER BY id DESC
    LIMIT 1
)
ORDER BY c.hostname
";

$q = $conn->query($sql);

while ($r = $q->fetch_assoc()) {
    $data[] = [
        "id" => $r['id'], // ⭐⭐⭐ WAJIB
        "hostname" => $r['hostname'],
        "ip" => $r['ip_address'],
        "os" => $r['os'],
        "status" => (strtotime($r['last_seen']) >= time() - 120) ? "online" : "offline",
        "last_seen" => $r['last_seen'],
        "cpu" => $r['cpu_usage'],
        "ram" => $r['ram_percent']
    ];
}

echo json_encode($data);
