<?php
// =========================================================================
// admin/ai_gateway_traffic_flow.php - LIVE VISUALIZATION XIEQA LLM
// Developer: Sikawarsito, S.Kom
// Fungsi: Visualisasi Auto-Pilot Load Balancer berdasarkan traffic real-time
// =========================================================================

session_start();
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../auth/login_page.php");
    exit;
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Live Traffic Flow - Xieqa LLM</title>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;800&display=swap" rel="stylesheet">
    <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">
    <style>
        body { background-color: #0f172a; color: #e2e8f0; font-family: 'Plus Jakarta Sans', sans-serif; overflow-x: hidden; }
        
        .header-title { color: #38bdf8; font-weight: 800; letter-spacing: 1px; }
        .control-panel { background: #1e293b; border: 1px solid #334155; border-radius: 15px; padding: 20px; margin-bottom: 30px; }
        
        .network-arena { 
            position: relative; height: 500px; background: #0b1120; 
            border: 2px dashed #334155; border-radius: 20px; 
            overflow: hidden; margin-bottom: 40px; box-shadow: inset 0 0 50px rgba(0,0,0,0.5);
        }

        .node { 
            position: absolute; padding: 15px 25px; border-radius: 12px; font-weight: 700; 
            text-align: center; z-index: 10; display: flex; flex-direction: column; align-items: center; justify-content: center;
            box-shadow: 0 10px 20px rgba(0,0,0,0.3); transition: all 0.3s; transform: translate(-50%, -50%); 
        }
        .node i { font-size: 2rem; margin-bottom: 5px; }

        .node-user { top: 50%; left: 10%; background: #334155; color: #f8fafc; border: 2px solid #475569; }
        .node-router { top: 50%; left: 40%; background: linear-gradient(135deg, #1d4ed8, #0f172a); border: 2px solid #3b82f6; color: white; box-shadow: 0 0 20px rgba(59, 130, 246, 0.4); }
        .node-cache { top: 20%; left: 80%; background: #faf5ff; color: #a855f7; border: 2px solid #a855f7; }
        .node-gemini { top: 50%; left: 80%; background: #e0f2fe; color: #0ea5e9; border: 2px solid #0ea5e9; }
        .node-groq { top: 80%; left: 80%; background: #ffedd5; color: #f97316; border: 2px solid #f97316; }

        .node.pulsing { transform: translate(-50%, -50%) scale(1.1); filter: brightness(1.2); }

        .packet {
            position: absolute; width: 14px; height: 14px; border-radius: 50%; z-index: 20; transform: translate(-50%, -50%);
            transition: left 0.5s linear, top 0.5s linear; display: none;
        }

        .path-line { position: absolute; background: #334155; height: 2px; z-index: 5; transform-origin: 0 0; }

        .log-box { background: #000; color: #4ade80; font-family: monospace; padding: 15px; border-radius: 10px; height: 150px; overflow-y: auto; font-size: 13px; }
        
        .radar-spinner { animation: spin 2s linear infinite; display: inline-block; }
        @keyframes spin { 100% { transform: rotate(360deg); } }
    </style>
</head>
<body>

<div class="container py-5">
    <div class="d-flex align-items-center justify-content-between mb-4">
        <div>
            <h2 class="header-title m-0"><i class="bi bi-broadcast me-2"></i> Live Traffic Auto-Pilot</h2>
            <p class="text-secondary m-0">Memantau lalu lintas API Gateway secara Real-Time</p>
        </div>
        <a href="dashboard_llm.php" class="btn btn-outline-secondary rounded-pill fw-bold text-light">Kembali</a>
    </div>

    <div class="control-panel shadow-sm d-flex justify-content-between align-items-center">
        <div>
            <h5 class="fw-bold mb-1 text-light"><i class="bi bi-radar radar-spinner text-success me-2"></i> Auto-Pilot Scanner: <span class="text-success">AKTIF</span></h5>
            <small class="text-secondary">Sistem sedang mendengarkan database. Bola cahaya akan meluncur otomatis saat ada user sungguhan yang mengirim pesan.</small>
        </div>
        <div class="d-flex gap-2">
            <button class="btn btn-sm btn-outline-info" onclick="simulateTraffic('gemini')">Tes Manual Gemini</button>
            <button class="btn btn-sm btn-outline-warning" onclick="simulateTraffic('groq')">Tes Manual Groq</button>
        </div>
    </div>

    <div class="network-arena" id="arena">
        <div id="lines-container"></div>
        <div class="node node-user" id="node-user"><i class="bi bi-people-fill"></i>Real Users</div>
        <div class="node node-router" id="node-router"><i class="bi bi-hdd-network-fill"></i>Xieqa Router<br><small style="font-size:10px;">Load Balancer</small></div>
        <div class="node node-cache" id="node-cache"><i class="bi bi-database-fill-check"></i>Xieqa Cache<br><small style="font-size:10px;">Internal Memory</small></div>
        <div class="node node-gemini" id="node-gemini"><i class="bi bi-google"></i>Gemini Cluster<br><small style="font-size:10px;">External API</small></div>
        <div class="node node-groq" id="node-groq"><i class="bi bi-cpu"></i>Groq Cluster<br><small style="font-size:10px;">External API</small></div>
    </div>

    <h5 class="fw-bold text-light"><i class="bi bi-terminal me-2"></i>Sistem Log (Real-time)</h5>
    <div class="log-box shadow" id="terminal-log">
        > <span class="text-success">System Auto-Pilot Listening on Port 3306 (Database)...</span><br>
    </div>
</div>

<script>
    const coords = {
        user: { left: 10, top: 50 }, router: { left: 40, top: 50 },
        cache: { left: 80, top: 20 }, gemini: { left: 80, top: 50 }, groq: { left: 80, top: 80 }
    };

    function drawLine(start, end) {
        const arena = document.getElementById('arena');
        const w = arena.offsetWidth; const h = arena.offsetHeight;
        const x1 = (coords[start].left / 100) * w; const y1 = (coords[start].top / 100) * h;
        const x2 = (coords[end].left / 100) * w; const y2 = (coords[end].top / 100) * h;
        const length = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
        const angle = Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI;

        const line = document.createElement('div');
        line.className = 'path-line';
        line.style.width = `${length}px`; line.style.left = `${x1}px`; line.style.top = `${y1}px`;
        line.style.transform = `rotate(${angle}deg)`;
        document.getElementById('lines-container').appendChild(line);
    }

    window.onload = () => {
        drawLine('user', 'router'); drawLine('router', 'cache');
        drawLine('router', 'gemini'); drawLine('router', 'groq');
    };

    function logTerminal(message, color = "#4ade80") {
        const logBox = document.getElementById('terminal-log');
        const time = new Date().toLocaleTimeString();
        logBox.innerHTML += `<span style="color: #64748b;">[${time}]</span> <span style="color: ${color};">${message}</span><br>`;
        logBox.scrollTop = logBox.scrollHeight;
    }

    function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }

    // Animasi Visual (Tidak memblokir animasi lain)
    async function simulateTraffic(destination, isRealTraffic = false) {
        const packet = document.createElement('div');
        packet.className = 'packet';
        
        let color, speed, destName;
        if (destination === 'cache') { color = '#a855f7'; speed = '0.3s'; destName = 'Xieqa Cache'; } 
        else if (destination === 'gemini') { color = '#0ea5e9'; speed = '0.6s'; destName = 'Gemini Cluster'; }
        else if (destination === 'groq') { color = '#f97316'; speed = '0.6s'; destName = 'Groq Cluster'; }
        
        packet.style.backgroundColor = color;
        packet.style.boxShadow = `0 0 15px ${color}, 0 0 30px ${color}`;
        packet.style.transition = `left ${speed} linear, top ${speed} linear`;
        
        packet.style.left = `${coords.user.left}%`; packet.style.top = `${coords.user.top}%`;
        packet.style.display = 'block';
        document.getElementById('arena').appendChild(packet);

        const nodeUser = document.getElementById('node-user');
        const nodeRouter = document.getElementById('node-router');
        const nodeDest = document.getElementById(`node-${destination}`);

        let logPrefix = isRealTraffic ? "[LIVE TRAFFIC]" : "[MANUAL TEST]";

        logTerminal(`> ${logPrefix} Request masuk dari User...`, '#e2e8f0');
        nodeUser.classList.add('pulsing');
        await sleep(100);
        packet.style.left = `${coords.router.left}%`; packet.style.top = `${coords.router.top}%`;
        
        await sleep(parseFloat(speed) * 1000);
        nodeUser.classList.remove('pulsing'); nodeRouter.classList.add('pulsing');
        
        if (destination === 'cache') logTerminal(`> ${logPrefix} Router memindai Memory. Dialihkan ke Cache!`, color);
        else logTerminal(`> ${logPrefix} Hash tidak ditemukan. Router menugaskan ${destName}...`, color);
        
        await sleep(200);
        packet.style.left = `${coords.destination?.left || coords[destination].left}%`;
        packet.style.top = `${coords.destination?.top || coords[destination].top}%`;
        
        await sleep(parseFloat(speed) * 1000);
        nodeRouter.classList.remove('pulsing'); nodeDest.classList.add('pulsing');
        
        await sleep(destination === 'cache' ? 300 : 1000); 
        
        packet.style.left = `${coords.router.left}%`; packet.style.top = `${coords.router.top}%`;
        
        await sleep(parseFloat(speed) * 1000);
        nodeDest.classList.remove('pulsing'); nodeRouter.classList.add('pulsing');

        packet.style.left = `${coords.user.left}%`; packet.style.top = `${coords.user.top}%`;
        
        await sleep(parseFloat(speed) * 1000);
        nodeRouter.classList.remove('pulsing'); nodeUser.classList.add('pulsing');
        
        await sleep(300);
        nodeUser.classList.remove('pulsing'); packet.remove(); 
    }

    // =================================================================
    // AUTO-PILOT LOGIC: MENGINTIP DATABASE (REAL-TIME POLLING)
    // =================================================================
    let lastUsedMemory = {}; // Menyimpan memori waktu terakhir API digunakan

    async function pollRealTraffic() {
        try {
            const res = await fetch('../api/api_monitor.php');
            const data = await res.json();
            
            if (data.status === 'success') {
                data.data.forEach(api => {
                    if (api.last_used) {
                        // Jika slot ini baru pertama kali dilihat, catat waktunya saja (jangan trigger animasi)
                        if (!lastUsedMemory[api.slot_id]) {
                            lastUsedMemory[api.slot_id] = api.last_used;
                        } 
                        // Jika waktu last_used BERUBAH (Berarti baru saja menembak API detik ini juga!)
                        else if (lastUsedMemory[api.slot_id] !== api.last_used) {
                            
                            // Trigger animasi bola cahaya sesuai mesin yang bekerja!
                            if (api.provider === 'gemini') simulateTraffic('gemini', true);
                            else if (api.provider === 'groq') simulateTraffic('groq', true);
                            else if (api.provider === 'internal') simulateTraffic('cache', true);

                            // Simpan waktu terbaru ke memori agar tidak diulang-ulang
                            lastUsedMemory[api.slot_id] = api.last_used;
                        }
                    }
                });
            }
        } catch (error) {
            console.log("Auto-Pilot waiting for connection...");
        }
    }

    // Jalankan mata-mata setiap 1 detik
    setInterval(pollRealTraffic, 1000);

</script>

</body>
</html>