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

$API_KEY = "SECRET_API_KEY_ANDA";

/* ===============================
   AUTH
================================ */
$headers = getallheaders();
if (!isset($headers['Authorization'])) {
    http_response_code(401);
    exit("No Authorization Header");
}

if ($headers['Authorization'] !== "Bearer $API_KEY") {
    http_response_code(403);
    exit("Invalid API Key");
}

/* ===============================
   READ JSON
================================ */
$input = json_decode(file_get_contents("php://input"), true);
if (!$input) {
    http_response_code(400);
    exit("Invalid JSON");
}

$basic   = $input['basic']   ?? [];
$cpu     = $input['cpu']     ?? [];
$ram     = $input['ram']     ?? [];
$disk    = $input['disk']    ?? [];
$sensors = $input['sensors'] ?? [];
$errors  = $input['errors']  ?? [];

/* ===============================
   VALIDATE BASIC
================================ */
$hostname = $basic['hostname'] ?? null;
$ip       = $basic['ip'] ?? null;
$os       = $basic['os'] ?? null;

if (!$hostname) {
    http_response_code(400);
    exit("Hostname missing");
}

/* ===============================
   PC REGISTER / UPDATE
================================ */
$stmt = $conn->prepare("SELECT id FROM pc_clients WHERE hostname=?");
$stmt->bind_param("s", $hostname);
$stmt->execute();
$res = $stmt->get_result();

if ($pc = $res->fetch_assoc()) {
    $pc_id = $pc['id'];

    $up = $conn->prepare("
        UPDATE pc_clients 
        SET ip_address=?, os=?, last_seen=NOW()
        WHERE id=?
    ");
    $up->bind_param("ssi", $ip, $os, $pc_id);
    $up->execute();
} else {
    $in = $conn->prepare("
        INSERT INTO pc_clients (hostname, ip_address, os, last_seen)
        VALUES (?, ?, ?, NOW())
    ");
    $in->bind_param("sss", $hostname, $ip, $os);
    $in->execute();
    $pc_id = $conn->insert_id;
}

/* ===============================
   SAVE MONITORING
================================ */
$cpu_usage  = $cpu['usage_percent'] ?? null;
$cpu_cores  = $cpu['core_count'] ?? null;

$ram_total  = $ram['total_gb'] ?? null;
$ram_used   = $ram['used_gb'] ?? null;
$ram_percent= $ram['percent'] ?? null;

$disk_json    = json_encode($disk);
$sensors_json = json_encode($sensors);
$errors_json  = json_encode($errors);

$mon = $conn->prepare("
    INSERT INTO pc_monitoring
    (pc_client_id, cpu_usage, cpu_cores, ram_total, ram_used, ram_percent, disk, sensors, errors)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
");

$mon->bind_param(
    "ididddsss",
    $pc_id,
    $cpu_usage,
    $cpu_cores,
    $ram_total,
    $ram_used,
    $ram_percent,
    $disk_json,
    $sensors_json,
    $errors_json
);

$mon->execute();

/* ===============================
   RESPONSE
================================ */
echo json_encode([
    "status" => "ok",
    "pc_id" => $pc_id,
    "time" => date("Y-m-d H:i:s")
]);
