<?php
require_once 'db.php';

date_default_timezone_set('Asia/Kolkata');

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

 $week_start  = date('Y-m-d', strtotime('monday this week'));
 $month_start = date('Y-m-01');

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

 $today_total = (float)$conn->query("
SELECT IFNULL(SUM(GREATEST(0,t.t - IFNULL(y.y,0))),0) v
FROM (SELECT vm_id, MAX(balance) t FROM earnapp_history WHERE DATE(recorded_at)=CURDATE() GROUP BY vm_id) t
LEFT JOIN (SELECT vm_id, MAX(balance) y FROM earnapp_history WHERE DATE(recorded_at)=CURDATE()-INTERVAL 1 DAY GROUP BY vm_id) y
ON y.vm_id=t.vm_id
")->fetch_assoc()['v'];

$week_total = (float)$conn->query("
SELECT IFNULL(SUM(
    GREATEST(0,
        w.cur - IFNULL(p.prev,0)
    )
),0) v
FROM
(
    SELECT vm_id, MAX(balance) cur
    FROM earnapp_history
    WHERE DATE(recorded_at) >= '$week_start'
    GROUP BY vm_id
) w
LEFT JOIN
(
    SELECT vm_id, MAX(balance) prev
    FROM earnapp_history
    WHERE DATE(recorded_at) < '$week_start'
    GROUP BY vm_id
) p ON p.vm_id = w.vm_id
")->fetch_assoc()['v'];

$month_total = (float)$conn->query("
SELECT IFNULL(SUM(
    GREATEST(0,
        m.cur - IFNULL(p.prev,0)
    )
),0) v
FROM
(
    SELECT vm_id, MAX(balance) cur
    FROM earnapp_history
    WHERE DATE(recorded_at) >= '$month_start'
    GROUP BY vm_id
) m
LEFT JOIN
(
    SELECT vm_id, MAX(balance) prev
    FROM earnapp_history
    WHERE DATE(recorded_at) < '$month_start'
    GROUP BY vm_id
) p ON p.vm_id = m.vm_id
")->fetch_assoc()['v'];

 $lifetime_total = (float)$conn->query("
SELECT IFNULL(SUM(balance),0) v
FROM (
    SELECT vm_id, MAX(balance) balance
    FROM earnapp_history
    GROUP BY vm_id
) x
")->fetch_assoc()['v'];

 $earnings = [
    'lifetime' => $lifetime_total,
    'today'    => $today_total,
    'week'     => $week_total,
    'month'    => $month_total
];

 $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
FROM earnapp_history
GROUP BY vm_id
");

 $daily=[];
while($r=$growthQ->fetch_assoc()){
    $daily[$r['d']] = ($daily[$r['d']] ?? 0) + 1;
}
ksort($daily);

 $gLabels=[];$gData=[];$total=0;
foreach($daily as $d=>$c){
    $total+=$c;
    $gLabels[]=$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>

<!-- FIX 3: Updated Table with Correct Group Calculations and Month Column -->
<table class="table-dark">
<thead>
<tr>
<th>GROUP</th><th>VMS</th><th>TODAY</th><th>THIS WEEK</th><th>THIS MONTH</th><th>LIFETIME</th>
</tr>
</thead>
<tbody>
<?php
// --- FIX 3: Complete rewrite of group statistics calculation ---
 $group_stats = [];
 $vm_map = [];

// 1. Map all VMs to their groups
 $q_vms = $conn->query("SELECT id, vm_id, group_name FROM vms WHERE group_name IS NOT NULL AND group_name != ''");
if ($q_vms) {
    while ($row = $q_vms->fetch_assoc()) {
        $gn = trim((string)($row['group_name']));
        $id = trim((string)($row['id']));
        $vmid = trim((string)($row['vm_id']));

        if (!isset($group_stats[$gn])) {
            $group_stats[$gn] = ['vms' => 0, 'today' => 0, 'week' => 0, 'month' => 0, 'lifetime' => 0];
        }
        $group_stats[$gn]['vms']++;
        if ($id) $vm_map[$id] = $gn;
        if ($vmid) $vm_map[$vmid] = $gn;
    }
}

// 2. Get lifetime earnings for each VM and add to its group
 $q_lifetime = $conn->query("SELECT vm_id, MAX(balance) as balance FROM earnapp_history GROUP BY vm_id");
if ($q_lifetime) {
    while ($r = $q_lifetime->fetch_assoc()) {
        $vid = trim((string)$r['vm_id']);
        if (isset($vm_map[$vid])) {
            $group_stats[$vm_map[$vid]]['lifetime'] += (float)$r['balance'];
        }
    }
}

// 3. Get today's earnings for each VM and add to its group
 $q_today = $conn->query("
    SELECT t.vm_id, GREATEST(0, t.t - IFNULL(y.y, 0)) as v 
    FROM (SELECT vm_id, MAX(balance) t FROM earnapp_history WHERE DATE(recorded_at) = CURDATE() GROUP BY vm_id) t
    LEFT JOIN (SELECT vm_id, MAX(balance) y FROM earnapp_history WHERE DATE(recorded_at) = CURDATE() - INTERVAL 1 DAY GROUP BY vm_id) y ON y.vm_id = t.vm_id
");
if ($q_today) {
    while ($r = $q_today->fetch_assoc()) {
        $vid = trim((string)$r['vm_id']);
        if (isset($vm_map[$vid])) {
            $group_stats[$vm_map[$vid]]['today'] += (float)$r['v'];
        }
    }
}

// 4. Get this week's earnings for each VM and add to its group
 $q_week = $conn->query("
    SELECT x.vm_id, SUM(GREATEST(0, x.daily_earnings)) as v 
    FROM (
        SELECT 
            h.vm_id,
            DATE(h.recorded_at) as day,
            MAX(h.balance) - COALESCE(
                (SELECT MAX(balance) FROM earnapp_history WHERE vm_id = h.vm_id AND DATE(recorded_at) = DATE(h.recorded_at) - INTERVAL 1 DAY), 0
            ) as daily_earnings
        FROM earnapp_history h
        WHERE DATE(h.recorded_at) >= '$week_start'
        GROUP BY DATE(h.recorded_at), h.vm_id
    ) x
    WHERE x.daily_earnings > 0
    GROUP BY x.vm_id
");
if ($q_week) {
    while ($r = $q_week->fetch_assoc()) {
        $vid = trim((string)$r['vm_id']);
        if (isset($vm_map[$vid])) {
            $group_stats[$vm_map[$vid]]['week'] += (float)$r['v'];
        }
    }
}

// 5. Get this month's earnings for each VM and add to its group
 $q_month = $conn->query("
    SELECT x.vm_id, SUM(GREATEST(0, x.daily_earnings)) as v 
    FROM (
        SELECT 
            h.vm_id,
            DATE(h.recorded_at) as day,
            MAX(h.balance) - COALESCE(
                (SELECT MAX(balance) FROM earnapp_history WHERE vm_id = h.vm_id AND DATE(recorded_at) = DATE(h.recorded_at) - INTERVAL 1 DAY), 0
            ) as daily_earnings
        FROM earnapp_history h
        WHERE DATE(h.recorded_at) >= '$month_start'
        GROUP BY DATE(h.recorded_at), h.vm_id
    ) x
    WHERE x.daily_earnings > 0
    GROUP BY x.vm_id
");
if ($q_month) {
    while ($r = $q_month->fetch_assoc()) {
        $vid = trim((string)$r['vm_id']);
        if (isset($vm_map[$vid])) {
            $group_stats[$vm_map[$vid]]['month'] += (float)$r['v'];
        }
    }
}

// 6. Render the table rows
foreach ($group_stats as $gn => $st):
?>
<tr>
<td><?= htmlspecialchars($gn) ?></td>
<td><?= $st['vms'] ?></td>
<td class="green">$<?= nf($st['today']) ?></td>
<td class="green">$<?= nf($st['week']) ?></td>
<td class="green">$<?= nf($st['month']) ?></td>
<td class="green">$<?= nf($st['lifetime']) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>

<br>
 
</div>