<?php
if (!function_exists('isSuperAdmin')) { require_once __DIR__ . '/../db.php'; }

date_default_timezone_set('Asia/Kolkata');

$conn->query("
    CREATE TABLE IF NOT EXISTS blocked_ip_history (
        id INT AUTO_INCREMENT PRIMARY KEY,
        unit_id VARCHAR(50) NOT NULL,
        ip_address VARCHAR(50) NOT NULL,
        group_name VARCHAR(100),
        rdp_name VARCHAR(100),
        blocked_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY unique_ip (ip_address)
    )
");

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

if (isset($_GET['fetch']) && $_GET['fetch'] == '1') {
    set_time_limit(0);
    $vms_query = $conn->query("SELECT * FROM vms WHERE id IN ($_vmIdList) AND earnapp_token IS NOT NULL AND earnapp_token != ''");
    
    while ($vm = $vms_query->fetch_assoc()) {
        $token = trim($vm['earnapp_token']);
        $unit_id = $vm['unit_id'] ?? '000';
        $current_ip = $vm['current_ip'] ?? '0.0.0.0';
        $status = strtolower($vm['status'] ?? '');
        
        $ch = curl_init("https://earnapp.com/api/v2/money");
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_TIMEOUT => 20,
            CURLOPT_HTTPHEADER => [
                "Authorization: Bearer " . $token,
                "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
            ],
        ]);
        $response = curl_exec($ch);
        $data = json_decode($response, true);
        curl_close($ch);

        if (isset($data['balance'])) {
            $new_balance = (float)$data['balance'];
            $new_traffic = (float)($data['total_earnings'] ?? 0);
            $vmId = (int)$vm['vm_id'];

            $conn->query("UPDATE vms SET balance = $new_balance, traffic = $new_traffic, last_updated = UTC_TIMESTAMP() WHERE vm_id = $vmId");

            $vm_id_esc = $conn->real_escape_string((string)$vm['vm_id']);
            $rdp_esc   = $conn->real_escape_string((string)$vm['rdp_nickname']);
            $group_esc = $conn->real_escape_string((string)$vm['group_name']);
            $ip_esc    = $conn->real_escape_string((string)$current_ip);
            $token_esc = $conn->real_escape_string($token);

            $conn->query("INSERT INTO earnapp_history (vm_id, group_name, rdp_nickname, balance, total, ip_address, earnapp_token, recorded_at) VALUES ('$vm_id_esc', '$group_esc', '$rdp_esc', '$new_balance', '$new_traffic', '$ip_esc', '$token_esc', UTC_TIMESTAMP())");

            if (in_array($status, ['blocked', 'anomaly'])) {
                $unit_esc = $conn->real_escape_string($unit_id);
                $ip_esc = $conn->real_escape_string($current_ip);
                $check = $conn->query("SELECT id FROM blocked_ip_history WHERE ip_address = '$ip_esc'");
                if ($check->num_rows == 0) {
                    $conn->query("INSERT INTO blocked_ip_history (unit_id, ip_address, group_name, rdp_name, blocked_at) VALUES ('$unit_esc', '$ip_esc', '$group_esc', '$rdp_esc', UTC_TIMESTAMP())");
                }
            }
        }
    }
}

$currently_blocked_vms = $conn->query("SELECT v.* FROM vms v WHERE v.id IN ($_vmIdList) AND LOWER(v.status) IN ('blocked', 'anomaly')");

while ($vm = $currently_blocked_vms->fetch_assoc()) {
    $unit_id = $vm['unit_id'] ?? '000';
    $current_ip = $vm['current_ip'] ?? '0.0.0.0';
    $unit_esc = $conn->real_escape_string($unit_id);
    $ip_esc = $conn->real_escape_string($current_ip);
    $group_esc = $conn->real_escape_string($vm['group_name'] ?? '');
    $rdp_esc = $conn->real_escape_string($vm['rdp_nickname'] ?? '');
    $check = $conn->query("SELECT id FROM blocked_ip_history WHERE ip_address = '$ip_esc'");
    if ($check->num_rows == 0) {
        $conn->query("INSERT INTO blocked_ip_history (unit_id, ip_address, group_name, rdp_name, blocked_at) VALUES ('$unit_esc', '$ip_esc', '$group_esc', '$rdp_esc', UTC_TIMESTAMP())");
    }
}

