<?php
require_once __DIR__ . '/../../db.php';
header('Content-Type: application/json');

$data  = json_decode(file_get_contents('php://input'), true);
$group = trim($data['group_name']   ?? '');
$rdp   = trim($data['rdp_nickname'] ?? '');
$unit  = trim($data['unit_id']      ?? '');
$ip    = $data['assigned_ip']       ?? null;

if (strlen($group) < 2 || strlen($unit) < 2) {
    echo json_encode(['success' => false, 'error' => 'Invalid input']);
    exit;
}

$g = $conn->query("SELECT id FROM groups WHERE name='".$conn->real_escape_string($group)."' LIMIT 1")->fetch_assoc();
if (!$g) {
    $conn->query("INSERT INTO groups (name) VALUES ('".$conn->real_escape_string($group)."')");
    $gid = $conn->insert_id;
} else {
    $gid = $g['id'];
}

$r = $conn->query("SELECT id FROM rdps WHERE name='".$conn->real_escape_string($rdp)."' AND group_id=$gid LIMIT 1")->fetch_assoc();
if (!$r) {
    $conn->query("INSERT INTO rdps (group_id, name) VALUES ($gid, '".$conn->real_escape_string($rdp)."')");
    $rid = $conn->insert_id;
} else {
    $rid = $r['id'];
}

$stmt = $conn->prepare("
    INSERT INTO vms (unit_id, rdp_id, current_ip, status, last_heartbeat)
    VALUES (?, ?, ?, 'Offline', NULL)
    ON DUPLICATE KEY UPDATE
        current_ip     = VALUES(current_ip),
        last_heartbeat = UTC_TIMESTAMP()
");
$stmt->bind_param("sis", $unit, $rid, $ip);
$stmt->execute();

$vmId = $conn->insert_id ?: $conn->query("SELECT id FROM vms WHERE unit_id='".$conn->real_escape_string($unit)."' AND rdp_id=$rid LIMIT 1")->fetch_assoc()['id'];

echo json_encode(['success' => true, 'vm_id' => (int)$vmId]);