<?php
require_once __DIR__ . '/../../../db.php';

$vm_id = (int)basename($_SERVER['REQUEST_URI']);
$input = json_decode(file_get_contents('php://input'), true);

if (!$vm_id) {
    http_response_code(400);
    echo json_encode(['success' => false]);
    exit;
}

$ip      = $input['current_ip'] ?? null;
$running = (int)($input['earnapp_running']   ?? 0);
$auto    = (int)($input['earnapp_autostart'] ?? 0);
$paused  = (int)($input['earnapp_paused']    ?? 0);
$balance = (float)($input['balance'] ?? 0);

$ipEsc = $ip ? "'" . $conn->real_escape_string($ip) . "'" : "NULL";

$conn->query("
    UPDATE vms SET
        current_ip        = $ipEsc,
        earnapp_running   = $running,
        earnapp_autostart = $auto,
        earnapp_paused    = $paused,
        balance           = $balance,
        last_heartbeat    = NOW()
    WHERE id = $vm_id
");

@file_put_contents(
    __DIR__ . '/../../../runtime/live_' . $vm_id . '.json',
    json_encode([
        'current_ip'        => $ip,
        'earnapp_running'   => $running,
        'earnapp_autostart' => $auto,
        'earnapp_paused'    => $paused,
        'balance'           => $balance,
        'last_seen'         => time(),
    ])
);

echo json_encode(['success' => true]);