<?php

date_default_timezone_set('Asia/Kolkata');


if (isset($_POST['fetch_today'])) {

    $today = date('Y-m-d');

    $q = mysqli_query($conn, "SELECT unit_id, balance FROM vms");

    while ($row = mysqli_fetch_assoc($q)) {

        $unit = mysqli_real_escape_string($conn, $row['unit_id']);
        $bal  = (float)$row['balance'];

        $y = mysqli_fetch_assoc(mysqli_query($conn, "
            SELECT earning
            FROM vm_earnings
            WHERE unit_id='$unit'
              AND DATE(date) = CURDATE() - INTERVAL 1 DAY
            LIMIT 1
        "));

        $ybal = $y ? (float)$y['earning'] : 0;

        $today_earn = ($ybal > 0) ? max(0, $bal - $ybal) : $bal;

        mysqli_query($conn, "
            INSERT INTO vm_earnings (unit_id, earning, date)
            VALUES ('$unit', '$today_earn', '$today')
            ON DUPLICATE KEY UPDATE earning = VALUES(earning)
        ");
    }

    header("Location: ".$_SERVER['REQUEST_URI']);
    exit;
}


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

$today_earnings_all = (float)(mysqli_fetch_assoc(mysqli_query(
    $conn,
    "SELECT IFNULL(SUM(earning),0) t 
    FROM vm_earnings 
    WHERE DATE(date) = CURDATE()"
))['t'] ?? 0);

$yesterday_earnings_all = (float)(mysqli_fetch_assoc(mysqli_query(
    $conn,
    "SELECT IFNULL(SUM(earning),0) y 
    FROM vm_earnings 
    WHERE DATE(date) = CURDATE() - INTERVAL 1 DAY"
))['y'] ?? 0);


$group_earnings = [];

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

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

$query = "
    SELECT 
        unit_id,
        group_name,
        rdp_nickname,
        current_ip,
        ip_address,
        earnapp_token,
        status,
        last_heartbeat
    FROM vms
    ORDER BY unit_id ASC
";

$result = mysqli_query($conn, $query) 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: 16px;
            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>

    <table>
        <thead>
            <tr>
                <th>UNIT ID</th>
                <th>GROUP</th>
                <th>RDP</th>
                <th>IP ADDRESS</th>
                <th>STATUS</th>
                <th>EARNNAPP 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);
            $status_class = 'status ';
            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'])) {
                $hbTs = strtotime($row['last_heartbeat']);
                $now  = time();
                $diff = $now - $hbTs;
            
                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'] ?? '—';
            ?>

                    <tr data-group="<?php echo htmlspecialchars(strtolower($row['group_name'] ?? '')); ?>" data-status="<?php echo htmlspecialchars(strtolower($status_raw)); ?>">
                        <td><?php echo htmlspecialchars($row['unit_id'] ?? '—'); ?></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');

    // Dummy group earnings – in real case fetch from DB and put in data attribute or JSON
      

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

        let visibleCount = 0;
        let visibleOnline = 0;

        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.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++;
                }
            }
        });

        // Update stats dynamically after filter
        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; // placeholder
 
    }

    groupFilter.addEventListener('change', applyFilters);
    statusFilter.addEventListener('change', applyFilters);
    searchInput.addEventListener('input', 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>