<?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;
$token = trim($data['earnapp_token'] ?? '');

if (strlen($group) < 2 || strlen($unit) < 2 || $unit === 'DefaultUnit' || $group === 'Default') {
    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 = (int)$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 = (int)$r['id'];
}

// Check duplicate unit_id
$dupCheck = $conn->prepare("SELECT id, rdp_id, status FROM vms WHERE unit_id = ? LIMIT 1");
$dupCheck->bind_param("s", $unit);
$dupCheck->execute();
$existId  = null; $existRdp = null; $existStat = null;
$dupCheck->bind_result($existId, $existRdp, $existStat);
$dupFound = $dupCheck->fetch();
$dupCheck->close();

if ($dupFound && $existId) {
    $existingId  = (int)$existId;
    $existingRdp = (int)$existRdp;

    if ($existingRdp !== $rid) {
        $conn->query("INSERT INTO vm_commands (vm_id, command, status, created_at) VALUES ($existingId, 'stop_agent', 'pending', NOW())");
        $upd = $conn->prepare("UPDATE vms SET rdp_id=?, group_name=?, rdp_nickname=?, current_ip=?, status='Offline', last_heartbeat=NOW(), duplicate_of=? WHERE id=?");
        $upd->bind_param("isssii", $rid, $group, $rdp, $ip, $existingRdp, $existingId);
        $upd->execute();
        $upd->close();
        echo json_encode(['success' => true, 'vm_id' => $existingId, 'bridged' => true, 'note' => 'Agent moved to new group/rdp']);
        exit;
    }

    $upd = $conn->prepare("UPDATE vms SET current_ip=?, status='Offline', last_heartbeat=NOW(), group_name=?, rdp_nickname=? WHERE id=?");
    $upd->bind_param("sssi", $ip, $group, $rdp, $existingId);
    $upd->execute();
    $upd->close();
    echo json_encode(['success' => true, 'vm_id' => $existingId]);
    exit;
}

// Check duplicate token
if (!empty($token)) {
    $tokenCheck = $conn->prepare("SELECT id FROM vms WHERE earnapp_token = ? AND unit_id != ? LIMIT 1");
    $tokenCheck->bind_param("ss", $token, $unit);
    $tokenCheck->execute();
    $conflictId = null;
    $tokenCheck->bind_result($conflictId);
    if ($tokenCheck->fetch() && $conflictId) {
        $conn->query("UPDATE vms SET earnapp_token=NULL, status='Offline' WHERE id=" . (int)$conflictId);
        $conn->query("INSERT INTO vm_commands (vm_id, command, status, created_at) VALUES (" . (int)$conflictId . ", 'stop_agent', 'pending', NOW())");
    }
    $tokenCheck->close();
}

$stmt = $conn->prepare("INSERT INTO vms (unit_id, rdp_id, group_id, group_name, rdp_nickname, current_ip, status, last_heartbeat) VALUES (?, ?, ?, ?, ?, ?, 'Offline', NULL)");
$stmt->bind_param("siisss", $unit, $rid, $gid, $group, $rdp, $ip);
$stmt->execute();
$vmId = $conn->insert_id;
$stmt->close();

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