$history_count = $conn->query("SELECT COUNT(*) as c FROM blocked_ip_history b JOIN vms v ON v.unit_id=b.unit_id WHERE v.id IN ($_vmIdList)")->fetch_assoc()['c'];
$blocked_history = $conn->query("SELECT b.* FROM blocked_ip_history b JOIN vms v ON v.unit_id = b.unit_id WHERE v.id IN ($_vmIdList) ORDER BY b.blocked_at DESC");

$stats = ['total' => 0, 'ok' => 0, 'blocked' => 0, 'unchecked' => 0];
$qTotal = $conn->query("SELECT COUNT(*) c FROM vms WHERE id IN ($_vmIdList)");
$stats['total'] = (int)$qTotal->fetch_assoc()['c'];
$qOnline = $conn->query("SELECT COUNT(*) c FROM vms WHERE id IN ($_vmIdList) AND last_heartbeat IS NOT NULL AND (last_heartbeat >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 5 MINUTE) OR LOWER(status) = 'running') AND LOWER(status) NOT IN ('blocked','anomaly')");
$stats['ok'] = (int)$qOnline->fetch_assoc()['c'];

$nested_data = [];
$blocked_vms = [];

$vms_query = $conn->query("
    SELECT v.*,
    (v.last_heartbeat IS NOT NULL AND v.last_heartbeat >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 5 MINUTE)) AS is_online_db,
    COALESCE((SELECT h.balance FROM earnapp_history h WHERE h.earnapp_token = v.earnapp_token AND DATE(h.recorded_at) = UTC_DATE() ORDER BY h.recorded_at ASC LIMIT 1), v.balance) as day_start_bal,
    COALESCE((SELECT h.balance FROM earnapp_history h WHERE h.earnapp_token = v.earnapp_token AND DATE(h.recorded_at) = SUBDATE(UTC_DATE(), 1) ORDER BY h.recorded_at DESC LIMIT 1), 0) as yest_end_bal,
    COALESCE((SELECT h.balance FROM earnapp_history h WHERE h.earnapp_token = v.earnapp_token AND DATE(h.recorded_at) = SUBDATE(UTC_DATE(), 1) ORDER BY h.recorded_at ASC LIMIT 1), 0) as yest_start_bal
    FROM vms v WHERE v.id IN ($_vmIdList)
");

while ($row = $vms_query->fetch_assoc()) {
    $cur = (float)($row['balance'] ?? 0);
    $today_start = (float)($row['day_start_bal'] ?? 0);
    $yest_start = (float)($row['yest_start_bal'] ?? 0);
    $yest_end = (float)($row['yest_end_bal'] ?? 0);

    $t_earn = max(0, $cur - $today_start);
    $y_earn = max(0, $yest_end - $yest_start);
    $change = ($y_earn > 0) ? (($t_earn - $y_earn) / $y_earn) * 100 : 0;

    $isOnline = (bool)($row['is_online_db'] ?? false) || strtolower($row['status'] ?? '') === 'running';
    $st = strtolower($row['status'] ?? '');
    $g = $row['group_name'] ?: 'Default';
    $r = $row['rdp_nickname'] ?: 'Default RDP';
    $vm_status = 'unchecked';

    if (in_array($st, ['blocked', 'anomaly'])) {
        $stats['blocked']++;
        $vm_status = 'blocked';
        $blocked_vms[] = ['unit_id' => $row['unit_id'] ?: '000', 'ip' => $row['current_ip'] ?: '-', 'earn' => $t_earn];
    } elseif ($isOnline) {
        $vm_status = 'ok';
    } else {
        $stats['unchecked']++;
    }

    if (!isset($nested_data[$g])) $nested_data[$g] = ['rdps' => [], 'total_vms' => 0, 'ok' => 0, 'blocked' => 0, 'unchecked' => 0, 'earn' => 0, 'y_earn' => 0];
    if (!isset($nested_data[$g]['rdps'][$r])) $nested_data[$g]['rdps'][$r] = ['vms' => [], 'total_vms' => 0, 'ok' => 0, 'blocked' => 0, 'unchecked' => 0, 'earn' => 0, 'y_earn' => 0];

    $vm_entry = ['unit_id' => $row['unit_id'] ?: '000', 'ip' => $row['current_ip'] ?: '-', 'status' => $vm_status, 'earn' => $t_earn, 'change' => $change];

    $nested_data[$g]['rdps'][$r]['vms'][] = $vm_entry;
    $nested_data[$g]['rdps'][$r]['total_vms']++;
    $nested_data[$g]['rdps'][$r]['earn'] += $t_earn;
    $nested_data[$g]['rdps'][$r]['y_earn'] += $y_earn;
    $nested_data[$g]['total_vms']++;
    $nested_data[$g]['earn'] += $t_earn;
    $nested_data[$g]['y_earn'] += $y_earn;

    if ($vm_status == 'ok') { $nested_data[$g]['rdps'][$r]['ok']++; $nested_data[$g]['ok']++; }
    elseif ($vm_status == 'blocked') { $nested_data[$g]['rdps'][$r]['blocked']++; $nested_data[$g]['blocked']++; }
    else { $nested_data[$g]['rdps'][$r]['unchecked']++; $nested_data[$g]['unchecked']++; }
}
?>

