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

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

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

$r = mysqli_query($conn, "SELECT vm_id, MAX(balance) bal FROM earnapp_history WHERE DATE(recorded_at) = CURDATE() GROUP BY vm_id");
if ($r) while ($row = mysqli_fetch_assoc($r)) $today_bal[$row['vm_id']] = (float)$row['bal'];

$r = mysqli_query($conn, "SELECT vm_id, MAX(balance) bal FROM earnapp_history WHERE DATE(recorded_at) = CURDATE() - INTERVAL 1 DAY GROUP BY vm_id");
if ($r) while ($row = mysqli_fetch_assoc($r)) $yest_bal[$row['vm_id']] = (float)$row['bal'];

$r = mysqli_query($conn, "SELECT vm_id, MAX(balance) bal FROM earnapp_history WHERE DATE(recorded_at) = CURDATE() - INTERVAL 2 DAY GROUP BY vm_id");
if ($r) while ($row = mysqli_fetch_assoc($r)) $prev_bal[$row['vm_id']] = (float)$row['bal'];

$token_map = [];
$r = mysqli_query($conn, "SELECT vm_id, earnapp_token FROM earnapp_history WHERE earnapp_token IS NOT NULL AND earnapp_token != '' GROUP BY vm_id");
if ($r) while ($row = mysqli_fetch_assoc($r)) $token_map[$row['vm_id']] = $row['earnapp_token'];

$earnings_by_token = [];
$all_vm_ids = array_unique(array_merge(array_keys($today_bal), array_keys($yest_bal)));

foreach ($all_vm_ids as $vid) {
    if (isset($token_map[$vid])) {
        $token = $token_map[$vid];
        $t = $today_bal[$vid] ?? 0;
        $y = $yest_bal[$vid]  ?? 0;
        $p = $prev_bal[$vid]  ?? 0;

        $today_earn = max(0, $t - $y);
        $yest_earn  = max(0, $y - $p);

        if (!isset($earnings_by_token[$token])) {
            $earnings_by_token[$token] = ['today' => 0, 'yesterday' => 0];
        }
        $earnings_by_token[$token]['today']     += $today_earn;
        $earnings_by_token[$token]['yesterday'] += $yest_earn;
    }
}

$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 vm_id, MAX(CAST(balance AS DECIMAL(10,4))) AS today_max FROM earnapp_history WHERE DATE(recorded_at) = CURDATE() GROUP BY vm_id) t
    LEFT JOIN (SELECT vm_id, MAX(CAST(balance AS DECIMAL(10,4))) AS prev_max FROM earnapp_history WHERE DATE(recorded_at) = CURDATE() - INTERVAL 1 DAY GROUP BY vm_id) y ON y.vm_id = t.vm_id
"))['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 vm_id, MAX(CAST(balance AS DECIMAL(10,4))) AS yest_max FROM earnapp_history WHERE DATE(recorded_at) = CURDATE() - INTERVAL 1 DAY GROUP BY vm_id) y
    LEFT JOIN (SELECT vm_id, MAX(CAST(balance AS DECIMAL(10,4))) AS prev_max FROM earnapp_history WHERE DATE(recorded_at) = CURDATE() - INTERVAL 2 DAY GROUP BY vm_id) p ON p.vm_id = y.vm_id
"))['total'];

