<?php
date_default_timezone_set('Asia/Kolkata');

if (isset($_POST['fetch_today'])) {
    header("Location: ".$_SERVER['REQUEST_URI']);
    exit;
}

$_vd       = getVmData($conn);
$_gidList  = $_vd['gidList'];
$_vmIdList = $_vd['vmIdList'];
$_tokList  = $_vd['tokenList'];

$today_bal = [];
$yest_bal  = [];
$prev_bal  = [];

$r = mysqli_query($conn, "SELECT earnapp_token, MAX(COALESCE(redeem_balance, CAST(balance AS DECIMAL(10,4)))) bal FROM earnapp_history WHERE DATE(recorded_at) = CURDATE() AND earnapp_token IN ($_tokList) GROUP BY earnapp_token");
if ($r) while ($row = mysqli_fetch_assoc($r)) $today_bal[$row['earnapp_token']] = (float)$row['bal'];

$r = mysqli_query($conn, "SELECT earnapp_token, MAX(COALESCE(redeem_balance, CAST(balance AS DECIMAL(10,4)))) bal FROM earnapp_history WHERE DATE(recorded_at) = CURDATE() - INTERVAL 1 DAY AND earnapp_token IN ($_tokList) GROUP BY earnapp_token");
if ($r) while ($row = mysqli_fetch_assoc($r)) $yest_bal[$row['earnapp_token']] = (float)$row['bal'];

$r = mysqli_query($conn, "SELECT earnapp_token, MAX(COALESCE(redeem_balance, CAST(balance AS DECIMAL(10,4)))) bal FROM earnapp_history WHERE DATE(recorded_at) = CURDATE() - INTERVAL 2 DAY AND earnapp_token IN ($_tokList) GROUP BY earnapp_token");
if ($r) while ($row = mysqli_fetch_assoc($r)) $prev_bal[$row['earnapp_token']] = (float)$row['bal'];

$earnings_by_token = array();
$all_tokens = array_unique(array_merge(array_keys($today_bal), array_keys($yest_bal)));
foreach ($all_tokens as $tok) {
    $t = isset($today_bal[$tok]) ? $today_bal[$tok] : 0;
    $y = isset($yest_bal[$tok])  ? $yest_bal[$tok]  : 0;
    $p = isset($prev_bal[$tok])  ? $prev_bal[$tok]  : 0;
    $earnings_by_token[$tok] = array('today'=>max(0,$t-$y), 'yesterday'=>max(0,$y-$p));
}

$today_earnings_all = (float)mysqli_fetch_assoc(mysqli_query($conn, "
    SELECT IFNULL(SUM(GREATEST(0, t.today_max - IFNULL(y.prev_max, 0))), 0) AS total
    FROM (SELECT earnapp_token, MAX(COALESCE(redeem_balance, CAST(balance AS DECIMAL(10,4)))) AS today_max 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)))) AS prev_max 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
"))['total'];

