<?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 = ["current_ip = ?", "last_heartbeat = NOW()"];
$params = [$ip];
$types = 's';

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

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

    if ($stat !== null && $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 && ($stat === 'Running' || $stat === 'Blocked')) {
        date_default_timezone_set('Asia/Kolkata');
        $earningDate = date('Y-m-d');
        
        $ins = $conn->prepare("
            INSERT INTO earnapp_history
            (vm_id, earning_date, 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),
                recorded_at = CURRENT_TIMESTAMP
        ");
    
        $balHist = $bal !== null ? (string)$bal : '0';
        $ins->bind_param("isssssss", $vmId, $earningDate, $group, $rdp, $balHist, $ip, $token, $stat);
        $ins->execute();
        $ins->close();
    }

    echo json_encode(["status" => "success"]);
} else {
    echo json_encode(["status" => "error", "msg" => "Database update failed"]);
}

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