<?php
if (!function_exists('isSuperAdmin')) { require_once __DIR__ . '/../db.php'; }

date_default_timezone_set('Asia/Kolkata');
$conn->query("SET time_zone = '+05:30'");

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

$vmData   = getVmData($conn);
$gidList  = $vmData['gidList'];
$vmIdList = $vmData['vmIdList'];
$tokList  = $vmData['tokenList'];

$week_start  = date('Y-m-d', strtotime('-6 days'));
$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 WHERE id IN ($vmIdList)
")->fetch_assoc();
$stats['pending'] = (int)$stats['offline'];

// ── Canonical earning formulas (same as dashboard.php) ──────────────────────

// TODAY: max(today) - max(yesterday) per token, summed
$today_total = (float)$conn->query("
    SELECT IFNULL(SUM(GREATEST(0, t.t - IFNULL(y.y,0))),0) v
    FROM (SELECT earnapp_token, MAX(COALESCE(redeem_balance, CAST(balance AS DECIMAL(10,4)))) t
          FROM earnapp_history WHERE DATE(recorded_at)=CURDATE() AND earnapp_token IN ($tokList) GROUP BY earnapp_token) t
    LEFT JOIN (SELECT earnapp_token, MAX(COALESCE(redeem_balance, CAST(balance AS DECIMAL(10,4)))) y
               FROM earnapp_history WHERE DATE(recorded_at)=CURDATE()-INTERVAL 1 DAY AND earnapp_token IN ($tokList) GROUP BY earnapp_token) y
    ON y.earnapp_token=t.earnapp_token
")->fetch_assoc()['v'];

// WEEK: sum of daily deltas for last 7 days
$week_total = (float)$conn->query("
    SELECT IFNULL(SUM(daily_earned),0) v FROM (
        SELECT t.earnapp_token, GREATEST(0, t.day_max - IFNULL(p.prev_day_max,0)) daily_earned
        FROM (SELECT earnapp_token, DATE(recorded_at) dt, MAX(COALESCE(redeem_balance, CAST(balance AS DECIMAL(10,4)))) day_max
              FROM earnapp_history WHERE DATE(recorded_at) BETWEEN '$week_start' AND CURDATE() AND earnapp_token IN ($tokList)
              GROUP BY earnapp_token, DATE(recorded_at)) t
        LEFT JOIN (SELECT earnapp_token, DATE(recorded_at) dt, MAX(COALESCE(redeem_balance, CAST(balance AS DECIMAL(10,4)))) prev_day_max
                   FROM earnapp_history WHERE earnapp_token IN ($tokList)
                   GROUP BY earnapp_token, DATE(recorded_at)) p
        ON p.earnapp_token=t.earnapp_token AND p.dt=DATE_SUB(t.dt, INTERVAL 1 DAY)
    ) x
")->fetch_assoc()['v'];

// MONTH: sum of daily deltas for this calendar month
$month_total = (float)$conn->query("
    SELECT IFNULL(SUM(daily_earned),0) v FROM (
        SELECT t.earnapp_token, GREATEST(0, t.day_max - IFNULL(p.prev_day_max,0)) daily_earned
        FROM (SELECT earnapp_token, DATE(recorded_at) dt, MAX(COALESCE(redeem_balance, CAST(balance AS DECIMAL(10,4)))) day_max
              FROM earnapp_history WHERE DATE(recorded_at) BETWEEN '$month_start' AND CURDATE() AND earnapp_token IN ($tokList)
              GROUP BY earnapp_token, DATE(recorded_at)) t
        LEFT JOIN (SELECT earnapp_token, DATE(recorded_at) dt, MAX(COALESCE(redeem_balance, CAST(balance AS DECIMAL(10,4)))) prev_day_max
                   FROM earnapp_history WHERE earnapp_token IN ($tokList)
                   GROUP BY earnapp_token, DATE(recorded_at)) p
        ON p.earnapp_token=t.earnapp_token AND p.dt=DATE_SUB(t.dt, INTERVAL 1 DAY)
    ) x
")->fetch_assoc()['v'];

// LIFETIME: sum of ALL daily deltas ever (correct cumulative earnings)
$lifetime_total = (float)$conn->query("
    SELECT IFNULL(SUM(daily_earned),0) v FROM (
        SELECT t.earnapp_token, GREATEST(0, t.day_max - IFNULL(p.prev_day_max,0)) daily_earned
        FROM (SELECT earnapp_token, DATE(recorded_at) dt, MAX(COALESCE(redeem_balance, CAST(balance AS DECIMAL(10,4)))) day_max
              FROM earnapp_history WHERE earnapp_token IN ($tokList)
              GROUP BY earnapp_token, DATE(recorded_at)) t
        LEFT JOIN (SELECT earnapp_token, DATE(recorded_at) dt, MAX(COALESCE(redeem_balance, CAST(balance AS DECIMAL(10,4)))) prev_day_max
                   FROM earnapp_history WHERE earnapp_token IN ($tokList)
                   GROUP BY earnapp_token, DATE(recorded_at)) p
        ON p.earnapp_token=t.earnapp_token AND p.dt=DATE_SUB(t.dt, INTERVAL 1 DAY)
    ) 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 WHERE id IN ($vmIdList)
")->fetch_assoc();

// TREND: daily earnings last 7 days (day-delta method, consistent)
$trendQ = $conn->query("
    SELECT dt d, SUM(daily_earned) v FROM (
        SELECT t.earnapp_token, t.dt, GREATEST(0, t.day_max - IFNULL(p.prev_day_max,0)) daily_earned
        FROM (SELECT earnapp_token, DATE(recorded_at) dt, MAX(COALESCE(redeem_balance, CAST(balance AS DECIMAL(10,4)))) day_max
              FROM earnapp_history WHERE DATE(recorded_at) BETWEEN '$week_start' AND CURDATE() AND earnapp_token IN ($tokList)
              GROUP BY earnapp_token, DATE(recorded_at)) t
        LEFT JOIN (SELECT earnapp_token, DATE(recorded_at) dt, MAX(COALESCE(redeem_balance, CAST(balance AS DECIMAL(10,4)))) prev_day_max
                   FROM earnapp_history WHERE earnapp_token IN ($tokList)
                   GROUP BY earnapp_token, DATE(recorded_at)) p
        ON p.earnapp_token=t.earnapp_token AND p.dt=DATE_SUB(t.dt, INTERVAL 1 DAY)
    ) x GROUP BY dt ORDER BY dt
");
$trendLabels=[]; $trendData=[];
if ($trendQ) { while($r=$trendQ->fetch_assoc()){ $trendLabels[]=$r['d']; $trendData[]=(float)$r['v']; } }

$growthQ = $conn->query("SELECT DATE(MIN(recorded_at)) d FROM earnapp_history WHERE earnapp_token IN ($tokList) GROUP BY earnapp_token");
$daily=[];
if ($growthQ) { while($r=$growthQ->fetch_assoc()){ $daily[$r['d']] = ($daily[$r['d']] ?? 0) + 1; } }
ksort($daily);
$gLabels=[]; $gData=[]; $cum=0;
foreach($daily as $d=>$c){ $cum+=$c; $gLabels[]=$d; $gData[]=$cum; }

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

// ── Group stats (same canonical formulas) ───────────────────────────────────
$group_stats = [];
$vm_map = [];

$q_vms = $conn->query("SELECT id, unit_id, earnapp_token, group_name FROM vms WHERE id IN ($vmIdList) AND group_name IS NOT NULL AND group_name != ''");
if ($q_vms) {
    while ($row = $q_vms->fetch_assoc()) {
        $gn  = trim($row['group_name']);
        $tok = trim($row['earnapp_token']);
        if (!isset($group_stats[$gn])) $group_stats[$gn] = ['vms'=>0,'today'=>0,'week'=>0,'month'=>0,'lifetime'=>0];
        $group_stats[$gn]['vms']++;
        if ($tok) $vm_map[$tok] = $gn;
    }
}

// Lifetime per token = sum of all daily deltas
$q_lifetime = $conn->query("
    SELECT earnapp_token, SUM(daily_earned) lifetime FROM (
        SELECT t.earnapp_token, GREATEST(0, t.day_max - IFNULL(p.prev_day_max,0)) daily_earned
        FROM (SELECT earnapp_token, DATE(recorded_at) dt, MAX(COALESCE(redeem_balance, CAST(balance AS DECIMAL(10,4)))) day_max
              FROM earnapp_history WHERE earnapp_token IN ($tokList) GROUP BY earnapp_token, DATE(recorded_at)) t
        LEFT JOIN (SELECT earnapp_token, DATE(recorded_at) dt, MAX(COALESCE(redeem_balance, CAST(balance AS DECIMAL(10,4)))) prev_day_max
                   FROM earnapp_history WHERE earnapp_token IN ($tokList) GROUP BY earnapp_token, DATE(recorded_at)) p
        ON p.earnapp_token=t.earnapp_token AND p.dt=DATE_SUB(t.dt, INTERVAL 1 DAY)
    ) x GROUP BY earnapp_token
");
if ($q_lifetime) { while($r=$q_lifetime->fetch_assoc()){ $t=trim($r['earnapp_token']); if(isset($vm_map[$t])) $group_stats[$vm_map[$t]]['lifetime']+=(float)$r['lifetime']; } }

// Today per token
$q_today = $conn->query("
    SELECT t.earnapp_token, GREATEST(0, t.t - IFNULL(y.y,0)) v
    FROM (SELECT earnapp_token, MAX(COALESCE(redeem_balance, CAST(balance AS DECIMAL(10,4)))) t
          FROM earnapp_history WHERE DATE(recorded_at)=CURDATE() AND earnapp_token IN ($tokList) GROUP BY earnapp_token) t
    LEFT JOIN (SELECT earnapp_token, MAX(COALESCE(redeem_balance, CAST(balance AS DECIMAL(10,4)))) y
               FROM earnapp_history WHERE DATE(recorded_at)=CURDATE()-INTERVAL 1 DAY AND earnapp_token IN ($tokList) GROUP BY earnapp_token) y
    ON y.earnapp_token=t.earnapp_token
");
if ($q_today) { while($r=$q_today->fetch_assoc()){ $t=trim($r['earnapp_token']); if(isset($vm_map[$t])) $group_stats[$vm_map[$t]]['today']+=(float)$r['v']; } }

// Week per token (daily delta sum)
$q_week = $conn->query("
    SELECT earnapp_token, SUM(daily_earned) v FROM (
        SELECT t.earnapp_token, GREATEST(0, t.day_max - IFNULL(p.prev_day_max,0)) daily_earned
        FROM (SELECT earnapp_token, DATE(recorded_at) dt, MAX(COALESCE(redeem_balance, CAST(balance AS DECIMAL(10,4)))) day_max
              FROM earnapp_history WHERE DATE(recorded_at) BETWEEN '$week_start' AND CURDATE() AND earnapp_token IN ($tokList)
              GROUP BY earnapp_token, DATE(recorded_at)) t
        LEFT JOIN (SELECT earnapp_token, DATE(recorded_at) dt, MAX(COALESCE(redeem_balance, CAST(balance AS DECIMAL(10,4)))) prev_day_max
                   FROM earnapp_history WHERE earnapp_token IN ($tokList) GROUP BY earnapp_token, DATE(recorded_at)) p
        ON p.earnapp_token=t.earnapp_token AND p.dt=DATE_SUB(t.dt, INTERVAL 1 DAY)
    ) x GROUP BY earnapp_token
");
if ($q_week) { while($r=$q_week->fetch_assoc()){ $t=trim($r['earnapp_token']); if(isset($vm_map[$t])) $group_stats[$vm_map[$t]]['week']+=(float)$r['v']; } }

// Month per token (daily delta sum)
$q_month = $conn->query("
    SELECT earnapp_token, SUM(daily_earned) v FROM (
        SELECT t.earnapp_token, GREATEST(0, t.day_max - IFNULL(p.prev_day_max,0)) daily_earned
        FROM (SELECT earnapp_token, DATE(recorded_at) dt, MAX(COALESCE(redeem_balance, CAST(balance AS DECIMAL(10,4)))) day_max
              FROM earnapp_history WHERE DATE(recorded_at) BETWEEN '$month_start' AND CURDATE() AND earnapp_token IN ($tokList)
              GROUP BY earnapp_token, DATE(recorded_at)) t
        LEFT JOIN (SELECT earnapp_token, DATE(recorded_at) dt, MAX(COALESCE(redeem_balance, CAST(balance AS DECIMAL(10,4)))) prev_day_max
                   FROM earnapp_history WHERE earnapp_token IN ($tokList) GROUP BY earnapp_token, DATE(recorded_at)) p
        ON p.earnapp_token=t.earnapp_token AND p.dt=DATE_SUB(t.dt, INTERVAL 1 DAY)
    ) x GROUP BY earnapp_token
");
if ($q_month) { while($r=$q_month->fetch_assoc()){ $t=trim($r['earnapp_token']); if(isset($vm_map[$t])) $group_stats[$vm_map[$t]]['month']+=(float)$r['v']; } }
?>

<script>
document.addEventListener('DOMContentLoaded', function() {
    Chart.defaults.maintainAspectRatio = false;
    function get(id){ return 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:'Earnings',data:<?= json_encode($trendData) ?>,borderColor:'#f5c542',backgroundColor:'rgba(245,197,66,.15)',pointRadius:4,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:[<?= (int)$ipStats['ok_ips']?>,<?= (int)$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}}}});
    }
});
</script>

<style>
.anl-card{background:#0b0b0b;border:1px solid #2a0000;border-radius:10px;padding:15px}
.anl-stat{font-size:22px;font-weight:800}
.anl-label{font-size:11px;color:#888}
.anl-green{color:#00ff4c}
.anl-red{color:#ff2b2b}
.anl-grid{display:grid;grid-template-columns:repeat(5,1fr);gap:15px}
.anl-chart{background:#0b0b0b;border:1px solid #2a0000;border-radius:10px;padding:15px;height:320px}
.anl-dashboard-row{display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:30px}
.anl-chart-box{background:#050505;border:1px solid #2a0000;border-radius:12px;padding:20px;height:360px}
.anl-chart-box h4{font-size:14px;margin-bottom:10px;color:#bbb}
.anl-chart-box canvas{width:100%!important;height:280px!important}
.anl-lifetime-box{background:#050505;border:1px solid #2a0000;border-radius:14px;padding:20px;margin-top:30px}
.anl-stat-cards{display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:20px}
.anl-stat-card{background:#0b0b0b;border:1px solid #2a0000;border-radius:12px;padding:16px}
.anl-stat-card .value{font-size:22px;font-weight:700}
.anl-table{width:100%;border-collapse:collapse}
.anl-table th,.anl-table td{padding:10px;border-bottom:1px solid #1a0000;font-size:13px}
</style>

<div class="container-fluid p-4">
<div id="top-stats-wrapper">
    <?php include __DIR__ . '/../parts/vm_top_stats.php'; ?>
</div>
<br>
<div class="anl-grid">
    <div class="anl-card"><div class="anl-label">TOTAL EARNINGS</div><div class="anl-stat anl-green">$<?= nf($earnings['lifetime']) ?></div></div>
    <div class="anl-card"><div class="anl-label">TODAY</div><div class="anl-stat anl-green">$<?= nf($earnings['today']) ?></div></div>
    <div class="anl-card"><div class="anl-label">THIS WEEK</div><div class="anl-stat anl-green">$<?= nf($earnings['week']) ?></div></div>
    <div class="anl-card"><div class="anl-label">THIS MONTH</div><div class="anl-stat anl-green">$<?= nf($earnings['month']) ?></div></div>
    <div class="anl-card"><div class="anl-label">BLOCKED IPS</div><div class="anl-stat anl-red"><?= (int)$stats['anomalies'] ?></div></div>
</div>
<br>
<div class="anl-grid" style="grid-template-columns:1fr 2fr">
    <div class="anl-chart"><canvas id="statusChart"></canvas></div>
    <div class="anl-chart"><canvas id="earningsTrend"></canvas></div>
</div>
<br>
<div class="anl-grid" style="grid-template-columns:1fr 1fr">
    <div class="anl-chart"><canvas id="vmGrowth"></canvas></div>
    <div class="anl-chart"><canvas id="groupBar"></canvas></div>
</div>
<br>
<div class="anl-dashboard-row">
    <div class="anl-chart-box"><h4>IP Status Overview</h4><canvas id="ipStatusChart"></canvas></div>
    <div class="anl-chart-box"><h4>Alerts by Type</h4><canvas id="alertsChart"></canvas></div>
</div>

<div class="anl-lifetime-box">
    <h4>Lifetime Earnings by Group</h4>
    <div class="anl-stat-cards">
        <div class="anl-stat-card"><small>Total Lifetime</small><div class="value anl-red">$<?= nf($earnings['lifetime']) ?></div></div>
        <div class="anl-stat-card"><small>Today</small><div class="value anl-green">$<?= nf($earnings['today']) ?></div></div>
        <div class="anl-stat-card"><small>This Week</small><div class="value anl-green">$<?= nf($earnings['week']) ?></div></div>
        <div class="anl-stat-card"><small>This Month</small><div class="value anl-green">$<?= nf($earnings['month']) ?></div></div>
    </div>
    <table class="anl-table">
        <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 foreach ($group_stats as $gn => $st): ?>
        <tr>
            <td><?= htmlspecialchars($gn) ?></td>
            <td><?= $st['vms'] ?></td>
            <td class="anl-green">$<?= nf($st['today']) ?></td>
            <td class="anl-green">$<?= nf($st['week']) ?></td>
            <td class="anl-green">$<?= nf($st['month']) ?></td>
            <td class="anl-green">$<?= nf($st['lifetime']) ?></td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
<br>
</div>