<?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();
        $rResult = $rq->get_result();

        while ($r = $rResult->fetch_assoc()) {

            $r['vms'] = [];

            $vq = $conn->prepare("
                SELECT
                    id,
                    name,
                    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", $r['id']);
            $vq->execute();
            $vResult = $vq->get_result();

            while ($v = $vResult->fetch_assoc()) {
                $r['vms'][] = $v;
            }

            $g['rdps'][] = $r;
        }

        $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']);