<?php
require_once 'db.php';

if (isset($_POST['fetch_today'])) {
    $today = date('Y-m-d');
    $q = $conn->query("SELECT unit_id, balance FROM vms");
    while ($row = $q->fetch_assoc()) {
        $unit = $conn->real_escape_string($row['unit_id']);
        $bal  = (float)$row['balance'];
        $prev = mysqli_fetch_assoc(mysqli_query($conn, "
            SELECT SUM(earning) sum_earn FROM vm_earnings
            WHERE unit_id='$unit' AND date < '$today'
        "));
        $prev_bal = $prev ? (float)$prev['sum_earn'] : 0;
        $today_earn = max(0, $bal - $prev_bal);
        $conn->query("
            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;
} 

date_default_timezone_set('Asia/Kolkata');

$threshold = 0.29;

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

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

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

$last_week_total = mysqli_fetch_assoc(mysqli_query($conn, "
    SELECT SUM(earning) t FROM vm_earnings
    WHERE YEARWEEK(DATE(date),1) = YEARWEEK(CURDATE(),1) - 1
"))['t'] ?? 0;

$month_total = mysqli_fetch_assoc(mysqli_query($conn, "
    SELECT SUM(earning) t FROM vm_earnings
    WHERE DATE(date) >= DATE_FORMAT(CURDATE(),'%Y-%m-01')
"))['t'] ?? 0;

$last_month_total = mysqli_fetch_assoc(mysqli_query($conn, "
    SELECT SUM(earning) t FROM vm_earnings
    WHERE DATE(date) >= DATE_FORMAT(CURDATE()-INTERVAL 1 MONTH,'%Y-%m-01')
      AND DATE(date) <  DATE_FORMAT(CURDATE(),'%Y-%m-01')
"))['t'] ?? 0;

$agg = [
    'today_total' => (float)$today_total,
    'yesterday_total' => (float)$yesterday_total,
    'week_total' => (float)$week_total,
    'month_total' => (float)$month_total,
    'last_week_total' => (float)$last_week_total,
    'last_month_total' => (float)$last_month_total
];

$today_change = ($agg['yesterday_total'] > 0)
    ? (($agg['today_total'] - $agg['yesterday_total']) / $agg['yesterday_total']) * 100 : 0;
$today_change_class = $today_change > 0 ? 'up' : 'down';
$today_change_sign = $today_change > 0 ? '+' : '';

$week_change = ($agg['last_week_total'] > 0)
    ? (($agg['week_total'] - $agg['last_week_total']) / $agg['last_week_total']) * 100 : 0;
$week_change_class = $week_change > 0 ? 'up' : 'down';
$week_change_sign = $week_change > 0 ? '+' : '';

$month_change = ($agg['last_month_total'] > 0)
    ? (($agg['month_total'] - $agg['last_month_total']) / $agg['last_month_total']) * 100 : 0;
$month_change_class = $month_change > 0 ? 'up' : 'down';
$month_change_sign = $month_change > 0 ? '+' : '';

$vms = [];


$q = $conn->query("
    SELECT
        v.unit_id,
        v.group_name,
        v.rdp_nickname,
        v.current_ip,
        v.ip_address,
        v.status,
        v.last_heartbeat,
        v.balance,
        COALESCE(t.earning,0) AS today_earn,
        COALESCE(y.earning,0) AS yesterday_earn
    FROM vms v
    LEFT JOIN vm_earnings t ON t.unit_id=v.unit_id AND DATE(t.date)=CURDATE()
    LEFT JOIN vm_earnings y ON y.unit_id=v.unit_id AND DATE(y.date)=CURDATE()-INTERVAL 1 DAY
");

while ($row = $q->fetch_assoc()) {

    $today = (float)$row['today_earn'];
    $yest  = (float)$row['yesterday_earn'];
    $change = ($yest > 0) ? (($today - $yest) / $yest) * 100 : 0;

    $isOnline = (
        !empty($row['last_heartbeat']) &&
        strtotime($row['last_heartbeat']) >= (time() - 300)
    );

    $status = strtolower(trim($row['status']));

        

    $vms[] = [
        'vm'        => $row['unit_id'],
        'rdp'       => $row['rdp_nickname'],
        'group'     => $row['group_name'],
        'ip'        => $row['current_ip'] ?? $row['ip_address'],
        'today'     => $today,
        'yesterday' => $yest,
        'total'     => (float)$row['balance'],
        'change'    => $change,
        'status'    => $row['status'],
        'online'    => $isOnline
    ];
}

$dropped_list = array_filter($vms, function($v) {
    return $v['yesterday'] > 0 && $v['today'] < $v['yesterday'];
});

$below_list = array_filter($vms, function($v) use ($threshold) {
    return $v['online'] === true
        && $v['today'] > 0
        && $v['today'] < $threshold;
});

$groups_data = [];
foreach ($vms as $v) {
    $groups_data[$v['group']][$v['rdp']][] = $v;
}


?>

<script>
document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('.group-toggle').forEach(el => {
        el.addEventListener('click', function () {
            const box = document.getElementById(this.dataset.target);
            const open = box.style.display === 'block';

            document.querySelectorAll('.group-content').forEach(g => g.style.display = 'none');
            document.querySelectorAll('.group-row').forEach(r => r.classList.remove('open'));

            if (!open) {
                box.style.display = 'block';
                this.classList.add('open');
            }
        });
    });
});
</script>

<div class="container-fluid p-4">
    <div class="row g-3 mb-4">
     <?php include __DIR__ . '/../parts/vm_top_stats.php'; ?>

     </div>

    <div class="row g-3 mb-4">
        <div class="col-md-3"><div class="stat-card"><span class="val-main">$<?= number_format($agg['today_total'],2) ?></span><span class="val-sub">Today</span></div></div>
        <div class="col-md-3"><div class="stat-card"><span class="val-main">$<?= number_format($agg['yesterday_total'],2) ?></span><span class="val-sub">Yesterday</span></div></div>
        <div class="col-md-3"><div class="stat-card"><span class="val-main"><?= count($below_list) ?></span><span class="val-sub">Below Threshold</span></div></div>
        <div class="col-md-3"><div class="stat-card"><span class="val-main"><?= count($dropped_list) ?></span><span class="val-sub">Dropped</span></div></div>
    </div>
    <div class="row g-3 mb-4">

        <div class="col-md-3">
        <div class="stat-card stat-glow green">
        <div class="stat-title">TODAY</div>
        <div class="stat-value">$<?= number_format($agg['today_total'],2) ?></div>
        <div class="stat-change <?= $today_change_class ?>">
        <?= $today_change_sign ?><?= number_format($today_change,1) ?>%
        </div>
        </div>
        </div>
        
        <div class="col-md-3">
        <div class="stat-card stat-glow red">
        <div class="stat-title">YESTERDAY</div>
        <div class="stat-value">$<?= number_format($agg['yesterday_total'],2) ?></div>
        </div>
        </div>
        
        <div class="col-md-3">
        <div class="stat-card stat-glow red">
        <div class="stat-title">THIS WEEK</div>
        <div class="stat-value">$<?= number_format($agg['week_total'],2) ?></div>
        <div class="stat-change <?= $week_change_class ?>">
        <?= $week_change_sign ?><?= number_format($week_change,1) ?>% vs last week
        </div>
        </div>
        </div>
        
        <div class="col-md-3">
        <div class="stat-card stat-glow green">
        <div class="stat-title">THIS MONTH</div>
        <div class="stat-value">$<?= number_format($agg['month_total'],2) ?></div>
        <div class="stat-change <?= $month_change_class ?>">
        <?= $month_change_sign ?><?= number_format($month_change,1) ?>% vs last month
        </div>
        </div>
        </div>
        <form method="post">
    <button type="submit" name="fetch_today" class="btn btn-warning">
        Fetch Today Earning
    </button>
</form>

        </div>


    <ul class="nav nav-pills mb-4" id="earnTabs" role="tablist">
    <li class="nav-item" role="presentation">
        <button class="nav-link active" data-bs-toggle="pill" data-bs-target="#tab-group" type="button">By Group</button>
    </li>
    <li class="nav-item" role="presentation">
        <button class="nav-link" data-bs-toggle="pill" data-bs-target="#tab-all" type="button">All VMs</button>
    </li>
    <li class="nav-item" role="presentation">
        <button class="nav-link" data-bs-toggle="pill" data-bs-target="#tab-dropped" type="button">Dropped</button>
    </li>
    <li class="nav-item" role="presentation">
        <button class="nav-link" data-bs-toggle="pill" data-bs-target="#tab-below" type="button">Below Threshold</button>
    </li>
</ul>

 
 <div class="tab-content">

   <div class="tab-pane fade show active" id="tab-group">
<?php foreach ($groups_data as $gName => $rdps): ?>
<?php
$gid = 'group-' . md5($gName);
$g_today = 0;
$g_yesterday = 0;
foreach ($rdps as $list) {
    foreach ($list as $v) {
        if ($v['today'] > 0) {
            $g_today += $v['today'];
        }
        if ($v['yesterday'] > 0) {
            $g_yesterday += $v['yesterday'];
        }
    }
}
?>
    <div class="mb-3">
        <button type="button"
            class="p-3 group-row mb-1 group-toggle w-100 text-start border-0"
            data-target="<?= $gid ?>">
            <i class="fas fa-folder me-2 text-accent"></i>
            <?= $gName ?>
            <span class="float-end small">
                Today: <b>$<?= number_format($g_today,2) ?></b> |
                Yesterday: <b>$<?= number_format($g_yesterday,2) ?></b>
            </span>
        </button>

        <div id="<?= $gid ?>" class="group-content ps-3">
            <?php foreach ($rdps as $rName => $list): ?>
                <div class="mb-2">
                    <div class="p-2 small border-bottom border-dark">
                        <?= $rName ?> (<?= count($list) ?> VMs)
                    </div>

                    <table class="table-dark-ui">
                        <thead>
                            <tr class="text-muted small">
                                <td>VM</td>
                                <td>IP</td>
                                <td>Today</td>
                                <td>Yesterday</td>
                                <td>Total</td>
                                <td>Change</td>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($list as $v): ?>
                            <tr>
                                <td><?= $v['vm'] ?></td>
                                <td><?= $v['ip'] ?></td>
                                <td>$<?= number_format($v['today'],4) ?></td>
                                <td>$<?= number_format($v['yesterday'],4) ?></td>
                                <td class="text-green">$<?= number_format($v['total'],2) ?></td>
                                <td class="<?= $v['change'] < 0 ? 'text-danger' : 'text-green' ?>">
                                    <?= number_format($v['change'],1) ?>%
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
<?php endforeach; ?>
</div>

    <div class="tab-pane fade" id="tab-all">
        <table class="table-dark-ui">
            <thead>
                <tr class="text-muted small">
                    <td>VM</td><td>RDP</td><td>Group</td><td>Today</td><td>Yesterday</td><td>Total</td>
                </tr>
            </thead>
            <tbody>
            <?php foreach($vms as $v): ?>
                <tr>
                    <td><?= $v['vm'] ?></td>
                    <td><?= $v['rdp'] ?></td>
                    <td><?= $v['group'] ?></td>
                    <td>$<?= number_format($v['today'], 4) ?></td>
                    <td>$<?= number_format($v['yesterday'], 4) ?></td>
                    <td>$<?= number_format($v['total'], 2) ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <div class="tab-pane fade" id="tab-dropped">
        <table class="table-dark-ui">
            <thead>
                <tr class="text-muted small">
                    <td>VM</td><td>RDP</td><td>Yesterday</td><td>Today</td><td>Drop %</td>
                </tr>
            </thead>
            <tbody>
            <?php foreach($dropped_list as $v): ?>
                <tr>
                    <td><?= $v['vm'] ?></td>
                    <td><?= $v['rdp'] ?></td>
                    <td>$<?= number_format($v['yesterday'], 4) ?></td>
                    <td class="text-danger">$<?= number_format($v['today'], 4) ?></td>
                    <td class="text-danger"><?= number_format($v['change'], 1) ?>%</td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <div class="tab-pane fade" id="tab-below">
        <table class="table-dark-ui">
            <thead>
                <tr class="text-muted small">
                    <td>VM</td><td>RDP</td><td>Group</td><td>Today</td><td>Threshold</td>
                </tr>
            </thead>
            <tbody>
            <?php foreach($below_list as $v): ?>
                <tr>
                    <td><?= $v['vm'] ?></td>
                    <td><?= $v['rdp'] ?></td>
                    <td><?= $v['group'] ?></td>
                    <td class="text-danger">$<?= number_format($v['today'], 4) ?></td>
                    <td>$<?= number_format($threshold, 2) ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>

</div>

</div>