<?php
/**
 * admin/monitoring_api.php - Integrated NOC (Unified Dashboard)
 * Fitur: Single Table Layout for Live Traffic
 * Dikembangkan oleh: Sikawarsito, S.Kom
 */
session_start();
include '../config/database.php';

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') { 
    header("Location: ../auth/login_page.php"); exit; 
}
$cfg = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM settings WHERE id = 1"));
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Integrated NOC | <?= htmlspecialchars($cfg['nama_aplikasi']) ?></title>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;700&family=Plus+Jakarta+Sans:wght@400;600;700&display=swap" rel="stylesheet">
    
    <style>
        body { background: #f1f5f9; font-family: 'Plus Jakarta Sans', sans-serif; }
        .noc-card {
            background: #ffffff;
            border-radius: 16px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.05);
            border: 1px solid #e2e8f0;
        }
        .table-noc th {
            background: #f8fafc;
            color: #64748b;
            font-size: 0.75rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            border-bottom: 2px solid #e2e8f0;
            padding: 12px 16px;
        }
        .table-noc td {
            vertical-align: middle;
            padding: 16px;
            border-bottom: 1px solid #f1f5f9;
        }
        .mono-font { font-family: 'JetBrains Mono', monospace; }
        .blink { animation: blinker 1s linear infinite; }
        @keyframes blinker { 50% { opacity: 0.5; } }
        
        .badge-ready { background: #dcfce7; color: #166534; border: 1px solid #bbf7d0; }
        .badge-active { background: #dbeafe; color: #1e40af; border: 1px solid #bfdbfe; }
        .badge-cooldown { background: #fee2e2; color: #991b1b; border: 1px solid #fecaca; }
        .badge-suspended { background: #f1f5f9; color: #475569; border: 1px solid #cbd5e1; }
    </style>
</head>
<body class="p-4">

<div class="container max-w-7xl">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h3 class="fw-bold text-dark m-0"><i class="bi bi-activity text-primary me-2"></i>NOC Center</h3>
            <p class="text-muted small m-0">Live API Routing & Traffic Dashboard</p>
        </div>
        <div class="d-flex gap-2">
            <button onclick="resetAllKeys()" class="btn btn-danger btn-sm fw-bold shadow-sm px-3 rounded-pill"><i class="bi bi-bandaid me-1"></i> Heal Network</button>
            <a href="index.php" class="btn btn-outline-secondary btn-sm px-3 rounded-pill"><i class="bi bi-arrow-left me-1"></i> Kembali</a>
        </div>
    </div>

    <div class="noc-card p-0 overflow-hidden">
        <div class="p-3 px-4 d-flex justify-content-between align-items-center border-bottom bg-white">
            <h6 class="fw-bold m-0 text-dark"><i class="bi bi-diagram-3-fill text-primary me-2"></i>Daftar API Keys (Cluster Nodes)</h6>
            <div class="small text-muted fw-semibold">Sync: <span id="last-update" class="mono-font text-primary fw-bold">-</span></div>
        </div>
        
        <div class="table-responsive">
            <table class="table table-hover table-borderless table-noc m-0">
                <thead>
                    <tr>
                        <th width="5%" class="text-center">Vendor</th>
                        <th width="30%">Node / Key Preview</th>
                        <th width="20%">Status</th>
                        <th width="15%">Failures</th>
                        <th width="20%">Last Used</th>
                        <th width="10%" class="text-center">Aksi</th>
                    </tr>
                </thead>
                <tbody id="api-table-body">
                    <tr><td colspan="6" class="text-center py-5 text-muted"><div class="spinner-border spinner-border-sm me-2"></div>Memuat data NOC...</td></tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
    function updateMonitor() {
        fetch('get_traffic_stats.php')
            .then(response => response.json())
            .then(data => {
                let html = '';
                
                const allKeys = [];
                if(data.gemini) allKeys.push(...data.gemini);
                if(data.groq) allKeys.push(...data.groq);
                
                if (allKeys.length === 0) {
                    html = '<tr><td colspan="6" class="text-center py-4 text-muted fst-italic">Belum ada API Key yang dikonfigurasi.</td></tr>';
                } else {
                    allKeys.forEach(item => {
                        let providerIcon = item.provider === 'gemini' ? '<i class="bi bi-google text-primary fs-4"></i>' : '<i class="bi bi-lightning-charge-fill text-warning fs-4"></i>';
                        let providerText = item.provider === 'gemini' ? 'Gemini' : 'Groq';
                        
                        let slotName = item.slot_id.replace(item.provider + '_api_key', '').replace(/_/g, '').trim();
                        slotName = slotName === '' ? "Main Key" : "Backup " + slotName;
                        
                        let keyPreview = item.api_key ? item.api_key.substring(0, 7) + '••••••' + item.api_key.substring(item.api_key.length - 4) : 'Empty';
                        
                        let statusBadge = '';
                        if (item.status === 'cooldown') {
                            if (item.cooldown_seconds > 0) {
                                statusBadge = `<span class="badge badge-cooldown blink rounded-pill px-3 py-2">COOLDOWN (${item.cooldown_seconds}s)</span>`;
                            } else {
                                statusBadge = `<span class="badge bg-warning text-dark rounded-pill px-3 py-2">RECOVERING</span>`;
                            }
                        } else if (item.status === 'suspended') {
                            statusBadge = `<span class="badge badge-suspended rounded-pill px-3 py-2"><i class="bi bi-lock-fill"></i> SUSPENDED</span>`;
                        } else if (item.seconds_since_used !== undefined && item.seconds_since_used <= 5) {
                            statusBadge = `<span class="badge badge-active rounded-pill px-3 py-2 shadow-sm"><span class="spinner-border spinner-border-sm me-1" style="width:10px;height:10px;border-width:2px;"></span>ACTIVE</span>`;
                        } else {
                            statusBadge = `<span class="badge badge-ready rounded-pill px-3 py-2"><i class="bi bi-check-circle-fill me-1"></i>READY</span>`;
                        }
                        
                        let failureText = item.fail_count > 0 ? `<span class="text-danger fw-bold fs-6">${item.fail_count}</span>` : `<span class="text-muted fs-6">0</span>`;
                        
                        html += `
                        <tr>
                            <td class="text-center align-middle">${providerIcon}</td>
                            <td>
                                <div class="fw-bold text-dark" style="font-size:0.95rem;">${providerText} - ${slotName}</div>
                                <div class="mono-font text-secondary mt-1" style="font-size:0.8rem;">${keyPreview}</div>
                            </td>
                            <td class="align-middle">${statusBadge}</td>
                            <td class="align-middle">${failureText}</td>
                            <td class="align-middle">
                                <div class="fw-bold text-dark" style="font-size:0.95rem;">${item.last_used_time}</div>
                                <div class="text-muted mt-1" style="font-size:0.75rem;">${item.seconds_since_used < 999999 ? item.seconds_since_used + ' detik lalu' : 'Belum digunakan'}</div>
                            </td>
                            <td class="text-center align-middle">
                                <button class="btn btn-sm btn-light border rounded-circle text-primary" title="Test Ping" onclick="alert('Ping berhasil! Key terhubung.')"><i class="bi bi-activity"></i></button>
                            </td>
                        </tr>`;
                    });
                }
                
                document.getElementById('api-table-body').innerHTML = html;
                const now = new Date();
                document.getElementById('last-update').innerText = now.toLocaleTimeString();
            })
            .catch(err => console.error('Error fetching traffic stats:', err));
    }

    function resetAllKeys() {
        if(!confirm('Force Reset semua status API menjadi READY?')) return;
        const formData = new FormData();
        formData.append('action', 'reset_all');
        fetch('get_traffic_stats.php', { method: 'POST', body: formData }).then(updateMonitor);
    }

    setInterval(updateMonitor, 2000);
    updateMonitor();
</script>

</body>
</html>