<?php
require_once 'db.php';

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

$threshold = 0.29;

$today            = date('Y-m-d');
$yesterday        = date('Y-m-d', strtotime('-1 day'));
$week_start = date('Y-m-d', strtotime('-6 days'));
$month_start      = date('Y-m-01');
$last_week_start  = date('Y-m-d', strtotime('monday last week'));
$last_week_end    = date('Y-m-d', strtotime('sunday last week'));
$last_month_start = date('Y-m-01', strtotime('first day of last month'));
$last_month_end   = date('Y-m-t',  strtotime('last day of last month'));


function daily_earned_query($conn, $date) {
    $prev = date('Y-m-d', strtotime($date . ' -1 day'));
    $r = $conn->query("
        SELECT t.vm_id, GREATEST(0, t.curr_max - IFNULL(p.prev_max, 0)) AS earned
        FROM (
            SELECT vm_id, MAX(CAST(balance AS DECIMAL(10,4))) AS curr_max
            FROM earnapp_history WHERE DATE(recorded_at) = '$date'
            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) = '$prev'
            GROUP BY vm_id
        ) p ON p.vm_id = t.vm_id
    ");
    $result = [];
    while ($row = $r->fetch_assoc()) {
        $result[$row['vm_id']] = (float)$row['earned'];
    }
    return $result;
}
 
