<?php

require __DIR__ . '/../../helpers/auth.php';
auth_check(); // ❗ proteksi API

require __DIR__ . "/koneksi.php";

header('Content-Type: application/json');

// ======================
// Ambil PC + Monitoring Terakhir
// ======================
$sql = "
SELECT 
    c.id,
    c.hostname,
    c.ip_address,
    c.os,
    c.last_seen,

    s.nama_site AS site_name,
    s.code_site,

    m.cpu_usage,
    m.ram_percent,
    m.sensors

FROM pc_clients c

LEFT JOIN sites s 
    ON s.code_site = SUBSTRING_INDEX(SUBSTRING_INDEX(c.ip_address, '.', 3), '.', -1)

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 s.nama_site, c.hostname
";

$res = $conn->query($sql);
$data = [];

while ($r = $res->fetch_assoc()) {

    $sensors = json_decode($r['sensors'], true) ?? [];

    $cpuTemp =
        $sensors['cpu_temp'][0]['value']
        ?? $sensors['temperatures'][0]['value']
        ?? null;

    $status = (strtotime($r['last_seen']) > time() - 120)
        ? 'online'
        : 'offline';

    // ======================
    // CEK ALERT AKTIF (READ ONLY)
    // ======================
    $alertRes = $conn->query("
        SELECT 1 FROM alert_log
        WHERE pc_id={$r['id']}
          AND alert_type='temperature'
          AND status='active'
        LIMIT 1
    ");
    $is_alert = $alertRes->num_rows > 0;

    $data[] = [
        "id"        => $r['id'],
        "hostname"  => $r['hostname'],
        "ip_address"=> $r['ip_address'],
        "os"        => $r['os'],

        "site_name" => $r['site_name'] ?? 'Unknown Site',
        "code_site" => $r['code_site'],

        "status"    => $status,
        "last_seen" => $r['last_seen'],
        "cpu"       => (float)$r['cpu_usage'],
        "ram"       => (float)$r['ram_percent'],
        "temp"      => $cpuTemp,
        "sensors"   => $sensors,
        "is_alert"  => $is_alert
    ];
}

echo json_encode($data);
