<?php
// =========================================================================
// api/api_monitor.php - DYNAMIC API HEALTH MONITOR (UNLIMITED SLOTS)
// =========================================================================
session_start();
include '../../config/database.php';

header('Content-Type: application/json');
date_default_timezone_set('Asia/Jakarta');

$apis = [];
$ada_yang_aktif = false;

// =========================================================================
// 1. SLOT INTERNAL: xieqa_cache (dari api_health_monitor — tetap ada)
// =========================================================================
$q_cache = @mysqli_query($conn, "SELECT * FROM api_health_monitor WHERE slot_id = 'xieqa_cache'");
if ($q_cache && $cache_row = mysqli_fetch_assoc($q_cache)) {
    $last_used = strtotime($cache_row['last_used'] ?? '2000-01-01');
    $is_active = (time() - $last_used) <= 6;
    
    $cache_row['health_label'] = 'MEMORI AKTIF';
    $cache_row['health_percent'] = 100;
    $cache_row['sisa_cooldown'] = 0;
    $cache_row['is_active'] = $is_active;
    if ($is_active) $ada_yang_aktif = true;
    
    $apis[] = $cache_row;
} else {
    // Buat slot cache jika belum ada
    @mysqli_query($conn, "INSERT IGNORE INTO api_health_monitor (slot_id, provider, status, fail_count, last_used) VALUES ('xieqa_cache', 'internal', 'ready', 0, NOW())");
    $apis[] = [
        'slot_id' => 'xieqa_cache', 'provider' => 'internal', 'status' => 'ready',
        'fail_count' => 0, 'last_used' => date('Y-m-d H:i:s'), 'cooldown_until' => null,
        'health_label' => 'MEMORI AKTIF', 'health_percent' => 100, 'sisa_cooldown' => 0, 'is_active' => false
    ];
}

// =========================================================================
// 2. SEMUA API KEY DINAMIS (dari tabel api_keys)
// =========================================================================
$q_keys = @mysqli_query($conn, "SELECT * FROM api_keys ORDER BY provider ASC, id ASC");

if ($q_keys) {
    $counter = ['gemini' => 0, 'groq' => 0];
    
    while ($row = mysqli_fetch_assoc($q_keys)) {
        $provider = $row['provider'];
        $counter[$provider] = ($counter[$provider] ?? 0) + 1;
        
        // Deteksi sedang bekerja (aktif dalam 6 detik terakhir)
        $last_used = strtotime($row['last_used'] ?? '2000-01-01');
        $is_active = (time() - $last_used) <= 6;
        
        // Hitung sisa cooldown
        $sisa_cooldown = 0;
        if ($row['status'] == 'cooldown' && !empty($row['cooldown_until'])) {
            $sisa_cooldown = strtotime($row['cooldown_until']) - time();
            if ($sisa_cooldown < 0) {
                $sisa_cooldown = 0;
                @mysqli_query($conn, "UPDATE api_keys SET status='ready', fail_count=0, cooldown_until=NULL WHERE id=" . (int)$row['id']);
                $row['status'] = 'ready';
                $row['fail_count'] = 0;
            }
        }
        
        // Tentukan health label
        if ($row['status'] == 'suspended' || $row['fail_count'] >= 999) {
            $health_label = 'INVALID';
            $health_percent = 0;
            $is_active = false;
        } else if ($row['status'] == 'cooldown') {
            $health_label = 'LIMIT';
            $health_percent = 30;
        } else {
            if ($row['fail_count'] == 0) { $health_label = 'PRIMA'; $health_percent = 100; }
            else if ($row['fail_count'] == 1) { $health_label = 'AWAS'; $health_percent = 75; }
            else { $health_label = 'KRITIS'; $health_percent = 45; }
        }
        
        // Format slot_id untuk kompatibilitas dengan dashboard
        $slot_label = $provider . '_key_' . $counter[$provider];
        
        $apis[] = [
            'slot_id' => $slot_label,
            'provider' => $provider,
            'status' => $row['status'],
            'fail_count' => $row['fail_count'],
            'last_used' => $row['last_used'],
            'cooldown_until' => $row['cooldown_until'],
            'health_label' => $health_label,
            'health_percent' => $health_percent,
            'sisa_cooldown' => $sisa_cooldown,
            'is_active' => $is_active,
            'label' => $row['label'] ?? '',
            'key_id' => $row['id']
        ];
        
        if ($is_active) $ada_yang_aktif = true;
    }
}

echo json_encode(['status' => 'success', 'router_active' => $ada_yang_aktif, 'data' => $apis, 'server_time' => time()]);
?>