$week_earnings_all = (float)mysqli_fetch_assoc(mysqli_query($conn, "
    SELECT IFNULL(SUM(daily_earned), 0) AS total
    FROM (
        SELECT t.vm_id, t.dt, GREATEST(0, t.day_max - IFNULL(p.prev_day_max, 0)) AS daily_earned
        FROM (
            SELECT vm_id, DATE(recorded_at) AS dt, MAX(CAST(balance AS DECIMAL(10,4))) AS day_max
            FROM earnapp_history
            WHERE DATE(recorded_at) BETWEEN CURDATE() - INTERVAL 6 DAY AND CURDATE()
            GROUP BY vm_id, DATE(recorded_at)
        ) t
        LEFT JOIN (
            SELECT vm_id, DATE(recorded_at) AS dt, MAX(CAST(balance AS DECIMAL(10,4))) AS prev_day_max
            FROM earnapp_history
            GROUP BY vm_id, DATE(recorded_at)
        ) p ON p.vm_id = t.vm_id 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"))['cnt'] ?? 0);
$online = (int)(mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as cnt FROM vms WHERE LOWER(TRIM(status)) IN ('running','online')"))['cnt'] ?? 0);
$offline = (int)(mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as cnt FROM vms WHERE LOWER(TRIM(status)) = 'offline'"))['cnt'] ?? 0);
$anomaly = 0;

$groups_result = mysqli_query($conn, "SELECT DISTINCT group_name FROM vms WHERE group_name IS NOT NULL AND group_name != '' ORDER BY group_name ASC");
$status_result = mysqli_query($conn, "SELECT DISTINCT status FROM vms WHERE 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 ORDER BY unit_id ASC
") or die("Query failed: " . mysqli_error($conn));
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>VM Inventory</title>
    <style>
        body { background: #0d1117; color: #c9d1d9; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; margin: 0; padding: 20px; }
        .container { max-width: 1440px; margin: 0 auto; }
        .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; }
        .title { font-size: 20px; font-weight: 600; }
        .controls { display: flex; gap: 12px; flex-wrap: wrap; align-items: center; }
        .btn, select, input[type="text"] { background: #21262d; border: 1px solid #30363d; color: #c9d1d9; padding: 6px 12px; border-radius: 6px; font-size: 14px; }
        .btn:hover, select:hover { background: #30363d; }
        .stats { display: flex; gap: 10px; margin: 16px 0 24px; flex-wrap: wrap; }
        .stat-box { background: #161b22; border: 1px solid #30363d; padding: 12px 18px; border-radius: 6px; min-width: 140px; text-align: center; font-weight: 500; }
        .stat-number { font-size: 22px; font-weight: bold; display: block; }
        .online .stat-number { color: #56d364; }
        .offline .stat-number { color: #f85149; }
        .anomaly .stat-number { color: #ffa657; }
        .earning .stat-number { color: #ffa657; font-size: 20px; }
        table { width: 100%; border-collapse: collapse; font-size: 14px; background: #0d1117; }
        th, td { padding: 10px 12px; border: 1px solid #21262d; text-align: left; }
        th { background: #161b22; color: #8b949e; font-weight: 600; position: sticky; top: 0; z-index: 1; }
        tr:nth-child(even) { background: #0d11171a; }
        .status { padding: 4px 8px; border-radius: 4px; font-weight: bold; }
        .yes { color: #56d364; font-weight: bold; }
        .no { color: #f85149; font-weight: bold; }
        .token-cell { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
        .token { font-family: monospace; font-size: 12px; color: #8b949e; word-break: break-all; max-width: 220px; }
        .copy-btn { background: #21262d; border: 1px solid #30363d; color: #c9d1d9; padding: 4px 8px; border-radius: 6px; cursor: pointer; font-size: 12px; transition: all 0.2s; }
        .copy-btn:hover { background: #30363d; color: #fff; }
        .copied { position: absolute; background: #56d364; color: #000; padding: 4px 8px; border-radius: 4px; font-size: 11px; pointer-events: none; opacity: 0; transition: opacity 0.3s; transform: translateY(-10px); }
        .last-hb { color: #8b949e; white-space: nowrap; }
    </style>
</head>
<body>

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

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

    <div class="stats">
        <div class="stat-box"><span class="stat-number"><?php echo $total; ?></span> TOTAL</div>
        <div class="stat-box online"><span class="stat-number"><?php echo $online; ?></span> ONLINE</div>
        <div class="stat-box offline"><span class="stat-number"><?php echo $offline; ?></span> OFFLINE</div>
        <div class="stat-box anomaly"><span class="stat-number"><?php echo $anomaly; ?></span> ANOMALY</div>
        <div class="stat-box earning"><span class="stat-number" id="todayEarning">$<?php echo number_format($today_earnings_all, 2); ?></span> TODAY</div>
        <div class="stat-box earning"><span class="stat-number" id="yesterdayEarning">$<?php echo number_format($yesterday_earnings_all, 2); ?></span> YESTERDAY</div>
        <div class="stat-box earning"><span class="stat-number" id="weekEarning">$<?php echo number_format($week_earnings_all, 2); ?></span> THIS WEEK</div>
    </div>

    <table>
        <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)): ?>
                    <?php
                    $status_raw   = trim($row['status'] ?? 'Unknown');
                    $status_lower = strtolower($status_raw);

                    if (in_array($status_lower, ['running','online'])) {
                        $status_class = 'style="background:#56d3641a; color:#56d364;"';
                    } elseif ($status_lower === 'offline') {
                        $status_class = 'style="background:#f851491a; color:#f85149;"';
                    } else {
                        $status_class = 'style="background:#444; color:#ccc;"';
                    }

                    $running_text = in_array($status_lower, ['running','online']) ? 'YES' : 'NO';
                    $ip = ($row['current_ip'] ?: '-') . ' / ' . ($row['ip_address'] ?: '—');

                    $hb_display = '—';
                    if (!empty($row['last_heartbeat'])) {
                        $diff = time() - strtotime($row['last_heartbeat']);
                        if ($diff < 0)          $hb_display = 'just now';
                        elseif ($diff < 60)     $hb_display = $diff . ' sec ago';
                        elseif ($diff < 3600)   $hb_display = floor($diff / 60) . ' min ago';
                        elseif ($diff < 86400)  $hb_display = floor($diff / 3600) . ' hrs ago';
                        else                    $hb_display = floor($diff / 86400) . ' days ago';
                    }

                    $token = $row['earnapp_token'] ?? '';
                    $uid   = $row['unit_id'];

                    $today_earn_value = 0.0;
                    $yest_earn_value  = 0.0;
                    if ($token && isset($earnings_by_token[$token])) {
                        $today_earn_value = (float)$earnings_by_token[$token]['today'];
                        $yest_earn_value  = (float)$earnings_by_token[$token]['yesterday'];
                    }
                    ?>
                    <tr
                        data-group="<?php echo htmlspecialchars(strtolower($row['group_name'] ?? '')); ?>"
                        data-status="<?php echo htmlspecialchars(strtolower($status_raw)); ?>"
                        data-unit="<?php echo htmlspecialchars($uid); ?>"
                        data-today-earn="<?php echo $today_earn_value; ?>"
                        data-yesterday-earn="<?php echo $yest_earn_value; ?>">
                        <td><?php echo htmlspecialchars($uid ?: '—'); ?></td>
                        <td><?php echo htmlspecialchars($row['group_name'] ?? '—'); ?></td>
                        <td><?php echo htmlspecialchars($row['rdp_nickname'] ?? '—'); ?></td>
                        <td><?php echo htmlspecialchars($ip); ?></td>
                        <td><span <?php echo $status_class; ?>><?php echo htmlspecialchars($status_raw); ?></span></td>
                        <td>
                            <div class="token-cell" style="position:relative;">
                                <span class="token"><?php echo htmlspecialchars($token ?: '—'); ?></span>
                                <?php if ($token): ?>
                                    <button class="copy-btn" onclick="copyToClipboard('https://earnapp.com/dashboard/link/<?php echo htmlspecialchars($token, ENT_QUOTES); ?>', this)">Copy</button>
                                <?php endif; ?>
                            </div>
                        </td>
                        <td class="<?php echo $running_text === 'YES' ? 'yes' : 'no'; ?>"><?php echo $running_text; ?></td>
                        <td class="yes">Yes</td>
                        <td class="no">No</td>
                        <td class="last-hb"><?php echo $hb_display; ?></td>
                    </tr>
                <?php endwhile; ?>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const groupFilter  = document.getElementById('groupFilter');
    const statusFilter = document.getElementById('statusFilter');
    const searchInput  = document.getElementById('searchInput');
    const rows         = document.querySelectorAll('table tbody tr');

    const dbTotalToday = <?php echo json_encode($today_earnings_all); ?>;
    const dbTotalYest  = <?php echo json_encode($yesterday_earnings_all); ?>;
    const dbTotalWeek  = <?php echo json_encode($week_earnings_all); ?>;

    function applyFilters() {
        const groupVal  = groupFilter.value.toLowerCase();
        const statusVal = statusFilter.value.toLowerCase();
        const searchVal = searchInput.value.toLowerCase();

        let visibleCount          = 0;
        let visibleOnline         = 0;
        let visibleTodayEarning   = 0;
        let visibleYesterdayEarning = 0;
        let processedUnits        = new Set();
        let anyFilterActive       = (groupVal !== '' || statusVal !== '' || searchVal !== '');

        rows.forEach(row => {
            if (row.cells.length < 6) return;

            const groupCell  = row.cells[1].textContent.toLowerCase();
            const statusCell = row.cells[4].textContent.toLowerCase();
            const unitId     = row.getAttribute('data-unit') || row.cells[0].textContent.toLowerCase();
            const token      = row.cells[5].textContent.toLowerCase();

            const matchGroup  = !groupVal  || groupCell.includes(groupVal);
            const matchStatus = !statusVal || statusCell.includes(statusVal);
            const matchSearch = !searchVal || unitId.includes(searchVal) || groupCell.includes(searchVal) || token.includes(searchVal);

            const show = matchGroup && matchStatus && matchSearch;
            row.style.display = show ? '' : 'none';

            if (show) {
                visibleCount++;
                if (statusCell.includes('running') || statusCell.includes('online')) visibleOnline++;
                if (!processedUnits.has(unitId + token)) {
                    visibleTodayEarning     += parseFloat(row.getAttribute('data-today-earn')     || 0);
                    visibleYesterdayEarning += parseFloat(row.getAttribute('data-yesterday-earn') || 0);
                    processedUnits.add(unitId + token);
                }
            }
        });

        document.querySelector('.stats .stat-box:nth-child(1) .stat-number').textContent = visibleCount;
        document.querySelector('.stats .stat-box.online .stat-number').textContent        = visibleOnline;
        document.querySelector('.stats .stat-box.offline .stat-number').textContent       = visibleCount - visibleOnline;
        document.querySelector('.stats .stat-box.anomaly .stat-number').textContent       = 0;

        if (anyFilterActive) {
            document.getElementById('todayEarning').textContent     = '$' + visibleTodayEarning.toFixed(2);
            document.getElementById('yesterdayEarning').textContent = '$' + visibleYesterdayEarning.toFixed(2);
            document.getElementById('weekEarning').textContent      = '$' + dbTotalWeek.toFixed(2);
        } else {
            document.getElementById('todayEarning').textContent     = '$' + dbTotalToday.toFixed(2);
            document.getElementById('yesterdayEarning').textContent = '$' + dbTotalYest.toFixed(2);
            document.getElementById('weekEarning').textContent      = '$' + dbTotalWeek.toFixed(2);
        }
    }

    groupFilter.addEventListener('change', applyFilters);
    statusFilter.addEventListener('change', applyFilters);
    searchInput.addEventListener('input', applyFilters);
    applyFilters();
});

function copyToClipboard(text, button) {
    navigator.clipboard.writeText(text).then(() => {
        const tooltip = document.createElement('span');
        tooltip.className   = 'copied';
        tooltip.textContent = 'Copied!';
        button.parentElement.appendChild(tooltip);
        setTimeout(() => tooltip.style.opacity = '1', 10);
        setTimeout(() => { tooltip.style.opacity = '0'; setTimeout(() => tooltip.remove(), 300); }, 1500);
    }).catch(err => console.error('Copy failed', err));
}
</script>
</body>
</html>