<?php
// public_html/earnapp/api/vm/command.php
require_once __DIR__ . '/../../db.php';
header('Content-Type: application/json');

$vmId = (int)basename($_SERVER['PATH_INFO'] ?? 0);
if (!$vmId) { echo json_encode(['commands'=>[]]); exit; }

$q = $conn->query("SELECT id, command FROM command_logs WHERE vm_id=$vmId AND status='pending' ORDER BY id ASC");
$cmds = [];
$ids = [];

while ($r = $q->fetch_assoc()) {
    $cmds[] = $r;
    $ids[] = $r['id'];
}

if ($ids) {
    $conn->query("UPDATE command_logs SET status='sent' WHERE id IN (".implode(',',$ids).")");
}

echo json_encode(['commands'=>$cmds]);
