<?php

require_once __DIR__ . '/../lib/PveApi.php';
$cfg = require __DIR__ . '/../config/pve.php';
$pve = new PveApi($cfg);

header('Content-Type: application/json; charset=utf-8');

try {
  $lxcs = $pve->listLxc();   // array mit vmid, name, status, cpu, mem, etc.
  $vms  = $pve->listQemu();  // array mit vmid, name, status, cpu, mem, etc.

  $all = [];

  foreach ($lxcs as $c) {
    $vmid = (int)($c['vmid'] ?? 0);
    if ($vmid >= 100 && $vmid <= 199) {
      $all[] = [
        'vmid' => $vmid,
        'type' => 'lxc',
        'name' => (string)($c['name'] ?? "LXC {$vmid}"),
        'status' => (string)($c['status'] ?? 'unknown'),
        'uptime' => (int)($c['uptime'] ?? 0),
        'cpu' => (float)($c['cpu'] ?? 0),
        'mem' => (int)($c['mem'] ?? 0),
        'maxmem' => (int)($c['maxmem'] ?? 0),
      ];
    }
  }

  foreach ($vms as $v) {
    $vmid = (int)($v['vmid'] ?? 0);
    if ($vmid >= 200 && $vmid <= 299) {
      $all[] = [
        'vmid' => $vmid,
        'type' => 'qemu',
        'name' => (string)($v['name'] ?? "VM {$vmid}"),
        'status' => (string)($v['status'] ?? 'unknown'),
        'uptime' => (int)($v['uptime'] ?? 0),
        'cpu' => (float)($v['cpu'] ?? 0),
        'mem' => (int)($v['mem'] ?? 0),
        'maxmem' => (int)($v['maxmem'] ?? 0),
      ];
    }
  }

  // Sort: erst LXCs, dann VMs oder nach vmid
  usort($all, fn($a, $b) => $a['vmid'] <=> $b['vmid']);

  echo json_encode(['ok' => true, 'items' => $all], JSON_UNESCAPED_UNICODE);

} catch (Throwable $e) {
  http_response_code(400);
  echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
}
