<?php
require_once 'db.php';

function nf($v,$d=2){ return number_format((float)($v ?? 0),$d); }

$stats = $conn->query("
SELECT
COUNT(*) total,
SUM(last_heartbeat >= DATE_SUB(NOW(), INTERVAL 5 MINUTE)) online,
SUM(last_heartbeat < DATE_SUB(NOW(), INTERVAL 5 MINUTE) OR last_heartbeat IS NULL) offline,
SUM(LOWER(status) IN ('blocked','anomaly')) anomalies
FROM vms
")->fetch_assoc();

$stats['pending'] = (int)$stats['offline'];

$life  = $conn->query("SELECT IFNULL(SUM(earning),0) v FROM vm_earnings")->fetch_assoc();
$today = $conn->query("SELECT IFNULL(SUM(earning),0) v FROM vm_earnings WHERE DATE(date)=CURDATE()")->fetch_assoc();
$week  = $conn->query("SELECT IFNULL(SUM(earning),0) v FROM vm_earnings WHERE date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)")->fetch_assoc();
$month = $conn->query("SELECT IFNULL(SUM(earning),0) v FROM vm_earnings WHERE date >= DATE_FORMAT(CURDATE(),'%Y-%m-01')")->fetch_assoc();

$earnings = [
    'lifetime' => (float)$life['v'],
    'today'    => (float)$today['v'],
    'week'     => (float)$week['v'],
    'month'    => (float)$month['v']
];

$ipStats = $conn->query("
SELECT
SUM(LOWER(status) NOT IN ('blocked','anomaly') AND last_heartbeat >= DATE_SUB(NOW(), INTERVAL 5 MINUTE)) ok_ips,
SUM(LOWER(status) IN ('blocked','anomaly')) blocked_ips
FROM vms
")->fetch_assoc();

$trendQ = $conn->query("
SELECT DATE(recorded_at) d,
SUM(
    GREATEST(
        balance - IFNULL(
            (
                SELECT balance
                FROM earnapp_history h1
                WHERE h1.vm_id = h2.vm_id
                AND h1.recorded_at < h2.recorded_at
                ORDER BY h1.recorded_at DESC
                LIMIT 1
            ),0
        ),0
    )
) v
FROM earnapp_history h2
WHERE recorded_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
GROUP BY DATE(recorded_at)
ORDER BY d
");

$trendLabels=[];$trendData=[];
while($r=$trendQ->fetch_assoc()){ $trendLabels[]=$r['d']; $trendData[]=(float)$r['v']; }

$growthQ = $conn->query("
SELECT DATE(MIN(recorded_at)) d, vm_id
FROM earnapp_history
GROUP BY vm_id
ORDER BY d
");

$gLabels = [];
$gData   = [];
$total   = 0;
$daily   = [];

while($r = $growthQ->fetch_assoc()){
    $day = $r['d'];
    if(!isset($daily[$day])) $daily[$day] = 0;
    $daily[$day]++;
}

ksort($daily);
foreach($daily as $d => $c){
    $total += $c;
    $gLabels[] = $d;
    $gData[]   = $total;
}

$gLabels=[];$gData=[];$total=0;
while($r=$growthQ->fetch_assoc()){
    $total += (int)$r['c'];
    $gLabels[] = $r['d'];
    $gData[]   = $total;
}

$groupQ = $conn->query("
SELECT group_name, COUNT(*) c
FROM vms
WHERE group_name IS NOT NULL AND group_name != ''
GROUP BY group_name
");
$groupLabels=[];$groupData=[];
while($g=$groupQ->fetch_assoc()){ $groupLabels[]=$g['group_name']; $groupData[]=$g['c']; }
?>

<script>
document.addEventListener('DOMContentLoaded', () => {

Chart.defaults.maintainAspectRatio = false;

const get = id => document.getElementById(id);

if(get('statusChart')){
new Chart(get('statusChart').getContext('2d'),{
    type:'doughnut',
    data:{
        labels:['Online','Pending','Anomaly'],
        datasets:[{
            data:[<?= $stats['online']?>,<?= $stats['pending']?>,<?= $stats['anomalies']?>],
            backgroundColor:['#00ff4c','#888','#ff2b2b'],
            cutout:'70%'
        }]
    },
    options:{plugins:{legend:{position:'bottom'}}}
});
}

if(get('earningsTrend')){
new Chart(get('earningsTrend').getContext('2d'),{
    type:'line',
    data:{
        labels:<?= json_encode($trendLabels) ?>,
        datasets:[{
            label:'RDP Earnings',
            data:<?= json_encode($trendData) ?>,
            borderColor:'#f5c542',
            backgroundColor:'rgba(245,197,66,.15)',
            pointRadius:4,
            pointHoverRadius:6,
            fill:true,
            tension:0.4
        }]
    },
    options:{
        plugins:{
            legend:{display:true}
        },
        scales:{
            x:{grid:{color:'#222'}},
            y:{grid:{color:'#222'}, beginAtZero:true}
        }
    }
});

}

if(get('vmGrowth')){
new Chart(get('vmGrowth').getContext('2d'),{
    type:'line',
    data:{
        labels:<?= json_encode($gLabels) ?>,
        datasets:[{
            label:'Total VMs',
            data:<?= json_encode($gData) ?>,
            borderColor:'#ff2b2b',
            backgroundColor:'rgba(255,0,0,.25)',
            fill:true,
            tension:.35
        }]
    },
    options:{plugins:{legend:{display:true}}}
});
}

if(get('groupBar')){
new Chart(get('groupBar').getContext('2d'),{
    type:'bar',
    data:{
        labels:<?= json_encode($groupLabels) ?>,
        datasets:[{
            data:<?= json_encode($groupData) ?>,
            backgroundColor:'#00ff4c'
        }]
    },
    options:{indexAxis:'y',plugins:{legend:{display:false}}}
});
}

if(get('ipStatusChart')){
new Chart(get('ipStatusChart').getContext('2d'),{
    type:'doughnut',
    data:{
        labels:['OK','Blocked'],
        datasets:[{
            data:[<?= $ipStats['ok_ips']?>,<?= $ipStats['blocked_ips']?>],
            backgroundColor:['#00ff4c','#ff2b2b'],
            cutout:'75%'
        }]
    },
    options:{plugins:{legend:{position:'bottom'}}}
});
}

if(get('alertsChart')){
new Chart(get('alertsChart').getContext('2d'),{
    type:'bar',
    data:{
        labels:['Pending','Anomaly'],
        datasets:[{
            data:[<?= $stats['pending']?>,<?= $stats['anomalies']?>],
            backgroundColor:['#888','#ff2b2b']
        }]
    },
    options:{plugins:{legend:{display:false}},scales:{y:{beginAtZero:true}}}
});
}
const statsWrap = document.getElementById('top-stats-wrapper');
if (statsWrap) {
    const cardCount = statsWrap.children.length;

    document.querySelectorAll('.chart, .chart-box').forEach(el => {
        el.style.marginTop = cardCount > 5 ? '20px' : '0';
    });
}
});
</script>



<style>
body{background:#000;color:#eee;font-family:Inter}
.card{background:#0b0b0b;border:1px solid #2a0000;border-radius:10px;padding:15px}
.stat{font-size:22px;font-weight:800}
.label{font-size:11px;color:#888}
.green{color:#00ff4c}
.red{color:#ff2b2b}
.yellow{color:#ffb300}
.grid{display:grid;grid-template-columns:repeat(5,1fr);gap:15px}
.chart{background:#0b0b0b;border:1px solid #2a0000;border-radius:10px;padding:15px}
table{width:100%;border-collapse:collapse}
th,td{padding:10px;border-bottom:1px solid #1a1a1a;font-size:12px}
.badge{padding:3px 8px;border-radius:6px;font-size:10px}
.dashboard-row {
    display:grid;
    grid-template-columns:1fr 1fr;
    gap:20px;
    margin-bottom:30px;
}

.chart {
    height:320px;
}

.chart-box {
    background:#050505;
    border:1px solid #2a0000;
    border-radius:12px;
    padding:20px;
    height:360px;
}

.chart-box h4 {
    font-size:14px;
    margin-bottom:10px;
    color:#bbb;
    display:flex;
    align-items:center;
    gap:6px;
}

.chart-box canvas {
    width:100% !important;
    height:280px !important;
}

.lifetime-box {
    background:#050505;
    border:1px solid #2a0000;
    border-radius:14px;
    padding:20px;
    margin-top:30px;
}

.stat-cards {
    display:grid;
    grid-template-columns:repeat(4,1fr);
    gap:16px;
    margin-bottom:20px;
}

.stat-card {
    background:#0b0b0b;
    border:1px solid #2a0000;
    border-radius:12px;
    padding:16px;
    display:flex;
    align-items:center;
    gap:14px;
}

.stat-card .value {
    font-size:22px;
    font-weight:700;
}

.table-dark {
    width:100%;
    border-collapse:collapse;
}

.table-dark th,
.table-dark td {
    padding:10px;
    border-bottom:1px solid #1a0000;
    font-size:13px;
}

.green { color:#00ff4c }
.red { color:#ff2b2b }
</style>

<div class="container-fluid p-4">
<div id="top-stats-wrapper">
    <?php include __DIR__ . '/../parts/vm_top_stats.php'; ?>
</div>

<br>

<div class="grid">
<div class="card"><div class="label">TOTAL EARNINGS</div><div class="stat green">$<?= nf($earnings['lifetime']) ?></div></div>
<div class="card"><div class="label">TODAY</div><div class="stat green">$<?= nf($earnings['today']) ?></div></div>

<div class="card"><div class="label">THIS MONTH</div><div class="stat green">$<?= nf($earnings['month']) ?></div></div>
<div class="card"><div class="label">LIFETIME</div><div class="stat green">$<?= nf($earnings['lifetime']) ?></div></div>
<div class="card"><div class="label">BLOCKED IPS</div><div class="stat red"><?= $stats['anomalies'] ?></div></div>
</div>

<br>

<div class="grid" style="grid-template-columns:1fr 2fr">
<div class="chart"><canvas id="statusChart"></canvas></div>
<div class="chart"><canvas id="earningsTrend"></canvas></div>
</div>

<br>

<div class="grid" style="grid-template-columns:1fr 1fr">
<div class="chart"><canvas id="vmGrowth"></canvas></div>
<div class="chart"><canvas id="groupBar"></canvas></div>
</div>

<br>

<div class="dashboard-row">
    <div class="chart-box">
        <h4>IP Status Overview</h4>
        <canvas id="ipStatusChart"></canvas>
    </div>
    <div class="chart-box">
        <h4>Alerts by Type</h4>
        <canvas id="alertsChart"></canvas>
    </div>
</div>

<div class="lifetime-box">
<h4>Lifetime Earnings Overview</h4>

<div class="stat-cards">
<div class="stat-card"><div><small>Total Lifetime</small><div class="value red">$<?= nf($earnings['lifetime']) ?></div></div></div>
<div class="stat-card"><div><small>Today</small><div class="value green">$<?= nf($earnings['today']) ?></div></div></div>
<div class="stat-card"><div><small>This Week</small><div class="value green">$<?= nf($earnings['week']) ?></div></div></div>
<div class="stat-card"><div><small>This Month</small><div class="value green">$<?= nf($earnings['month']) ?></div></div></div>
</div>

<table class="table-dark">
<thead>
<tr>
<th>GROUP</th><th>VMS</th><th>TODAY</th><th>THIS WEEK</th><th>LIFETIME</th>
</tr>
</thead>
<tbody>
<?php
$groups = $conn->query("SELECT group_name, COUNT(*) vms, SUM(balance) life FROM vms GROUP BY group_name");
while($g = $groups->fetch_assoc()):
?>
<tr>
<td><?= $g['group_name'] ?></td>
<td><?= $g['vms'] ?></td>
<td class="green">$0.00</td>
<td class="green">$0.00</td>
<td class="green">$<?= nf($g['life']) ?></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>

<br>
 
</div> 

 