$yesterday_earnings_all = (float)mysqli_fetch_assoc(mysqli_query($conn, "
    SELECT IFNULL(SUM(GREATEST(0, y.yest_max - IFNULL(p.prev_max, 0))), 0) AS total
    FROM (SELECT earnapp_token, MAX(COALESCE(redeem_balance, CAST(balance AS DECIMAL(10,4)))) AS yest_max FROM earnapp_history WHERE DATE(recorded_at) = CURDATE() - INTERVAL 1 DAY AND earnapp_token IN ($_tokList) GROUP BY earnapp_token) y
    LEFT JOIN (SELECT earnapp_token, MAX(COALESCE(redeem_balance, CAST(balance AS DECIMAL(10,4)))) AS prev_max FROM earnapp_history WHERE DATE(recorded_at) = CURDATE() - INTERVAL 2 DAY AND earnapp_token IN ($_tokList) GROUP BY earnapp_token) p ON p.earnapp_token = y.earnapp_token
"))['total'];

$week_earnings_all = (float)mysqli_fetch_assoc(mysqli_query($conn, "
    SELECT IFNULL(SUM(daily_earned), 0) AS total
    FROM (
        SELECT t.earnapp_token, t.dt, GREATEST(0, t.day_max - IFNULL(p.prev_day_max, 0)) AS daily_earned
        FROM (
            SELECT earnapp_token, DATE(recorded_at) AS dt, MAX(COALESCE(redeem_balance, CAST(balance AS DECIMAL(10,4)))) AS day_max
            FROM earnapp_history
            WHERE DATE(recorded_at) BETWEEN CURDATE() - INTERVAL 6 DAY AND CURDATE() AND earnapp_token IN ($_tokList)
            GROUP BY earnapp_token, DATE(recorded_at)
        ) t
        LEFT JOIN (
            SELECT earnapp_token, DATE(recorded_at) AS dt, MAX(COALESCE(redeem_balance, CAST(balance AS DECIMAL(10,4)))) AS 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
"))['total'];

$total   = (int)(mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as cnt FROM vms WHERE id IN ($_vmIdList)"))['cnt'] ?? 0);
$online  = (int)(mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as cnt FROM vms WHERE id IN ($_vmIdList) AND LOWER(TRIM(status)) IN ('running','online')"))['cnt'] ?? 0);
$offline = (int)(mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as cnt FROM vms WHERE id IN ($_vmIdList) AND LOWER(TRIM(status)) = 'offline'"))['cnt'] ?? 0);
$anomaly = 0;

$groups_result = mysqli_query($conn, "SELECT DISTINCT group_name FROM vms WHERE id IN ($_vmIdList) AND group_name IS NOT NULL AND group_name != '' ORDER BY group_name ASC");
$status_result = mysqli_query($conn, "SELECT DISTINCT status FROM vms WHERE id IN ($_vmIdList) AND status IS NOT NULL AND status != '' ORDER BY status ASC");

$result = mysqli_query($conn, "
    SELECT unit_id, group_name, rdp_nickname, current_ip, ip_address, earnapp_token, status, last_heartbeat
    FROM vms WHERE id IN ($_vmIdList) ORDER BY unit_id ASC
") or die("Query failed: " . mysqli_error($conn));
?>

<style>
.rpt-wrap{background:#0d1117;color:#c9d1d9;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;padding:20px;}
.rpt-header{background:#161b22;padding:12px 16px;border-radius:6px;margin-bottom:16px;display:flex;justify-content:space-between;align-items:center;border:1px solid #30363d;}
.rpt-title{font-size:20px;font-weight:600;}
.rpt-controls{display:flex;gap:12px;flex-wrap:wrap;align-items:center;}
.rpt-btn,.rpt-select,.rpt-input{background:#21262d;border:1px solid #30363d;color:#c9d1d9;padding:6px 12px;border-radius:6px;font-size:14px;cursor:pointer;}
.rpt-btn:hover,.rpt-select:hover{background:#30363d;}
.rpt-stats{display:flex;gap:10px;margin:16px 0 24px;flex-wrap:wrap;}
.rpt-stat-box{background:#161b22;border:1px solid #30363d;padding:12px 18px;border-radius:6px;min-width:140px;text-align:center;font-weight:500;}
.rpt-stat-number{font-size:22px;font-weight:bold;display:block;}
.rpt-online .rpt-stat-number{color:#56d364;}
.rpt-offline .rpt-stat-number{color:#f85149;}
.rpt-anomaly .rpt-stat-number{color:#ffa657;}
.rpt-earning .rpt-stat-number{color:#ffa657;font-size:20px;}
.rpt-table{width:100%;border-collapse:collapse;font-size:14px;background:#0d1117;}
.rpt-table th,.rpt-table td{padding:10px 12px;border:1px solid #21262d;text-align:left;}
.rpt-table th{background:#161b22;color:#8b949e;font-weight:600;position:sticky;top:0;z-index:1;}
.rpt-table tr:nth-child(even){background:rgba(13,17,23,.1);}
.rpt-token-cell{display:flex;align-items:center;gap:8px;flex-wrap:wrap;position:relative;}
.rpt-token{font-family:monospace;font-size:12px;color:#8b949e;word-break:break-all;max-width:220px;}
.rpt-copy-btn{background:#21262d;border:1px solid #30363d;color:#c9d1d9;padding:4px 8px;border-radius:6px;cursor:pointer;font-size:12px;}
.rpt-copy-btn:hover{background:#30363d;color:#fff;}
.rpt-copied{position:absolute;background:#56d364;color:#000;padding:4px 8px;border-radius:4px;font-size:11px;pointer-events:none;opacity:0;transition:opacity .3s;transform:translateY(-10px);}
.rpt-yes{color:#56d364;font-weight:bold;}
.rpt-no{color:#f85149;font-weight:bold;}
.rpt-last-hb{color:#8b949e;white-space:nowrap;}
</style>

<div class="rpt-wrap">
<div id="top-stats-wrapper">
    <?php include __DIR__ . '/../parts/vm_top_stats.php'; ?>
</div>

<div class="rpt-header">
    <div class="rpt-title">VM Inventory</div>
    <div class="rpt-controls">
        <select class="rpt-select" id="rptGroupFilter">
            <option value="">All Groups</option>
            <?php while ($g = mysqli_fetch_assoc($groups_result)): ?>
                <option value="<?= htmlspecialchars($g['group_name']) ?>"><?= htmlspecialchars($g['group_name']) ?></option>
            <?php endwhile; ?>
        </select>
        <select class="rpt-select" id="rptStatusFilter">
            <option value="">All Status</option>
            <?php while ($s = mysqli_fetch_assoc($status_result)): ?>
                <option value="<?= htmlspecialchars($s['status']) ?>"><?= htmlspecialchars($s['status']) ?></option>
            <?php endwhile; ?>
        </select>
        <input type="text" placeholder="Search..." class="rpt-input" id="rptSearchInput" style="width:160px;">
        <button class="rpt-btn" onclick="rptExport()">EXPORT</button>
    </div>
</div>

<div class="rpt-stats">
    <div class="rpt-stat-box"><span class="rpt-stat-number" id="rptTotal"><?= $total ?></span> TOTAL</div>
    <div class="rpt-stat-box rpt-online"><span class="rpt-stat-number" id="rptOnline"><?= $online ?></span> ONLINE</div>
    <div class="rpt-stat-box rpt-offline"><span class="rpt-stat-number" id="rptOffline"><?= $offline ?></span> OFFLINE</div>
    <div class="rpt-stat-box rpt-anomaly"><span class="rpt-stat-number" id="rptAnomaly">0</span> ANOMALY</div>
    <div class="rpt-stat-box rpt-earning"><span class="rpt-stat-number" id="rptToday">$<?= number_format($today_earnings_all,2) ?></span> TODAY</div>
    <div class="rpt-stat-box rpt-earning"><span class="rpt-stat-number" id="rptYesterday">$<?= number_format($yesterday_earnings_all,2) ?></span> YESTERDAY</div>
    <div class="rpt-stat-box rpt-earning"><span class="rpt-stat-number" id="rptWeek">$<?= number_format($week_earnings_all,2) ?></span> THIS WEEK</div>
</div>

<div style="overflow-x:auto;">
<table class="rpt-table" id="rptTable">
    <thead>
        <tr>
            <th>UNIT ID</th><th>GROUP</th><th>RDP</th><th>IP ADDRESS</th>
            <th>STATUS</th><th>EARNAPP LINK</th><th>RUNNING</th><th>AUTO</th><th>PAUSED</th><th>LAST HEARTBEAT</th>
        </tr>
    </thead>
    <tbody>
        <?php if (mysqli_num_rows($result) == 0): ?>
            <tr><td colspan="10" style="text-align:center;padding:40px;color:#f85149;">No records found</td></tr>
        <?php else: ?>
            <?php while ($row = mysqli_fetch_assoc($result)):
                $status_raw   = trim($row['status'] ?? 'Unknown');
                $status_lower = strtolower($status_raw);
                if (in_array($status_lower, ['running','online'])) {
                    $st_style = 'background:#56d3641a;color:#56d364;';
                } elseif ($status_lower === 'offline') {
                    $st_style = 'background:#f851491a;color:#f85149;';
                } else {
                    $st_style = 'background:#444;color:#ccc;';
                }
                $running_text = in_array($status_lower, ['running','online']) ? 'YES' : 'NO';
                $ip = ($row['current_ip'] ?: '-') . ' / ' . ($row['ip_address'] ?: '—');
                $hb = '—';
                if (!empty($row['last_heartbeat'])) {
                    $diff = time() - strtotime($row['last_heartbeat']);
                    if ($diff < 0)         $hb = 'just now';
                    elseif ($diff < 60)    $hb = $diff . ' sec ago';
                    elseif ($diff < 3600)  $hb = floor($diff/60) . ' min ago';
                    elseif ($diff < 86400) $hb = floor($diff/3600) . ' hrs ago';
                    else                   $hb = floor($diff/86400) . ' days ago';
                }
                $token = $row['earnapp_token'] ?? '';
                $uid   = $row['unit_id'];
                $te = 0.0; $ye = 0.0;
                if ($token && isset($earnings_by_token[$token])) {
                    $te = (float)$earnings_by_token[$token]['today'];
                    $ye = (float)$earnings_by_token[$token]['yesterday'];
                }
            ?>
            <tr data-group="<?= htmlspecialchars(strtolower($row['group_name'] ?? '')) ?>"
                data-status="<?= htmlspecialchars($status_lower) ?>"
                data-unit="<?= htmlspecialchars($uid) ?>"
                data-today-earn="<?= $te ?>"
                data-yesterday-earn="<?= $ye ?>">
                <td><?= htmlspecialchars($uid ?: '—') ?></td>
                <td><?= htmlspecialchars($row['group_name'] ?? '—') ?></td>
                <td><?= htmlspecialchars($row['rdp_nickname'] ?? '—') ?></td>
                <td><?= htmlspecialchars($ip) ?></td>
                <td><span style="<?= $st_style ?>;padding:4px 8px;border-radius:4px;font-weight:bold;"><?= htmlspecialchars($status_raw) ?></span></td>
                <td>
                    <div class="rpt-token-cell">
                        <span class="rpt-token"><?= htmlspecialchars($token ?: '—') ?></span>
                        <?php if ($token): ?>
                            <button class="rpt-copy-btn" onclick="rptCopy('https://earnapp.com/dashboard/link/<?= htmlspecialchars($token,ENT_QUOTES) ?>',this)">Copy</button>
                        <?php endif; ?>
                    </div>
                </td>
                <td class="<?= $running_text==='YES'?'rpt-yes':'rpt-no' ?>"><?= $running_text ?></td>
                <td class="rpt-yes">Yes</td>
                <td class="rpt-no">No</td>
                <td class="rpt-last-hb"><?= $hb ?></td>
            </tr>
            <?php endwhile; ?>
        <?php endif; ?>
    </tbody>
</table>
</div>
</div>

<script>
(function(){
    const dbToday=<?= json_encode($today_earnings_all) ?>,dbYest=<?= json_encode($yesterday_earnings_all) ?>,dbWeek=<?= json_encode($week_earnings_all) ?>;
    const gf=document.getElementById('rptGroupFilter'),sf=document.getElementById('rptStatusFilter'),si=document.getElementById('rptSearchInput');
    const rows=document.querySelectorAll('#rptTable tbody tr');
    function run(){
        const gv=gf.value.toLowerCase(),sv=sf.value.toLowerCase(),q=si.value.toLowerCase();
        let cnt=0,on=0,ts=0,ys=0;const seen=new Set(),active=gv||sv||q;
        rows.forEach(r=>{
            if(r.cells.length<6)return;
            const gc=r.cells[1].textContent.toLowerCase(),sc=r.cells[4].textContent.toLowerCase(),uc=(r.getAttribute('data-unit')||'').toLowerCase(),tc=r.cells[5].textContent.toLowerCase();
            const show=(!gv||gc.includes(gv))&&(!sv||sc.includes(sv))&&(!q||uc.includes(q)||gc.includes(q)||tc.includes(q));
            r.style.display=show?'':'none';
            if(show){cnt++;if(sc.includes('running')||sc.includes('online'))on++;const k=uc+tc;if(!seen.has(k)){ts+=parseFloat(r.getAttribute('data-today-earn')||0);ys+=parseFloat(r.getAttribute('data-yesterday-earn')||0);seen.add(k);}}
        });
        document.getElementById('rptTotal').textContent=cnt;
        document.getElementById('rptOnline').textContent=on;
        document.getElementById('rptOffline').textContent=cnt-on;
        document.getElementById('rptToday').textContent='$'+(active?ts:dbToday).toFixed(2);
        document.getElementById('rptYesterday').textContent='$'+(active?ys:dbYest).toFixed(2);
        document.getElementById('rptWeek').textContent='$'+dbWeek.toFixed(2);
    }
    gf.addEventListener('change',run);sf.addEventListener('change',run);si.addEventListener('input',run);run();
})();
function rptCopy(text,btn){navigator.clipboard.writeText(text).then(()=>{const t=document.createElement('span');t.className='rpt-copied';t.textContent='Copied!';btn.parentElement.appendChild(t);setTimeout(()=>t.style.opacity='1',10);setTimeout(()=>{t.style.opacity='0';setTimeout(()=>t.remove(),300);},1500);});}
function rptExport(){const rows=document.querySelectorAll('#rptTable tr');let csv=[];rows.forEach(r=>{if(r.style.display==='none')return;const cols=Array.from(r.querySelectorAll('th,td')).map(c=>'"'+c.textContent.trim().replace(/"/g,'""')+'"');csv.push(cols.join(','));});const b=new Blob([csv.join('\n')],{type:'text/csv'});const a=document.createElement('a');a.href=URL.createObjectURL(b);a.download='vm_report_'+new Date().toISOString().slice(0,10)+'.csv';a.click();}
</script>
</body>
</html>