<?php
require_once __DIR__ . '/../../db.php';

$raw  = file_get_contents('php://input');
$json = json_decode($raw, true);
$data = is_array($json) ? $json : $_POST;

if (($data['action'] ?? '') === 'heartbeat') {

    $vm_id             = (int)($data['vm_id']             ?? 0);
    $earnapp_running   = (int)($data['earnapp_running']   ?? 0);
    $earnapp_autostart = (int)($data['earnapp_autostart'] ?? 0);
    $earnapp_paused    = (int)($data['earnapp_paused']    ?? 0);
    $current_ip        = $data['current_ip'] ?? '';

    if ($vm_id <= 0) {
        echo json_encode(['success' => false]);
        exit;
    }

    $stmt = $conn->prepare("
        UPDATE vms SET
            earnapp_running   = ?,
            earnapp_autostart = ?,
            earnapp_paused    = ?,
            current_ip        = ?,
            last_heartbeat    = NOW()
        WHERE id = ?
    ");
    $stmt->bind_param("iiisi", $earnapp_running, $earnapp_autostart, $earnapp_paused, $current_ip, $vm_id);
    $stmt->execute();
    $stmt->close();

    echo json_encode(['success' => true]);
    exit;
}

if (($data['action'] ?? '') === 'load_all') {

    $groups = [];
    $gq = $conn->query("SELECT * FROM `groups` ORDER BY id");

    while ($g = $gq->fetch_assoc()) {
        $g['rdps'] = [];

        $rq = $conn->prepare("SELECT * FROM rdps WHERE group_id = ?");
        $rq->bind_param("i", $g['id']);
        $rq->execute();
        $rId = null; $rName = null; $rGid = null;

        // fetch all rdp rows manually
        $rdpRows = [];
        $rq->bind_result($rId, $rName, $rGid);
        while ($rq->fetch()) {
            $rdpRows[] = ['id' => $rId, 'name' => $rName, 'group_id' => $rGid, 'vms' => []];
        }
        $rq->close();

        foreach ($rdpRows as &$rdpRow) {
            $vq = $conn->prepare("
                SELECT id, unit_id, rdp_id,
                    CAST(earnapp_running   AS UNSIGNED) AS earnapp_running,
                    CAST(earnapp_autostart AS UNSIGNED) AS earnapp_autostart,
                    CAST(earnapp_paused    AS UNSIGNED) AS earnapp_paused,
                    current_ip, last_heartbeat, balance
                FROM vms WHERE rdp_id = ?
            ");
            $vq->bind_param("i", $rdpRow['id']);
            $vq->execute();
            $vId = null; $vUnit = null; $vRdpId = null;
            $vRunning = null; $vAutostart = null; $vPaused = null;
            $vIp = null; $vHb = null; $vBal = null;
            $vq->bind_result($vId, $vUnit, $vRdpId, $vRunning, $vAutostart, $vPaused, $vIp, $vHb, $vBal);
            while ($vq->fetch()) {
                $rdpRow['vms'][] = [
                    'id'                => $vId,
                    'unit_id'           => $vUnit,
                    'rdp_id'            => $vRdpId,
                    'earnapp_running'   => $vRunning,
                    'earnapp_autostart' => $vAutostart,
                    'earnapp_paused'    => $vPaused,
                    'current_ip'        => $vIp,
                    'last_heartbeat'    => $vHb,
                    'balance'           => $vBal,
                ];
            }
            $vq->close();
        }
        unset($rdpRow);

        $g['rdps']  = $rdpRows;
        $groups[]   = $g;
    }

    echo json_encode([
        'success' => true,
        'data'    => [
            'data'        => $groups,
            'server_time' => date('Y-m-d H:i:s'),
        ],
    ]);
    exit;
}

echo json_encode(['success' => false, 'msg' => 'Unknown action']);
?>