<?php
if (!isset($conn)) {
    die('DB connection missing');
}

 
$res = $conn->query("SELECT COUNT(*) AS c FROM vms");
$stats['total_vms'] = (int)$res->fetch_assoc()['c'];

 
$res = $conn->query("
    SELECT COUNT(*) AS c
    FROM vms
    WHERE last_heartbeat IS NOT NULL
      AND last_heartbeat >= NOW() - INTERVAL 5 MINUTE
");
$stats['online_vms'] = (int)$res->fetch_assoc()['c'];

/* APP RUNNING (earnapp status only) */
$res = $conn->query("
    SELECT COUNT(*) AS c
    FROM vms
    WHERE LOWER(status) LIKE '%running%'
");
$stats['app_online'] = (int)$res->fetch_assoc()['c'];

/* TODAY EARNING */
$res = $conn->query("
    SELECT IFNULL(SUM(earning),0) AS total
    FROM vm_earnings
    WHERE date = CURDATE()
");
$stats['earning_today'] = (float)$res->fetch_assoc()['total'];

$res = $conn->query("
    SELECT IFNULL(SUM(earning),0) AS total
    FROM vm_earnings
    WHERE date = CURDATE() - INTERVAL 1 DAY
");
$stats['earning_yesterday'] = (float)$res->fetch_assoc()['total'];

/* MONTH EARNING */
$res = $conn->query("
    SELECT IFNULL(SUM(earning),0) AS total
    FROM vm_earnings
    WHERE YEAR(date)=YEAR(CURDATE())
      AND MONTH(date)=MONTH(CURDATE())
");
$stats['earning_month'] = (float)$res->fetch_assoc()['total'];

/* CURRENT BALANCE */
$res = $conn->query("SELECT IFNULL(SUM(balance),0) AS total FROM vms");
$total_lifetime = (float)$res->fetch_assoc()['total'];
?>

<div class="row mb-4 flex-nowrap">
    <div class="col">
        <div class="card bg-dark text-white p-3 border-danger text-center">
            <h6>Total VMs</h6>
            <h3><?= $stats['total_vms'] ?></h3>
        </div>
    </div>

    <div class="col">
        <div class="card bg-dark text-white p-3 border-success text-center">
            <h6>Online</h6>
            <h3><?= $stats['online_vms'] ?></h3>
        </div>
    </div>

    <div class="col">
        <div class="card bg-dark text-white p-3 border-success text-center">
            <h6>App Online</h6>
            <h3><?= $stats['app_online'] ?></h3>
        </div>
    </div>

    <div class="col">
        <div class="card bg-dark text-white p-3 border-warning text-center">
            <h6>Today</h6>
            <h3>$<?= number_format($stats['earning_today'],2) ?></h3>
        </div>
    </div>

    <div class="col">
        <div class="card bg-dark text-white p-3 border-secondary text-center">
            <h6>Yesterday</h6>
            <h3>$<?= number_format($stats['earning_yesterday'],2) ?></h3>
        </div>
    </div>

    <div class="col">
        <div class="card bg-dark text-white p-3 border-info text-center">
            <h6>This Month</h6>
            <h3>$<?= number_format($stats['earning_month'],2) ?></h3>
        </div>
    </div>

    <div class="col">
        <div class="card bg-dark text-white p-3 border-info text-center">
            <h6>Current Balance</h6>
            <h3>$<?= number_format($total_lifetime,2) ?></h3>
        </div>
    </div>
</div>

