<?php
require_once __DIR__ . '/auth.php';

// Ignored Admin/Test Accounts
$ignored_uids = [1, 6];
$ignored_sql = implode(',', $ignored_uids);

// Handle UI Toggle for Banned Users
$show_banned = isset($_GET['show_banned']) && $_GET['show_banned'] === '1';

// Handle AJAX Request for Banning an Entire Syndicate
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'ban_chain') {
    header('Content-Type: application/json');
    $uids = isset($_POST['uids']) ? explode(',', $_POST['uids']) : [];
    $count = 0;
    foreach($uids as $uid) {
        $uid = (int)$uid;
        if($uid > 0 && !in_array($uid, $ignored_uids)) {
            $pdo->prepare("UPDATE users SET isbanned = 1 WHERE id = ?")->execute([$uid]);
            $count++;
        }
    }
    echo json_encode(['ok' => true, 'msg' => "Dismantled threat group. Banned $count users."]);
    exit;
}

// ============================================================================
// 1. UNIFIED WINGO GAMING ANALYSIS
// ============================================================================
$wingo_stats = [];
try {
    $w_st = $pdo->query("
        SELECT 
            user_id as uid, COUNT(*) as total_rounds, SUM(amount) as total_bet, SUM(payout) as total_win
        FROM (
            SELECT user_id, amount, payout FROM wingo_bets
            UNION ALL
            SELECT user_id, amount, payout FROM wingo_bets_1min
        ) as combined_tables
        WHERE user_id NOT IN ($ignored_sql)
        GROUP BY user_id
    ");
    while($row = $w_st->fetch(PDO::FETCH_ASSOC)) {
        $wingo_stats[$row['uid']] = $row;
    }
} catch (Exception $e) {}

// ============================================================================
// 2. BASE USER PROFILING (PASS 1)
// ============================================================================
$st_users = $pdo->query("SELECT * FROM users WHERE id NOT IN ($ignored_sql) ORDER BY id ASC");
$all_users = $st_users->fetchAll(PDO::FETCH_ASSOC);

$user_profiles = [];
$whale_threshold = 20000;

foreach($all_users as $u) {
    $uid = $u['id'];
    
    // Initialize custom profiling fields
    $u['risk_score'] = 0;
    $u['flags'] = [];
    $u['category_count'] = 0;
    $u['net_loss'] = ($u['total_withdrawn'] ?? 0) - $u['total_deposits'];
    
    $w_rounds = $wingo_stats[$uid]['total_rounds'] ?? 0;
    $w_bet = $wingo_stats[$uid]['total_bet'] ?? 0;
    $w_win = $wingo_stats[$uid]['total_win'] ?? 0;
    $w_net = $w_win - $w_bet;
    $u['wingo'] = ['rounds' => $w_rounds, 'bet' => $w_bet, 'win' => $w_win, 'net' => $w_net];

    // Rule A: Financial Risk
    if (($u['total_withdrawn'] ?? 0) > 0 && $u['total_deposits'] == 0) {
        $u['risk_score'] += 45;
        $u['flags'][] = ['name' => '0-Dep Payout', 'color' => 'red'];
        $u['category_count']++;
    } elseif (($u['total_withdrawn'] ?? 0) > 5000 && ($u['total_withdrawn'] ?? 0) > ($u['total_deposits'] * 4)) {
        $u['risk_score'] += 35;
        $u['flags'][] = ['name' => 'High W/D Ratio', 'color' => 'orange'];
        $u['category_count']++;
    }

    // Rule B: Wingo Exploitations
    if ($w_rounds >= 5 && $w_net > 500 && $w_win > ($w_bet * 1.35)) {
        $u['risk_score'] += 30;
        $u['flags'][] = ['name' => 'Wingo Anomaly', 'color' => 'purple'];
        $u['category_count']++;
    }
    
    $user_profiles[$uid] = $u;
}

// ============================================================================
// 3. ADVANCED SYNDICATE DETECTION (PASS 2 - MODIFIES BY REFERENCE)
// ============================================================================
$profiled_in_syndicate = [];

// --- A. PASSWORD SYNDICATES ---
$st_pw = $pdo->query("SELECT password, COUNT(id) as c FROM users WHERE password IS NOT NULL AND password != '' AND id NOT IN ($ignored_sql) GROUP BY password HAVING c > 1 ORDER BY c DESC");
$pw_groups = $st_pw->fetchAll(PDO::FETCH_ASSOC);

foreach($pw_groups as $g) {
    $refercodes = [];
    $earliest_user_id = null;
    $earliest_time = null;

    // Find Mastermind
    foreach($user_profiles as $uid => $u) {
        if($u['password'] === $g['password']) {
            $refercodes[] = $u['refercode'];
            $user_time = strtotime($u['created_at']);
            if ($earliest_time === null || $user_time < $earliest_time) {
                $earliest_time = $user_time;
                $earliest_user_id = $uid;
            }
        }
    }

    // Assign Threat Levels
    foreach($user_profiles as $uid => &$u) {
        if($u['password'] === $g['password']) {
            $u['u_role_pw'] = ($uid === $earliest_user_id) ? 'MASTERMIND' : 'MEMBER';
            $u['risk_score'] += ($u['u_role_pw'] === 'MASTERMIND') ? 45 : 30;
            $u['flags'][] = ['name' => ($u['u_role_pw'] === 'MASTERMIND') ? 'Syndicate Root' : 'Shared PWD', 'color' => ($u['u_role_pw'] === 'MASTERMIND') ? 'red' : 'blue'];
            $u['category_count']++;

            if(!empty($u['referedby']) && in_array($u['referedby'], $refercodes)) {
                $u['risk_score'] += 25;
                $u['flags'][] = ['name' => 'Self-Referred', 'color' => 'orange'];
            }
            $u['syndicate_pw'] = $g['password'];
            $profiled_in_syndicate[] = $uid;
        }
    }
    unset($u);
}

// --- B. IP SYNDICATES (New Logic) ---
// Find IPs with more than 3 accounts
$st_ip = $pdo->query("SELECT ip, COUNT(id) as c FROM users WHERE ip IS NOT NULL AND ip != '' AND id NOT IN ($ignored_sql) GROUP BY ip HAVING c > 3 ORDER BY c DESC");
$ip_groups = $st_ip->fetchAll(PDO::FETCH_ASSOC);

foreach($ip_groups as $g) {
    // Gather UIDs for this IP
    $ip_uids = [];
    foreach($user_profiles as $uid => $u) {
        if(isset($u['ip']) && $u['ip'] === $g['ip']) {
            $ip_uids[] = $uid;
        }
    }
    
    // Sort by ID to find the first 3
    usort($ip_uids, fn($a, $b) => $user_profiles[$a]['id'] <=> $user_profiles[$b]['id']);
    
    foreach($ip_uids as $idx => $uid) {
        $u = &$user_profiles[$uid];
        $u['syndicate_ip'] = $g['ip'];
        $profiled_in_syndicate[] = $uid;
        $u['category_count']++;
        
        if ($idx < 3) { // First 3 accounts are permitted residents
            $u['u_role_ip'] = 'RESIDENT';
            $u['risk_score'] += 10;
            $u['flags'][] = ['name' => 'IP Resident', 'color' => 'blue'];
        } else { // 4th account onwards are clones
            $u['u_role_ip'] = 'CLONE';
            $u['risk_score'] += 40;
            $u['flags'][] = ['name' => 'IP Clone', 'color' => 'red'];
        }
    }
    unset($u);
}

// --- C. CROSS-ABUSER NORMALIZATION ---
$total_exposure = 0;
foreach($user_profiles as $uid => &$u) {
    if($u['category_count'] >= 2) {
        $u['flags'][] = ['name' => 'Cross-Abuser (' . $u['category_count'] . ')', 'color' => 'red'];
        $u['risk_score'] += 15;
    }
    $u['risk_score'] = min(100, $u['risk_score']);
    
    // Calculate global active exposure (Ensures no double counting)
    if(!$u['isbanned'] && $u['net_loss'] > 0 && count($u['flags']) > 0) {
        $total_exposure += $u['net_loss'];
    }
}
unset($u);


// ============================================================================
// 4. BUILD FINAL UI RENDER ARRAYS (PASS 3 - VIEW LOGIC)
// ============================================================================
$syndicates_ui = [];

// Render Password Rings
foreach($pw_groups as $g) {
    $render_users = [];
    $ring_loss = 0;
    foreach($user_profiles as $uid => $u) {
        if(isset($u['syndicate_pw']) && $u['syndicate_pw'] === $g['password']) {
            if (!$u['isbanned'] || $show_banned) {
                $render_users[] = $u;
                if (!$u['isbanned']) $ring_loss += $u['net_loss']; // Only active loss
            }
        }
    }
    if(count($render_users) > 0) {
        usort($render_users, fn($a, $b) => $b['risk_score'] <=> $a['risk_score']);
        $syndicates_ui[] = [
            'type' => 'password',
            'title' => "Password Vault Ring (" . count($render_users) . " Nodes)",
            'subtitle' => "Shared Password Signature: <span style='font-family:monospace;background:#2a3042;padding:2px 6px;border-radius:4px;color:#f26d0f;'>" . htmlspecialchars($g['password']) . "</span>",
            'users' => $render_users,
            'loss' => $ring_loss
        ];
    }
}

// Render IP Rings
foreach($ip_groups as $g) {
    $render_users = [];
    $ring_loss = 0;
    foreach($user_profiles as $uid => $u) {
        if(isset($u['syndicate_ip']) && $u['syndicate_ip'] === $g['ip']) {
            if (!$u['isbanned'] || $show_banned) {
                $render_users[] = $u;
                if (!$u['isbanned']) $ring_loss += $u['net_loss'];
            }
        }
    }
    if(count($render_users) > 0) {
        usort($render_users, fn($a, $b) => $b['risk_score'] <=> $a['risk_score']);
        $syndicates_ui[] = [
            'type' => 'ip',
            'title' => "IP Network Anomaly (" . count($render_users) . " Nodes)",
            'subtitle' => "Shared IP Address: <span style='font-family:monospace;background:#2a3042;padding:2px 6px;border-radius:4px;color:#3b82f6;'>" . htmlspecialchars($g['ip']) . "</span> (First 3 allowed, rest flagged)",
            'users' => $render_users,
            'loss' => $ring_loss
        ];
    }
}

// Standalone Threats
$standalone_threats = [];
foreach($user_profiles as $uid => $u) {
    if(!in_array($uid, $profiled_in_syndicate) && count($u['flags']) > 0) {
        if(!$u['isbanned'] || $show_banned) {
            $standalone_threats[] = $u;
        }
    }
}
usort($standalone_threats, fn($a, $b) => $b['risk_score'] <=> $a['risk_score']);

// High Balance Whales
$manual_audit_whales = [];
foreach($user_profiles as $uid => $u) {
    if($u['balance'] >= $whale_threshold) {
        if(!$u['isbanned'] || $show_banned) {
            $manual_audit_whales[] = $u;
        }
    }
}
usort($manual_audit_whales, fn($a, $b) => $b['balance'] <=> $a['balance']);
?>
<!DOCTYPE html>
<html lang="en"><head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>SOC Dashboard — PakClub Admin</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
/* Same CSS Base */
*{box-sizing:border-box;margin:0;padding:0}
body{background:#090b11;color:#d1d5db;font-family:'Segoe UI',sans-serif;display:flex;min-height:100vh}
.main{flex:1;overflow-x:hidden}
.topbar{background:#111520;border-bottom:1px solid rgba(255,255,255,.05);padding:18px 28px;display:flex;align-items:center;justify-content:space-between}
.topbar h2{font-size:19px;font-weight:700;color:#fff;display:flex;align-items:center;gap:10px}
.content{padding:24px 28px}

.stats-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:20px;margin-bottom:28px}
.stat-card{background:#121622;border:1px solid rgba(255,255,255,.05);border-radius:12px;padding:20px;display:flex;align-items:center;gap:16px}
.stat-icon{width:44px;height:44px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:18px}
.stat-icon.danger{background:rgba(239,68,68,.1);color:#ef4444}
.stat-icon.warning{background:rgba(242,109,15,.1);color:#f26d0f}
.stat-icon.audit{background:rgba(59,130,246,.1);color:#3b82f6}
.stat-info h4{font-size:11px;color:#9ca3af;text-transform:uppercase;letter-spacing:1px;margin-bottom:2px}
.stat-info .val{font-size:22px;font-weight:700;color:#fff}

.panel-section-title{font-size:14px;font-weight:700;text-transform:uppercase;letter-spacing:1px;color:#9ca3af;margin:24px 0 12px;display:flex;align-items:center;gap:8px}
.soc-panel{background:#111520;border:1px solid rgba(255,255,255,.06);border-radius:12px;overflow:hidden;margin-bottom:24px}
.soc-panel.border-critical{border-left:4px solid #ef4444}
.soc-panel-header{background:rgba(255,255,255,.02);padding:16px 20px;display:flex;justify-content:space-between;align-items:center;border-bottom:1px solid rgba(255,255,255,.04)}
.header-profile-block{display:flex;align-items:center;gap:12px}
.node-counter{background:#1e2330;padding:6px 12px;border-radius:8px;text-align:center;min-width:45px}
.node-counter .count{font-size:16px;font-weight:700;color:#fff}
.node-counter .lbl{font-size:9px;color:#6b7280;text-transform:uppercase}
.panel-title{font-size:15px;font-weight:700;color:#fff}
.panel-desc{font-size:12px;color:#9ca3af;margin-top:2px}

.btn{padding:8px 14px;border-radius:8px;border:none;cursor:pointer;font-size:12px;font-weight:600;display:inline-flex;align-items:center;gap:6px;transition:all .15s}
.btn:hover{filter:brightness(1.15)}
.btn:disabled{opacity:0.4;cursor:not-allowed}
.btn-red{background:#ef4444;color:#fff}
.btn-gray{background:#262b3d;color:#d1d5db}
.btn-sm{padding:5px 10px;font-size:11px;border-radius:6px}

table{width:100%;border-collapse:collapse;font-size:13px}
th{padding:12px 16px;background:rgba(0,0,0,.15);color:#9ca3af;font-size:11px;text-transform:uppercase;letter-spacing:.5px;text-align:left}
td{padding:12px 16px;border-bottom:1px solid rgba(255,255,255,.03);color:#c9ccd6;vertical-align:middle}
tr:hover td{background:rgba(255,255,255,.01)}

.threat-badge{display:flex;align-items:center;gap:8px}
.score-indicator{font-weight:800;font-size:13px;width:24px}
.bar-track{flex:1;max-width:80px;height:5px;background:#232a3c;border-radius:4px;overflow:hidden}
.bar-fill{height:100%;border-radius:4px}
.flags-cluster{display:flex;flex-wrap:wrap;gap:4px;max-width:210px}
.tag{padding:2px 6px;border-radius:4px;font-size:10px;font-weight:700;letter-spacing:0.3px}
.tag-red{background:rgba(239,68,68,.12);color:#ef4444;border:1px solid rgba(239,68,68,.25)}
.tag-orange{background:rgba(242,109,15,.12);color:#f26d0f;border:1px solid rgba(242,109,15,.25)}
.tag-blue{background:rgba(59,130,246,.12);color:#3b82f6;border:1px solid rgba(59,130,246,.25)}
.tag-purple{background:rgba(168,85,247,.12);color:#a855f7;border:1px solid rgba(168,85,247,.25)}

.mastermind-highlight {background:rgba(239,68,68,0.03);}
.mastermind-badge {background:#ef4444;color:#fff;font-size:9px;padding:1px 4px;border-radius:3px;font-weight:800;display:inline-block;margin-top:2px}
.clone-badge {background:#f26d0f;color:#fff;font-size:9px;padding:1px 4px;border-radius:3px;font-weight:800;display:inline-block;margin-top:2px}

.pill{padding:3px 9px;border-radius:12px;font-size:11px;font-weight:600}
.pill-ok{background:rgba(34,197,94,.1);color:#22c55e}
.pill-ban{background:rgba(239,68,68,.1);color:#ef4444}
.mono{font-family:'Courier New',monospace;font-size:12px;line-height:1.3}

#toast{position:fixed;bottom:30px;left:50%;transform:translateX(-50%);background:#111520;border:1px solid rgba(255,255,255,.1);color:#fff;padding:12px 24px;border-radius:8px;font-size:13px;display:none;z-index:9999;box-shadow:0 10px 25px rgba(0,0,0,0.5)}

/* Toggle Switch CSS */
.top-controls {display:flex; align-items:center; gap:15px; font-size:13px; color:#9ca3af;}
.switch {position:relative; display:inline-block; width:36px; height:20px;}
.switch input {opacity:0; width:0; height:0;}
.slider {position:absolute; cursor:pointer; top:0; left:0; right:0; bottom:0; background-color:#374151; transition:.3s; border-radius:20px;}
.slider:before {position:absolute; content:""; height:14px; width:14px; left:3px; bottom:3px; background-color:white; transition:.3s; border-radius:50%;}
input:checked + .slider {background-color:#f26d0f;}
input:checked + .slider:before {transform:translateX(16px);}
</style>
</head><body>
<?php include 'sidebar.php'; ?>
<div class="main">
  <div class="topbar">
    <h2><i class="fa-solid fa-microchip-ai" style="color:#ef4444"></i> Operational Security Center</h2>
    <div class="top-controls">
        <label class="switch">
          <input type="checkbox" id="bannedToggle" <?= $show_banned ? 'checked' : '' ?> onchange="window.location.href='?show_banned='+(this.checked?'1':'0')">
          <span class="slider round"></span>
        </label>
        <span style="font-weight:600;color:<?= $show_banned ? '#f26d0f' : '#9ca3af' ?>">Reveal Banned Accounts</span>
    </div>
  </div>
  
  <div class="content">
    
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon danger"><i class="fa-solid fa-chart-line-down"></i></div>
            <div class="stat-info">
                <h4>Active Capital Exposure</h4>
                <div class="val" style="color:#ef4444">Rs <?= number_format($total_exposure, 2) ?></div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon warning"><i class="fa-solid fa-circle-nodes"></i></div>
            <div class="stat-info">
                <h4>Detected Syndicates</h4>
                <div class="val"><?= count($syndicates_ui) ?></div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon audit"><i class="fa-solid fa-wallet"></i></div>
            <div class="stat-info">
                <h4>Whales To Inspect</h4>
                <div class="val" style="color:#3b82f6"><?= count($manual_audit_whales) ?></div>
            </div>
        </div>
    </div>

    <!-- SECTION 1: SYSTEM ORGANIZED CRIME INTERSECTION RINGS -->
    <div class="panel-section-title"><i class="fa-solid fa-network-wired"></i> Collusive Password & IP Networks</div>
    
    <?php if(empty($syndicates_ui)): ?>
        <div style="text-align:center;padding:40px 20px;background:#111520;border-radius:12px;border:1px dashed rgba(255,255,255,.1);margin-bottom:24px">
            <i class="fa-solid fa-shield-check" style="font-size:32px;color:#22c55e;margin-bottom:10px;display:block"></i>
            <p style="color:#9ca3af">No active syndicates detected. <?= !$show_banned ? 'Try revealing banned accounts.' : '' ?></p>
        </div>
    <?php endif; ?>

    <?php foreach($syndicates_ui as $syn): ?>
    <div class="soc-panel <?= $syn['loss'] > 5000 ? 'border-critical' : '' ?>">
      <div class="soc-panel-header">
        <div class="header-profile-block">
            <div class="node-counter"><div class="count"><?= count($syn['users']) ?></div><div class="lbl">Nodes</div></div>
            <div>
                <div class="panel-title">
                    <?php if($syn['type'] == 'password'): ?><i class="fa-solid fa-key" style="color:#f26d0f;margin-right:6px"></i><?php else: ?><i class="fa-solid fa-globe" style="color:#3b82f6;margin-right:6px"></i><?php endif; ?>
                    <?= $syn['title'] ?>
                </div>
                <div class="panel-desc"><?= $syn['subtitle'] ?></div>
            </div>
        </div>
        <div style="display:flex;align-items:center;gap:20px;">
            <div style="text-align:right">
                <div style="font-size:10px;text-transform:uppercase;color:#6b7280">Active Group Damage</div>
                <div style="font-weight:700;font-size:15px;" class="<?= $syn['loss'] > 0 ? 'color:#ef4444' : 'color:#22c55e' ?>"><?= $syn['loss'] > 0 ? '-' : '+' ?>Rs <?= number_format(abs($syn['loss']), 2) ?></div>
            </div>
            <?php 
                $active_uids = [];
                foreach($syn['users'] as $u) if(!$u['isbanned']) $active_uids[] = $u['id'];
                $uids_str = implode(',', $active_uids);
            ?>
            <button class="btn btn-red" onclick="banChain('<?= $uids_str ?>', this)" <?= empty($active_uids) ? 'disabled' : '' ?>><i class="fa-solid fa-gavel"></i> Ban Active Nodes</button>
        </div>
      </div>
      
      <table>
        <tr>
            <th width="110">User Target</th>
            <th width="120">Risk Profile</th>
            <th width="220">Intersection Tags</th>
            <th width="160">Ledger (Dep / With)</th>
            <th>Wingo Betting Profile Matrix</th>
            <th width="90">Status</th>
            <th width="50">Action</th>
        </tr>
        <?php foreach($syn['users'] as $u): 
            $rc = ($u['risk_score'] >= 70) ? '#ef4444' : (($u['risk_score'] >= 40) ? '#f26d0f' : '#22c55e');
            $is_mm = isset($u['u_role_pw']) && $u['u_role_pw'] === 'MASTERMIND';
            $is_clone = isset($u['u_role_ip']) && $u['u_role_ip'] === 'CLONE';
        ?>
        <tr class="<?= $is_mm ? 'mastermind-highlight' : '' ?>" style="<?= $u['isbanned'] ? 'opacity:0.4' : '' ?>">
          <td>
            <a href="users.php?uid=<?= $u['id'] ?>" target="_blank" style="color:#3b82f6;text-decoration:none;font-weight:700">#<?= $u['id'] ?></a><br>
            <span style="font-size:11px;color:#6b7280"><?= htmlspecialchars($u['number']) ?></span>
            <?php if($is_mm && $syn['type'] == 'password'): ?><br><span class="mastermind-badge"><i class="fa-solid fa-key"></i> ROOT</span><?php endif; ?>
            <?php if($is_clone && $syn['type'] == 'ip'): ?><br><span class="clone-badge"><i class="fa-solid fa-copy"></i> CLONE</span><?php endif; ?>
          </td>
          <td>
            <div class="threat-badge">
                <span class="score-indicator" style="color:<?= $rc ?>"><?= $u['risk_score'] ?></span>
                <div class="bar-track"><div class="bar-fill" style="width:<?= $u['risk_score'] ?>%;background:<?= $rc ?>"></div></div>
            </div>
          </td>
          <td>
            <div class="flags-cluster">
                <?php foreach($u['flags'] as $f): ?><span class="tag tag-<?= $f['color'] ?>"><?= $f['name'] ?></span><?php endforeach; ?>
            </div>
          </td>
          <td class="mono">
            D: <span style="color:#22c55e"><?= number_format($u['total_deposits']) ?></span><br>
            W: <span style="color:#ef4444"><?= number_format($u['total_withdrawn']??0) ?></span>
          </td>
          <td class="mono" style="color:#9ca3af;font-size:12px">
            <?php if($u['wingo']['rounds'] > 0): ?>
                Cycles: <span style="color:#fff"><?= $u['wingo']['rounds'] ?></span> Bet: <span style="color:#ef4444"><?= number_format($u['wingo']['bet']) ?></span>
                Win: <span style="color:#22c55e"><?= number_format($u['wingo']['win']) ?></span> Net: <span class="<?= $u['wingo']['net'] >= 0 ? 'pill-ok' : 'text-danger' ?>" style="padding:1px 4px;border-radius:3px"><?= $u['wingo']['net'] >= 0 ? '+' : '' ?><?= number_format($u['wingo']['net']) ?></span>
            <?php else: ?>
                <span style="color:#4b5563;font-style:italic">No Wingo Log Matches</span>
            <?php endif; ?>
          </td>
          <td class="status-cell-<?= $u['id'] ?>"><span class="pill <?= $u['isbanned']?'pill-ban':'pill-ok' ?>"><?= $u['isbanned']?'Banned':'Active' ?></span></td>
          <td>
             <?php if(!$u['isbanned']): ?>
                <button class="btn btn-gray btn-sm btn-indiv-ban-<?= $u['id'] ?>" onclick="toggleBan(<?= $u['id'] ?>,this)"><i class="fa-solid fa-ban"></i></button>
             <?php endif; ?>
          </td>
        </tr>
        <?php endforeach; ?>
      </table>
    </div>
    <?php endforeach; ?>

    <!-- SECTION 2: STANDALONE INDIVIDUAL POLICY VIOLATORS -->
    <div class="panel-section-title"><i class="fa-solid fa-user-shield"></i> Standalone High-Risk Isolation Metrics</div>
    <div class="soc-panel">
      <table>
        <tr>
            <th width="110">User Target</th>
            <th width="120">Risk Profile</th>
            <th width="220">Intersection Tags</th>
            <th width="160">Ledger (Dep / With)</th>
            <th>Wingo Betting Profile Matrix</th>
            <th width="90">Status</th>
            <th width="50">Action</th>
        </tr>
        <?php foreach($standalone_threats as $u): 
            $rc = ($u['risk_score'] >= 70) ? '#ef4444' : (($u['risk_score'] >= 40) ? '#f26d0f' : '#22c55e');
        ?>
        <tr style="<?= $u['isbanned'] ? 'opacity:0.4' : '' ?>">
          <td>
            <a href="users.php?uid=<?= $u['id'] ?>" target="_blank" style="color:#3b82f6;text-decoration:none;font-weight:700">#<?= $u['id'] ?></a><br>
            <span style="font-size:11px;color:#6b7280"><?= htmlspecialchars($u['number']) ?></span>
          </td>
          <td>
            <div class="threat-badge">
                <span class="score-indicator" style="color:<?= $rc ?>"><?= $u['risk_score'] ?></span>
                <div class="bar-track"><div class="bar-fill" style="width:<?= $u['risk_score'] ?>%;background:<?= $rc ?>"></div></div>
            </div>
          </td>
          <td>
            <div class="flags-cluster">
                <?php foreach($u['flags'] as $f): ?><span class="tag tag-<?= $f['color'] ?>"><?= $f['name'] ?></span><?php endforeach; ?>
            </div>
          </td>
          <td class="mono">
            D: <span style="color:#22c55e"><?= number_format($u['total_deposits']) ?></span><br>
            W: <span style="color:#ef4444"><?= number_format($u['total_withdrawn']??0) ?></span>
          </td>
          <td class="mono" style="color:#9ca3af;font-size:12px">
            <?php if($u['wingo']['rounds'] > 0): ?>
                Cycles: <span style="color:#fff"><?= $u['wingo']['rounds'] ?></span> Bet: <span style="color:#ef4444"><?= number_format($u['wingo']['bet']) ?></span>
                Win: <span style="color:#22c55e"><?= number_format($u['wingo']['win']) ?></span> Net: <span class="<?= $u['wingo']['net'] >= 0 ? 'pill-ok' : 'text-danger' ?>" style="padding:1px 4px;border-radius:3px"><?= $u['wingo']['net'] >= 0 ? '+' : '' ?><?= number_format($u['wingo']['net']) ?></span>
            <?php else: ?>
                <span style="color:#4b5563;font-style:italic">No Wingo Log Matches</span>
            <?php endif; ?>
          </td>
          <td class="status-cell-<?= $u['id'] ?>"><span class="pill <?= $u['isbanned']?'pill-ban':'pill-ok' ?>"><?= $u['isbanned']?'Banned':'Active' ?></span></td>
          <td>
             <?php if(!$u['isbanned']): ?>
                <button class="btn btn-gray btn-sm btn-indiv-ban-<?= $u['id'] ?>" onclick="toggleBan(<?= $u['id'] ?>,this)"><i class="fa-solid fa-ban"></i></button>
             <?php endif; ?>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php if(empty($standalone_threats)): ?><tr><td colspan="7" style="text-align:center;padding:24px;color:#4b5563;">No standalone operations.</td></tr><?php endif; ?>
      </table>
    </div>

    <!-- SECTION 3: SYSTEM LARGE-BALANCE ACCOUNTS (MANUAL AUDITING INSPECTOR) -->
    <div class="panel-section-title"><i class="fa-solid fa-magnifying-glass-dollar"></i> High Balance Watchlist (Manual Inspection Panel)</div>
    <div class="soc-panel">
      <table>
        <tr>
            <th>User Target</th>
            <th>Available Balance Pool</th>
            <th>Wager Requirements Met</th>
            <th>Total Aggregated Deposits</th>
            <th>Syndicate Affiliation</th>
            <th>Status</th>
        </tr>
        <?php foreach($manual_audit_whales as $u): ?>
        <tr style="<?= $u['isbanned'] ? 'opacity:0.4' : '' ?>">
          <td>
            <a href="users.php?uid=<?= $u['id'] ?>" target="_blank" style="color:#3b82f6;text-decoration:none;font-weight:700">#<?= $u['id'] ?></a><br>
            <span style="font-size:11px;color:#6b7280"><?= htmlspecialchars($u['number']) ?></span>
          </td>
          <td style="color:#22c55e;font-weight:700" class="mono">Rs <?= number_format($u['balance'], 2) ?></td>
          <td style="color:#f59e0b" class="mono">Rs <?= number_format($u['wager'], 2) ?></td>
          <td class="mono">Rs <?= number_format($u['total_deposits'], 2) ?></td>
          <td>
             <?= in_array($u['id'], $profiled_in_syndicate) ? '<span class="tag tag-red"><i class="fa-solid fa-triangle-exclamation"></i> Part of Ring</span>' : '<span class="tag tag-blue">Independent Whale</span>' ?>
          </td>
          <td class="status-cell-<?= $u['id'] ?>"><span class="pill <?= $u['isbanned']?'pill-ban':'pill-ok' ?>"><?= $u['isbanned']?'Banned':'Active' ?></span></td>
        </tr>
        <?php endforeach; ?>
        <?php if(empty($manual_audit_whales)): ?><tr><td colspan="6" style="text-align:center;padding:24px;color:#4b5563;">No users matching capital storage threshold.</td></tr><?php endif; ?>
      </table>
    </div>

  </div>
</div>

<div id="toast"></div>

<script>
function toast(m, ok=true) {
    const t = document.getElementById('toast');
    t.style.display = 'block';
    t.style.borderLeft = '4px solid ' + (ok ? '#22c55e' : '#ef4444');
    t.innerHTML = m;
    setTimeout(() => t.style.display = 'none', 3500);
}

function toggleBan(uid, btn){
    if(!confirm(`Validate explicit ban configuration execution on account #${uid}?`)) return;
    btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i>';
    
    const fd = new FormData();
    fd.append('action', 'ban_user');
    fd.append('uid', uid);
    
    fetch('actions.php', {method: 'POST', body: fd})
    .then(r => r.json())
    .then(r => {
        if(r.ok) {
            toast(`Node #${uid} safely terminated.`);
            btn.closest('tr').style.opacity = '0.4';
            document.querySelectorAll(`.status-cell-${uid}`).forEach(c => c.innerHTML = '<span class="pill pill-ban">Banned</span>');
            btn.style.display = 'none';
        } else {
            toast(r.msg, false);
            btn.innerHTML = '<i class="fa-solid fa-ban"></i>';
        }
    }).catch(() => toast('System link anomaly during execution.', false));
}

function banChain(uids, btn) {
    if(!uids) return;
    if(!confirm('CRITICAL ACTION LOG REQUIRED: Dismantle and terminate ALL active nodes in this group?')) return;
    
    btn.disabled = true;
    btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Purging...';

    const fd = new FormData();
    fd.append('action', 'ban_chain');
    fd.append('uids', uids);

    fetch('sus.php', {method: 'POST', body: fd})
    .then(r => r.json())
    .then(r => {
        if(r.ok) {
            toast(r.msg);
            btn.innerHTML = '<i class="fa-solid fa-check-double"></i> Purged';
            btn.className = 'btn btn-gray';
            
            const idArray = uids.split(',');
            idArray.forEach(id => {
                const row = document.querySelector(`.status-cell-${id}`).closest('tr');
                if(row) row.style.opacity = '0.4';
                document.querySelectorAll(`.status-cell-${id}`).forEach(c => c.innerHTML = '<span class="pill pill-ban">Banned</span>');
                const banBtn = document.querySelector(`.btn-indiv-ban-${id}`);
                if(banBtn) banBtn.style.display = 'none';
            });
        } else {
            toast('Failed processing chain disruption operation.', false);
            btn.disabled = false;
            btn.innerHTML = '<i class="fa-solid fa-gavel"></i> Ban Active Nodes';
        }
    })
    .catch(() => {
        toast('System link anomaly during execution.', false);
        btn.disabled = false;
        btn.innerHTML = '<i class="fa-solid fa-gavel"></i> Ban Active Nodes';
    });
}
</script>
</body></html>