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

$where = [];
$params = [];
$types = '';

if (!empty($_GET['from'])) {
    $where[] = "m.created_at >= ?";
    $params[] = $_GET['from'] . " 00:00:00";
    $types .= 's';
}

if (!empty($_GET['to'])) {
    $where[] = "m.created_at <= ?";
    $params[] = $_GET['to'] . " 23:59:59";
    $types .= 's';
}

if (!empty($_GET['pc_id'])) {
    $where[] = "m.pc_client_id = ?";
    $params[] = (int)$_GET['pc_id'];
    $types .= 'i';
}

$sql = "
SELECT m.*, p.hostname
FROM pc_monitoring m
JOIN pc_clients p ON p.id = m.pc_client_id
";

if ($where) {
    $sql .= " WHERE " . implode(" AND ", $where);
}

$sql .= " ORDER BY m.id DESC LIMIT 500";

$stmt = $conn->prepare($sql);

if ($params) {
    $stmt->bind_param($types, ...$params);
}

$stmt->execute();
$res = $stmt->get_result();

$data = [];

while ($r = $res->fetch_assoc()) {
    $sensors = json_decode($r['sensors'], true);
    $data[] = [
        "created_at" => $r['created_at'],
        "hostname" => $r['hostname'],
        "cpu_usage" => $r['cpu_usage'],
        "ram_percent" => $r['ram_percent'],
        "cpu_temp" => $sensors['cpu_temp'][0]['value'] ?? null
    ];
}

echo json_encode($data);