<style>
  :root {
    --red: #c0392b;
    --red-b: #e74c3c;
    --red-glow: rgba(192,57,43,.22);
    --green: #27ae60;
    --green-dim: rgba(39,174,96,.15);
    --yellow: #f39c12;
    --yellow-dim: rgba(243,156,18,.12);
    --s0: #090909;
    --s1: #111;
    --s2: #171717;
    --s3: #1f1f1f;
    --s4: #272727;
    --border: rgba(255,255,255,.07);
    --border-r: rgba(192,57,43,.25);
    --txt: #e8e8e8;
    --txt2: #888;
    --txt3: #555;
    --radius: 12px;
  }

  .ipa-wrap { padding: 1.75rem 1.5rem; background: var(--s0); min-height: 100vh; }

  
  .ipa-page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 1rem;
    margin-bottom: 1.75rem;
  }
  .ipa-page-title {
    display: flex;
    align-items: center;
    gap: .85rem;
  }
  .ipa-title-icon {
    width: 42px; height: 42px;
    background: linear-gradient(135deg, var(--red), #6e1209);
    border-radius: 10px;
    display: flex; align-items: center; justify-content: center;
    color: #fff; font-size: 1rem;
    box-shadow: 0 0 18px var(--red-glow);
    flex-shrink: 0;
  }
  .ipa-page-title h4 { margin: 0; color: var(--txt); font-size: 1.25rem; font-weight: 700; letter-spacing: -.3px; }
  .ipa-page-title p  { margin: 0; font-size: .78rem; color: var(--txt2); }

  .btn-check-all {
    display: inline-flex; align-items: center; gap: .5rem;
    padding: .6rem 1.5rem;
    background: linear-gradient(135deg, var(--red), #7b1a13);
    border: none; border-radius: 9px;
    color: #fff; font-weight: 700; font-size: .82rem; letter-spacing: .3px;
    cursor: pointer; text-decoration: none;
    box-shadow: 0 4px 14px var(--red-glow);
    transition: all .2s;
  }
  .btn-check-all:hover { transform: translateY(-1px); box-shadow: 0 6px 20px rgba(192,57,43,.45); color:#fff; }

  
  .ipa-stats {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 1rem;
    margin-bottom: 1.75rem;
  }
  @media(max-width:780px){ .ipa-stats { grid-template-columns: repeat(2,1fr); } }

  .ipa-stat {
    background: var(--s1);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 1.1rem 1.25rem;
    display: flex; align-items: center; gap: 1rem;
    position: relative; overflow: hidden;
    transition: border-color .2s;
  }
  .ipa-stat::before {
    content: '';
    position: absolute; left: 0; top: 0; bottom: 0;
    width: 3px;
    border-radius: 3px 0 0 3px;
  }
  .ipa-stat.s-total::before  { background: #5b8dee; }
  .ipa-stat.s-ok::before     { background: var(--green); }
  .ipa-stat.s-pending::before{ background: var(--yellow); }
  .ipa-stat.s-blocked::before{ background: var(--red); }

  .ipa-stat-icon {
    width: 38px; height: 38px; border-radius: 9px;
    display: flex; align-items: center; justify-content: center;
    font-size: .95rem; flex-shrink: 0;
  }
  .s-total  .ipa-stat-icon { background: rgba(91,141,238,.12); color: #5b8dee; }
  .s-ok     .ipa-stat-icon { background: var(--green-dim);     color: var(--green); }
  .s-pending .ipa-stat-icon { background: var(--yellow-dim);   color: var(--yellow); }
  .s-blocked .ipa-stat-icon { background: var(--red-glow);     color: var(--red-b); }

  .ipa-stat-info { min-width: 0; }
  .ipa-stat-val  { font-size: 1.6rem; font-weight: 800; color: var(--txt); line-height: 1; margin-bottom: .2rem; }
  .ipa-stat-lbl  { font-size: .72rem; color: var(--txt2); text-transform: uppercase; letter-spacing: .8px; }

  
  .ipa-tabs {
    display: flex; gap: .25rem;
    border-bottom: 1px solid var(--border);
    margin-bottom: 1.5rem;
    flex-wrap: wrap;
  }
  .ipa-tab-btn {
    padding: .65rem 1.2rem;
    background: none; border: none;
    border-bottom: 2px solid transparent;
    color: var(--txt2); font-size: .83rem; font-weight: 600;
    cursor: pointer; transition: all .2s;
    display: flex; align-items: center; gap: .5rem;
    white-space: nowrap;
    margin-bottom: -1px;
  }
  .ipa-tab-btn:hover { color: var(--txt); }
  .ipa-tab-btn.active { color: var(--txt); border-bottom-color: var(--red-b); }
  .ipa-tab-btn .tab-badge {
    padding: .15rem .5rem; border-radius: 20px; font-size: .7rem; font-weight: 700;
  }
  .ipa-tab-btn .tab-badge.danger  { background: rgba(192,57,43,.2); color: var(--red-b); }
  .ipa-tab-btn .tab-badge.warning { background: var(--yellow-dim); color: var(--yellow); }
  .ipa-tab-btn .tab-badge.muted   { background: var(--s3); color: var(--txt2); }

  .ipa-tab-pane { display: none; }
  .ipa-tab-pane.active { display: block; }

  
  .acc-group {
    background: var(--s1);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    margin-bottom: .75rem;
    overflow: hidden;
  }

  .acc-head {
    display: flex; align-items: center; justify-content: space-between;
    padding: .9rem 1.25rem;
    cursor: pointer;
    background: linear-gradient(90deg, rgba(192,57,43,.04) 0%, transparent 50%);
    border-bottom: 1px solid transparent;
    transition: background .2s;
    gap: 1rem;
  }
  .acc-head:hover { background: linear-gradient(90deg, rgba(192,57,43,.09) 0%, rgba(255,255,255,.02) 60%); }
  .acc-head.open  { border-bottom-color: var(--border); }

  .acc-head-left { display: flex; align-items: center; gap: .75rem; min-width: 0; }
  .acc-head-left i { color: #a78bfa; font-size: .9rem; flex-shrink: 0; }
  .acc-group-name { font-weight: 700; font-size: .88rem; color: var(--txt); text-transform: uppercase; letter-spacing: .5px; }
  .acc-vm-count { font-size: .72rem; background: rgba(167,139,250,.12); color: #a78bfa; padding: .15rem .55rem; border-radius: 20px; font-weight: 600; }

  .acc-head-right { display: flex; align-items: center; gap: .6rem; flex-shrink: 0; }
  .mini-pill {
    display: inline-flex; align-items: center; gap: .3rem;
    padding: .2rem .65rem; border-radius: 20px; font-size: .72rem; font-weight: 600;
  }
  .pill-ok      { background: var(--green-dim); color: var(--green); }
  .pill-blocked { background: var(--red-glow);  color: var(--red-b); }
  .pill-unk     { background: var(--s3);         color: var(--txt2); }
  .acc-chevron  { color: var(--txt3); font-size: .75rem; transition: transform .2s; flex-shrink:0; }
  .acc-head.open .acc-chevron { transform: rotate(180deg); }

  .acc-body { display: none; }
  .acc-body.open { display: block; }

  
  .rdp-section { padding: .75rem 1.25rem 0; }
  .rdp-label {
    font-size: .7rem; text-transform: uppercase; letter-spacing: 1px;
    color: var(--txt3); font-weight: 600; margin-bottom: .6rem;
    display: flex; align-items: center; gap: .5rem;
  }
  .rdp-label::after { content:''; flex:1; height:1px; background: var(--border); }

  .vm-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(230px, 1fr));
    gap: .6rem;
    margin-bottom: 1rem;
  }

  .vm-card {
    background: var(--s2);
    border: 1px solid var(--border);
    border-radius: 9px;
    padding: .75rem 1rem;
    display: flex; align-items: center; gap: .75rem;
    transition: border-color .2s;
  }
  .vm-card:hover { border-color: rgba(255,255,255,.13); }
  .vm-card.vm-ok      { border-left: 3px solid var(--green); }
  .vm-card.vm-blocked { border-left: 3px solid var(--red-b); }
  .vm-card.vm-unchecked { border-left: 3px solid var(--txt3); }

  .vm-dot {
    width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0;
  }
  .vm-ok      .vm-dot { background: var(--green); box-shadow: 0 0 6px var(--green); }
  .vm-blocked .vm-dot { background: var(--red-b);  box-shadow: 0 0 6px var(--red-b); }
  .vm-unchecked .vm-dot { background: var(--txt3); }

  .vm-info { min-width: 0; flex: 1; }
  .vm-uid  { font-size: .8rem; font-weight: 700; color: var(--txt); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
  .vm-ip   { font-size: .73rem; color: var(--txt2); margin-top: .1rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

  .vm-status-tag {
    font-size: .65rem; font-weight: 700; letter-spacing: .5px;
    padding: .15rem .5rem; border-radius: 4px; flex-shrink: 0;
  }
  .vm-ok .vm-status-tag       { background: var(--green-dim);  color: var(--green); }
  .vm-blocked .vm-status-tag  { background: var(--red-glow);   color: var(--red-b); }
  .vm-unchecked .vm-status-tag{ background: var(--s4);         color: var(--txt3); }

  
  .ipa-table-wrap {
    background: var(--s1);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    overflow: hidden;
  }
  .ipa-table-head {
    padding: 1rem 1.5rem;
    border-bottom: 1px solid var(--border);
    display: flex; align-items: center; justify-content: space-between;
    background: linear-gradient(90deg, rgba(192,57,43,.05) 0%, transparent 60%);
  }
  .ipa-table-head h6 { margin: 0; color: var(--txt); font-weight: 700; font-size: .9rem; }
  .ipa-count-badge { background: var(--red-glow); color: var(--red-b); padding: .2rem .7rem; border-radius: 20px; font-size: .72rem; font-weight: 700; }

  .ipa-table {
    width: 100%; border-collapse: collapse;
  }
  .ipa-table thead tr {
    background: var(--s2);
  }
  .ipa-table thead th {
    padding: .75rem 1.25rem;
    font-size: .7rem; text-transform: uppercase; letter-spacing: .8px;
    color: var(--txt2); font-weight: 600; border: none;
    white-space: nowrap;
  }
  .ipa-table tbody tr {
    border-top: 1px solid var(--border);
    transition: background .15s;
  }
  .ipa-table tbody tr:hover { background: rgba(255,255,255,.025); }
  .ipa-table td {
    padding: .8rem 1.25rem;
    color: var(--txt); font-size: .84rem; border: none; vertical-align: middle;
  }
  .ipa-table td code {
    background: var(--s3); border: 1px solid var(--border-r);
    color: var(--red-b); padding: .2rem .6rem; border-radius: 5px; font-size: .8rem;
  }

  .badge-unit { background: var(--s3); color: var(--txt2); padding: .2rem .6rem; border-radius: 5px; font-size: .75rem; font-weight: 600; }
  .badge-archived { background: var(--s3); color: var(--txt3); padding: .2rem .65rem; border-radius: 5px; font-size: .72rem; font-weight: 600; }
  .badge-blocked  { background: var(--red-glow); color: var(--red-b); padding: .2rem .65rem; border-radius: 5px; font-size: .72rem; font-weight: 700; }

  
  .ipa-empty {
    text-align: center; padding: 4rem 2rem;
  }
  .ipa-empty i { font-size: 2.5rem; margin-bottom: 1rem; display: block; }
  .ipa-empty h5 { color: var(--txt); margin-bottom: .4rem; }
  .ipa-empty p  { color: var(--txt2); font-size: .85rem; margin: 0; }
</style>

<div class="ipa-wrap">

  
  <div class="ipa-page-header">
    <div class="ipa-page-title">
      <div class="ipa-title-icon"><i class="fas fa-network-wired"></i></div>
      <div>
        <h4>IP Analysis</h4>
        <p>Monitor, track and review all VM IP statuses</p>
      </div>
    </div>
    <a href="?page=ip-analysis&fetch=1" class="btn-check-all">
      <i class="fas fa-search"></i> Check All IPs
    </a>
  </div>

  
  <div class="ipa-stats">
    <div class="ipa-stat s-total">
      <div class="ipa-stat-icon"><i class="fas fa-desktop"></i></div>
      <div class="ipa-stat-info">
        <div class="ipa-stat-val"><?= $stats['total'] ?></div>
        <div class="ipa-stat-lbl">Total VMs</div>
      </div>
    </div>
    <div class="ipa-stat s-ok">
      <div class="ipa-stat-icon"><i class="fas fa-check-circle"></i></div>
      <div class="ipa-stat-info">
        <div class="ipa-stat-val"><?= $stats['ok'] ?></div>
        <div class="ipa-stat-lbl">Online</div>
      </div>
    </div>
    <div class="ipa-stat s-pending">
      <div class="ipa-stat-icon"><i class="fas fa-clock"></i></div>
      <div class="ipa-stat-info">
        <div class="ipa-stat-val"><?= $stats['unchecked'] ?></div>
        <div class="ipa-stat-lbl">Pending</div>
      </div>
    </div>
    <div class="ipa-stat s-blocked">
      <div class="ipa-stat-icon"><i class="fas fa-ban"></i></div>
      <div class="ipa-stat-info">
        <div class="ipa-stat-val"><?= $stats['blocked'] ?></div>
        <div class="ipa-stat-lbl">Blocked</div>
      </div>
    </div>
  </div>

  
  <div class="ipa-tabs">
    <button class="ipa-tab-btn active" onclick="switchTab('allTab', this)">
      <i class="fas fa-list"></i> All VMs
      <span class="tab-badge muted"><?= $stats['total'] ?></span>
    </button>
    <button class="ipa-tab-btn" onclick="switchTab('blockedTab', this)">
      <i class="fas fa-ban"></i> Currently Blocked
      <span class="tab-badge danger"><?= $stats['blocked'] ?></span>
    </button>
    <button class="ipa-tab-btn" onclick="switchTab('historyTab', this)">
      <i class="fas fa-history"></i> Blocked IP History
      <span class="tab-badge warning"><?= $history_count ?></span>
    </button>
  </div>

  
  <div class="ipa-tab-pane active" id="allTab">
    <?php foreach($nested_data as $groupName => $group):
      $gid = md5((string)$groupName);
    ?>
    <div class="acc-group">
      <div class="acc-head" onclick="toggleAcc('<?= $gid ?>', this)">
        <div class="acc-head-left">
          <i class="fas fa-folder-open"></i>
          <span class="acc-group-name"><?= htmlspecialchars((string)$groupName) ?></span>
          <span class="acc-vm-count"><?= (int)$group['total_vms'] ?> VMs</span>
        </div>
        <div class="acc-head-right">
          <span class="mini-pill pill-ok"><i class="fas fa-check fa-xs"></i> <?= (int)$group['ok'] ?></span>
          <span class="mini-pill pill-blocked"><i class="fas fa-ban fa-xs"></i> <?= (int)$group['blocked'] ?></span>
          <span class="mini-pill pill-unk"><i class="fas fa-question fa-xs"></i> <?= (int)$group['unchecked'] ?></span>
          <i class="fas fa-chevron-down acc-chevron"></i>
        </div>
      </div>
      <div class="acc-body open" id="acc-<?= $gid ?>">
        <?php foreach($group['rdps'] as $rdpName => $rdp): ?>
        <div class="rdp-section">
          <div class="rdp-label"><i class="fas fa-server fa-xs"></i> <?= htmlspecialchars((string)$rdpName) ?></div>
          <div class="vm-grid">
            <?php foreach($rdp['vms'] as $vm): ?>
            <div class="vm-card vm-<?= $vm['status'] ?>">
              <div class="vm-dot"></div>
              <div class="vm-info">
                <div class="vm-uid"><?= htmlspecialchars($vm['unit_id']) ?></div>
                <div class="vm-ip"><i class="fas fa-wifi fa-xs me-1"></i><?= htmlspecialchars($vm['ip']) ?></div>
              </div>
              <div class="vm-status-tag"><?= strtoupper($vm['status'] === 'ok' ? 'OK' : ($vm['status'] === 'unchecked' ? 'OFFLINE' : $vm['status'])) ?></div>
            </div>
            <?php endforeach; ?>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endforeach; ?>
  </div>

  
  <div class="ipa-tab-pane" id="blockedTab">
    <?php if(count($blocked_vms) > 0): ?>
    <div class="ipa-table-wrap">
      <div class="ipa-table-head">
        <h6><i class="fas fa-ban me-2" style="color:var(--red-b)"></i> Currently Blocked VMs</h6>
        <span class="ipa-count-badge"><?= count($blocked_vms) ?> blocked</span>
      </div>
      <div style="overflow-x:auto;">
        <table class="ipa-table">
          <thead>
            <tr>
              <th>Unit ID</th>
              <th>Current IP</th>
              <th>Today's Earnings</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach($blocked_vms as $vm): ?>
            <tr>
              <td><span class="badge-unit"><?= htmlspecialchars($vm['unit_id']) ?></span></td>
              <td><code><?= htmlspecialchars($vm['ip']) ?></code></td>
              <td style="color:var(--red-b); font-weight:700;">$<?= number_format((float)$vm['earn'], 2) ?></td>
              <td><span class="badge-blocked">BLOCKED</span></td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
    <?php else: ?>
    <div class="ipa-empty">
      <i class="fas fa-check-circle" style="color:var(--green)"></i>
      <h5>No Blocked VMs</h5>
      <p>All systems are running normally.</p>
    </div>
    <?php endif; ?>
  </div>

  
  <div class="ipa-tab-pane" id="historyTab">
    <div class="ipa-table-wrap">
      <div class="ipa-table-head">
        <h6><i class="fas fa-archive me-2" style="color:var(--yellow)"></i> Blocked IP History</h6>
        <span class="ipa-count-badge"><?= $history_count ?> recorded</span>
      </div>
      <?php if($blocked_history->num_rows > 0): ?>
      <div style="overflow-x:auto;">
        <table class="ipa-table">
          <thead>
            <tr>
              <th>Unit ID</th>
              <th>IP Address</th>
              <th>Group</th>
              <th>RDP Name</th>
              <th>Blocked At</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
            <?php while($ip = $blocked_history->fetch_assoc()): ?>
            <tr>
              <td><span class="badge-unit"><?= htmlspecialchars($ip['unit_id']) ?></span></td>
              <td><code><?= htmlspecialchars($ip['ip_address']) ?></code></td>
              <td style="color:var(--txt2)"><?= htmlspecialchars($ip['group_name']) ?></td>
              <td style="color:var(--txt2)"><?= htmlspecialchars($ip['rdp_name']) ?></td>
              <td style="color:var(--txt2)">
                <i class="far fa-clock me-1" style="color:var(--txt3)"></i>
                <?= date('Y-m-d H:i', strtotime($ip['blocked_at'])) ?>
              </td>
              <td><span class="badge-archived">Archived</span></td>
            </tr>
            <?php endwhile; ?>
          </tbody>
        </table>
      </div>
      <?php else: ?>
      <div class="ipa-empty">
        <i class="fas fa-inbox" style="color:var(--txt3)"></i>
        <h5>No History Yet</h5>
        <p>Blocked IP records will appear here automatically.</p>
      </div>
      <?php endif; ?>
    </div>
  </div>

</div>

<script>
function switchTab(id, btn) {
  document.querySelectorAll('.ipa-tab-pane').forEach(p => p.classList.remove('active'));
  document.querySelectorAll('.ipa-tab-btn').forEach(b => b.classList.remove('active'));
  document.getElementById(id).classList.add('active');
  btn.classList.add('active');
}

function toggleAcc(id, head) {
  const body = document.getElementById('acc-' + id);
  const isOpen = body.classList.contains('open');
  body.classList.toggle('open', !isOpen);
  head.classList.toggle('open', !isOpen);
}

document.querySelectorAll('.acc-head').forEach(h => h.classList.add('open'));
</script>