<?php
require_once 'db.php';

date_default_timezone_set('Asia/Kolkata');

// Create table if not exists
$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)
    )
");

if (isset($_GET['fetch']) && $_GET['fetch'] == '1') {
    set_time_limit(0);
    $vms_query = $conn->query("SELECT * FROM vms WHERE 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'] ?? '');
        
        // API Call for all VMs (not just blocked) to update balance
        $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'];

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

            // Record history
            $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())
            ");

            // === BLOCKED IP HISTORY - Save when blocked ===
            if (in_array($status, ['blocked', 'anomaly'])) {
                $unit_esc = $conn->real_escape_string($unit_id);
                $ip_esc = $conn->real_escape_string($current_ip);
                
                // Check if this IP already exists
                $check = $conn->query("SELECT id FROM blocked_ip_history WHERE ip_address = '$ip_esc'");
                
                if ($check->num_rows == 0) {
                    // Insert new blocked IP
                    $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())
                    ");
                }
            }
        }
    }
}

// Also check and save currently blocked VMs that might have been missed
$currently_blocked_vms = $conn->query("
    SELECT v.* FROM vms v 
    WHERE 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 if this IP already exists in history
    $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())
        ");
    }
}

// Get all VMs with stats
$vms_query = $conn->query("
    SELECT v.*, 
    COALESCE((SELECT h.balance FROM earnapp_history h WHERE h.vm_id = v.vm_id 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.vm_id = v.vm_id 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.vm_id = v.vm_id 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
");

// Get blocked IP history count
$history_count = $conn->query("SELECT COUNT(*) as c FROM blocked_ip_history")->fetch_assoc()['c'];

// Get blocked IP history
$blocked_history = $conn->query("
    SELECT * FROM blocked_ip_history 
    ORDER BY blocked_at DESC
");

$stats = [
    'total' => 0,
    'ok' => 0,
    'blocked' => 0,
    'unchecked' => 0
];

$qTotal = $conn->query("SELECT COUNT(*) c FROM vms");
$stats['total'] = (int)$qTotal->fetch_assoc()['c'];

$qOnline = $conn->query("
    SELECT COUNT(*) c
    FROM vms
    WHERE last_heartbeat IS NOT NULL
      AND last_heartbeat >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 5 MINUTE)
");
$stats['ok'] = (int)$qOnline->fetch_assoc()['c'];

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

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 = (!empty($row['last_heartbeat']) && strtotime($row['last_heartbeat']) >= (time() - 300));
    $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 {
        if (!isset($nested_data[$g]['rdps'][$r]['unchecked'])) {
            $nested_data[$g]['rdps'][$r]['unchecked'] = 0;
        }
        $nested_data[$g]['rdps'][$r]['unchecked']++;
        if (!isset($nested_data[$g]['unchecked'])) {
            $nested_data[$g]['unchecked'] = 0;
        }
        $nested_data[$g]['unchecked']++;
    }
}
?>

<div class="container-fluid p-4">
    <div class="stat-strip">
        <div class="stat-box box-total"><i class="fas fa-desktop"></i><div class="val"><?= $stats['total'] ?></div><div class="lbl">Total VMs</div></div>
        <div class="stat-box box-online"><i class="fas fa-check-circle text-green"></i><div class="val"><?= $stats['ok'] ?></div><div class="lbl">Online</div></div>
        <div class="stat-box box-pending"><i class="fas fa-clock"></i><div class="val"><?= $stats['unchecked'] ?></div><div class="lbl">Pending</div></div>
        <div class="stat-box box-anomaly"><i class="fas fa-exclamation-triangle text-yellow"></i><div class="val"><?= $stats['blocked'] ?></div><div class="lbl">Anomalies</div></div>
    </div>

    <div class="analysis-bar">
        <div style="font-weight: bold; font-size: 1.2rem; margin-right: 20px;"><i class="fas fa-network-wired me-2"></i> IP Analysis</div>
        <div class="analysis-item"><i class="fas fa-desktop"></i> <span><?= $stats['total'] ?></span> <span class="label-tag">TOTAL VMS</span></div>
        <div class="analysis-item"><i class="fas fa-check-circle text-green"></i> <span><?= $stats['ok'] ?></span> <span class="label-tag">OK</span></div>
        <div class="analysis-item"><i class="fas fa-ban text-red"></i> <span><?= $stats['blocked'] ?></span> <span class="label-tag">BLOCKED</span></div>
        <div class="analysis-item"><i class="fas fa-question-circle text-yellow"></i> <span><?= $stats['unchecked'] ?></span> <span class="label-tag">UNCHECKED</span></div>
        <div class="ms-auto"><a href="?page=ip-analysis&fetch=1" class="btn btn-sm btn-danger px-4 fw-bold"><i class="fas fa-search me-2"></i> CHECK ALL IPS</a></div>
    </div>
    
    <ul class="nav nav-tabs mt-4" id="ipTabs">
        <li class="nav-item">
            <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#allTab">
                <i class="fas fa-list me-1"></i> All VMs
            </button>
        </li>
        <li class="nav-item">
            <button class="nav-link text-danger" data-bs-toggle="tab" data-bs-target="#blockedTab">
                <i class="fas fa-ban me-1"></i> Currently Blocked (<?= $stats['blocked'] ?>)
            </button>
        </li>
        <li class="nav-item">
            <button class="nav-link text-warning" data-bs-toggle="tab" data-bs-target="#historyTab">
                <i class="fas fa-history me-1"></i> Blocked IP History (<?= $history_count ?>)
            </button>
        </li>
    </ul>

    <div class="tab-content mt-4">

        <!-- All VMs Tab -->
        <div class="tab-pane fade show active" id="allTab">
            <div class="mt-4">
                <?php foreach($nested_data as $groupName => $group): ?>
                <div class="accordion-group">
                    <div class="accordion-header" data-bs-toggle="collapse" data-bs-target="#group-<?= md5((string)$groupName) ?>">
                        <div class="group-info">
                            <i class="fas fa-folder-open text-purple"></i>
                            <span class="fw-bold"><?= strtoupper((string)$groupName) ?></span>
                            <span class="badge-purple"><?= (int)$group['total_vms'] ?> VMs</span>
                        </div>
                        <div class="d-flex align-items-center gap-3">
                            <div class="d-flex gap-2">
                                <div class="status-badge-pill text-green"><i class="fas fa-check small"></i> <?= (int)$group['ok'] ?></div>
                                <div class="status-badge-pill text-red"><i class="fas fa-ban small"></i> <?= (int)$group['blocked'] ?></div>
                                <div class="status-badge-pill"><i class="fas fa-question small"></i> <?= (int)$group['unchecked'] ?></div>
                            </div>
                        </div>
                    </div>

                    <div class="collapse show" id="group-<?= md5((string)$groupName) ?>">
                        <?php foreach($group['rdps'] as $rdpName => $rdp): ?>
                        <div class="rdp-container">
                            <?php foreach($rdp['vms'] as $vm): ?>
                            <div class="vm-row">
                                <div class="vm-id"><?= htmlspecialchars($vm['unit_id']) ?></div>
                                <div class="vm-ip-status">
                                    <div><i class="fas fa-wifi me-1"></i> <?= htmlspecialchars($vm['ip']) ?></div>
                                    <div class="status-pill status-<?= htmlspecialchars($vm['status']) ?>">
                                        <?= strtoupper($vm['status'] == 'ok' ? 'OK' : ($vm['status'] == 'unchecked' ? 'OFFLINE' : $vm['status'])) ?>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Currently Blocked Tab -->
        <div class="tab-pane fade" id="blockedTab">
            <?php if(count($blocked_vms) > 0): ?>
                <div class="table-responsive">
                    <table class="table table-dark table-striped table-hover">
                        <thead class="table-dark">
                            <tr>
                                <th>Unit ID</th>
                                <th>Current IP</th>
                                <th>Today's Earning</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach($blocked_vms as $vm): ?>
                            <tr class="table-danger">
                                <td><span class="badge bg-dark"><?= htmlspecialchars($vm['unit_id']) ?></span></td>
                                <td><i class="fas fa-wifi text-danger me-2"></i><?= htmlspecialchars($vm['ip']) ?></td>
                                <td class="text-danger fw-bold">$<?= number_format((float)$vm['earn'], 2) ?></td>
                                <td><span class="badge bg-danger">BLOCKED</span></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div class="text-center p-5 text-muted">
                    <i class="fas fa-check-circle fa-3x text-success mb-3"></i>
                    <h4>No blocked VMs</h4>
                    <p>All systems running normally</p>
                </div>
            <?php endif; ?>
        </div>

        <!-- Blocked IP History Tab -->
        <div class="tab-pane fade" id="historyTab">
            <div class="card bg-dark border-secondary">
                <div class="card-header bg-dark border-secondary d-flex justify-content-between align-items-center">
                    <h5 class="mb-0 text-white"><i class="fas fa-archive me-2"></i>All Blocked IPs (Unique)</h5>
                    <span class="badge bg-danger"><?= $history_count ?> IPs Recorded</span>
                </div>
                <div class="card-body p-0">
                    <?php if($blocked_history->num_rows > 0): ?>
                        <div class="table-responsive">
                            <table class="table table-dark table-striped table-hover mb-0">
                                <thead>
                                    <tr class="text-uppercase text-muted small">
                                        <th class="ps-4">Unit ID</th>
                                        <th>IP Address</th>
                                        <th>Group</th>
                                        <th>RDP Name</th>
                                        <th>Blocked Date & Time</th>
                                        <th class="pe-4">Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while($ip = $blocked_history->fetch_assoc()): ?>
                                    <tr>
                                        <td class="ps-4">
                                            <span class="badge bg-secondary"><?= htmlspecialchars($ip['unit_id']) ?></span>
                                        </td>
                                        <td>
                                            <i class="fas fa-wifi text-danger me-2"></i>
                                            <code class="text-danger"><?= htmlspecialchars($ip['ip_address']) ?></code>
                                        </td>
                                        <td><?= htmlspecialchars($ip['group_name']) ?></td>
                                        <td><?= htmlspecialchars($ip['rdp_name']) ?></td>
                                        <td>
                                            <i class="far fa-clock me-1 text-muted"></i>
                                            <?= date('Y-m-d H:i', strtotime($ip['blocked_at'])) ?>
                                        </td>
                                        <td class="pe-4">
                                            <span class="badge bg-secondary">Archived</span>
                                        </td>
                                    </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="text-center p-5 text-muted">
                            <i class="fas fa-inbox fa-3x mb-3"></i>
                            <h5>No blocked IP history</h5>
                            <p>History will appear here when IPs get blocked</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

    </div>
</div>