<?php
file_put_contents('/home/bdmaco/public_html/earnapp/debug.log', date('H:i:s') . ' - POST: ' . file_get_contents('php://input') . "\n", FILE_APPEND);
ini_set('display_errors', 1);
error_reporting(E_ALL);
header('Content-Type: application/json');
require_once __DIR__ . '/db.php';

$json = file_get_contents('php://input');
$data = json_decode($json, true);

if (!$data || empty($data['vm_id'])) {
    echo json_encode(["status" => "error", "msg" => "vm_id missing"]);
    exit;
}

$vmId  = (int)$data['vm_id'];
$group = trim($data['group_name'] ?? '');
$rdp   = trim($data['rdp_nickname'] ?? '');
$bal = (isset($data['balance']) && $data['balance'] !== null && $data['balance'] !== '') 
    ? (float)preg_replace('/[^0-9.]/', '', (string)$data['balance']) 
    : null;
$trafRaw = $data['traffic'] ?? '0';
$traf = (float)preg_replace('/[^0-9.]/', '', $trafRaw);
$stat = trim($data['status'] ?? '');

$allowed = ['Running','Blocked','Paused','Connecting','Offline'];

if (!in_array($stat, $allowed, true)) {
    $stat = null;
}

if ($stat === 'Connecting') {
    $stat = 'Offline';
}

$token = $data['earnapp_token'] ?? null;
$ip    = $data['ip_address'] ?? $_SERVER['REMOTE_ADDR'];
$isHeartbeat = isset($data['action']) && $data['action'] === 'heartbeat';

$chk = $conn->prepare("SELECT last_heartbeat FROM vms WHERE id = ? LIMIT 1");
$chk->bind_param("i", $vmId);
$chk->execute();
$chk->bind_result($lastHeartbeat);
$exists = $chk->fetch();
$chk->close();

if (!$exists) {
    echo json_encode(["status" => "error", "msg" => "VM not registered"]);
    exit;
}

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

$updates[] = "current_ip = ?";
$params[] = $ip;
$types .= 's';

$updates[] = "last_heartbeat = NOW()";


if (!$isHeartbeat) {
  
    $updates[] = "traffic = ?";
    $params[] = $traf;
    $types .= 'd';

    if ($token !== null) {
        $updates[] = "earnapp_token = ?";
        $params[] = $token;
        $types .= 's';
    }

    // Connecting ko overwrite avoid kar rahe hain (transient hota hai)
    if ($stat !== null && $stat !== 'Connecting' && $stat !== 'Unknown') {
        $updates[] = "status = ?";
        $params[] = $stat;
        $types .= 's';
    }

    if ($bal !== null) {
        $updates[] = "balance = ?";
        $params[] = $bal;
        $types .= 'd';
    }
}

$sql = "UPDATE vms SET " . implode(", ", $updates) . " WHERE id = ?";
$params[] = $vmId;
$types .= 'i';

$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);

if ($stmt->execute()) {

    if (!$isHeartbeat) {

        if ($stat === 'Running' || $stat === 'Blocked') {

            $ins = $conn->prepare("
                INSERT INTO earnapp_history
                (vm_id, group_name, rdp_nickname, balance, ip_address, earnapp_token, status)
                VALUES (?,?,?,?,?,?,?)
                ON DUPLICATE KEY UPDATE
                    balance = VALUES(balance),
                    status = VALUES(status),
                    ip_address = VALUES(ip_address)
            ");
            $balHist = $bal !== null ? (string)$bal : '0';
            $ins->bind_param("issssss", $vmId, $group, $rdp, $balHist, $ip, $token, $stat);
            $ins->execute();
            $ins->close();
        }

        echo json_encode(["status" => "success"]);
    } else {
        echo json_encode(["status" => "success"]);
    }
}

$stmt->close();
$conn->close();