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

$pc_id = (int)($_GET['pc_id'] ?? 0);
$limit = 30;

$sql = "
SELECT 
    m.created_at,
    m.cpu_usage,
    m.ram_percent,
    m.disk,
    m.sensors,
    m.errors
FROM pc_monitoring m
WHERE m.pc_client_id = ?
ORDER BY m.id DESC
LIMIT ?
";

$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $pc_id, $limit);
$stmt->execute();
$res = $stmt->get_result();

$rows = [];

while ($r = $res->fetch_assoc()) {
    $sensors = json_decode($r['sensors'], true) ?? [];
    $disk = json_decode($r['disk'], true) ?? [];
    $errors = json_decode($r['errors'], true) ?? [];

    $rows[] = [
        "time" => $r['created_at'],
        "cpu" => $r['cpu_usage'],
        "ram" => $r['ram_percent'],
        "cpu_temp" => $sensors['cpu_temp'][0]['value'] ?? null,
        "gpu_temp" => $sensors['gpu_temp'][0]['value'] ?? null,
        "fan" => $sensors['fan'][0]['rpm'] ?? null,
        "disk" => $disk,
        "sensors" => $sensors,
        "errors" => $errors
    ];
}

echo json_encode(array_reverse($rows));