function range_earned_query($conn, $from, $to) {
    $r = $conn->query("
        SELECT IFNULL(SUM(daily_earned), 0) AS earned
        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 '$from' AND '$to'
                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
    ");
    $row = $r->fetch_assoc();
    return (float)($row['earned'] ?? 0);
}

$today_bal_map   = daily_earned_query($conn, $today);
$yest_bal_map    = daily_earned_query($conn, $yesterday);

$today_total      = array_sum($today_bal_map);
$yesterday_total  = array_sum($yest_bal_map);
$week_total       = range_earned_query($conn, $week_start, $today);
$last_week_total  = range_earned_query($conn, $last_week_start, $last_week_end);
$month_total      = range_earned_query($conn, $month_start, $today);
$last_month_total = range_earned_query($conn, $last_month_start, $last_month_end);

$agg = [
    'today_total'      => $today_total,
    'yesterday_total'  => $yesterday_total,
    'week_total'       => $week_total,
    'month_total'      => $month_total,
    'last_week_total'  => $last_week_total,
    'last_month_total' => $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 ? '+' : '';

$history_vms = [];
$r = $conn->query("
    SELECT vm_id, group_name, rdp_nickname, ip_address
    FROM earnapp_history
    WHERE recorded_at >= NOW() - INTERVAL 30 DAY
    GROUP BY vm_id
");
while ($row = $r->fetch_assoc()) {
    $history_vms[$row['vm_id']] = [
        'group' => $row['group_name'],
        'rdp'   => $row['rdp_nickname'],
        'ip'    => $row['ip_address']
    ];
}

$vms = [];
foreach ($history_vms as $vid => $info) {
    $today_earned = $today_bal_map[$vid] ?? 0;
    $yest_earned  = $yest_bal_map[$vid]  ?? 0;
    $change       = ($yest_earned > 0) ? (($today_earned - $yest_earned) / $yest_earned) * 100 : 0;

    $vms[] = [
        'vm'        => $vid,
        'rdp'       => $info['rdp'],
        'group'     => $info['group'],
        'ip'        => $info['ip'],
        'today'     => $today_earned,
        'yesterday' => $yest_earned,
        'total'     => 0,
        'change'    => $change,
        'online'    => false
    ];
}

$vms_db = [];
$q = $conn->query("SELECT unit_id, earnapp_token, current_ip, ip_address, status, last_heartbeat, balance FROM vms");
while ($row = $q->fetch_assoc()) {
    $vms_db[$row['earnapp_token']] = $row;
}

$token_map = [];
$r = $conn->query("SELECT vm_id, earnapp_token FROM earnapp_history WHERE earnapp_token IS NOT NULL GROUP BY vm_id");
while ($row = $r->fetch_assoc()) $token_map[$row['vm_id']] = $row['earnapp_token'];

foreach ($vms as &$v) {
    $vid   = $v['vm'];
    $token = $token_map[$vid] ?? null;
    if ($token && isset($vms_db[$token])) {
        $dbrow = $vms_db[$token];
        $v['vm']     = $dbrow['unit_id'];
        $v['ip']     = $dbrow['current_ip'] ?? $dbrow['ip_address'];
        $v['total']  = (float)$dbrow['balance'];
        $v['online'] = (!empty($dbrow['last_heartbeat']) && strtotime($dbrow['last_heartbeat']) >= (time() - 300));
    }
}
unset($v);

$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) {
    if (empty($v['group'])) continue;
    $groups_data[$v['group']][$v['rdp']][] = $v;
}
ksort($groups_data);
?>

<script>
document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('.toggle-btn').forEach(el => {
        el.addEventListener('click', function (e) {
            e.stopPropagation();
            const targetId = this.dataset.target;
            const box = document.getElementById(targetId);
            if (box) {
                const isOpen = box.style.display === 'block';
                box.style.display = isOpen ? 'none' : 'block';
                if (!isOpen) this.classList.add('open'); else this.classList.remove('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) ?>% vs yesterday</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 blue">
                <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>
    </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) { $g_today += $v['today']; $g_yesterday += $v['yesterday']; }
            ?>
                <div class="mb-3">
                    <button type="button" class="p-3 group-row mb-1 toggle-btn w-100 text-start border-0" data-target="<?= $gid ?>" style="background: #2b3035; color: #fff;">
                        <i class="fas fa-folder me-2 text-accent"></i>
                        <strong><?= htmlspecialchars($gName) ?></strong>
                        <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 ?>" style="display:none; padding-left: 15px; border-left: 2px solid #444;">
                        <?php foreach ($rdps as $rName => $list): ?>
                        <?php
                            $rid = 'rdp-' . md5($gName . $rName);
                            $r_today = 0; $r_yesterday = 0;
                            foreach ($list as $v) { $r_today += $v['today']; $r_yesterday += $v['yesterday']; }
                        ?>
                            <div class="mt-1">
                                <button type="button" class="p-2 w-100 text-start border-0 toggle-btn" data-target="<?= $rid ?>" style="background: #343a40; color: #ccc;">
                                    <i class="fas fa-server me-2"></i>
                                    <?= htmlspecialchars($rName) ?> (<?= count($list) ?> VMs)
                                    <span class="float-end small">
                                        Today: <b>$<?= number_format($r_today,2) ?></b> |
                                        Yesterday: <b>$<?= number_format($r_yesterday,2) ?></b>
                                    </span>
                                </button>

                                <div id="<?= $rid ?>" style="display:none; padding: 10px; background: #212529;">
                                    <table class="table-dark-ui w-100">
                                        <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><?= htmlspecialchars($v['vm']) ?></td>
                                                <td><?= htmlspecialchars($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>
                            </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><?= htmlspecialchars($v['vm']) ?></td>
                        <td><?= htmlspecialchars($v['rdp']) ?></td>
                        <td><?= htmlspecialchars($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><?= htmlspecialchars($v['vm']) ?></td>
                        <td><?= htmlspecialchars($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>IP Address</td><td>RDP</td><td>Group</td><td>Today</td><td>Threshold</td>
                    </tr>
                </thead>
                <tbody>
                <?php foreach($below_list as $v): ?>
                    <tr>
                        <td><?= htmlspecialchars($v['vm']) ?></td>
                        <td><?= htmlspecialchars($v['ip']) ?></td>
                        <td><?= htmlspecialchars($v['rdp']) ?></td>
                        <td><?= htmlspecialchars($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>