<?php
/**
 * admin/get_traffic_stats.php
 * API Internal untuk memberi data real-time ke Dashboard Admin.
 * Sekarang membaca dari tabel api_keys (dinamis) + api_health_monitor (cache).
 */
session_start();
include '../config/database.php';
header('Content-Type: application/json');

// Cek Admin
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    echo json_encode(['error' => 'Unauthorized']); exit;
}

// Fitur Reset/Heal Manual
if (isset($_POST['action']) && $_POST['action'] == 'reset_all') {
    mysqli_query($conn, "UPDATE api_keys SET status='ready', fail_count=0, cooldown_until=NULL");
    echo json_encode(['status' => 'success']); exit;
}

$data = [];

// 1. Cache slot (dari api_health_monitor)
$q_cache = mysqli_query($conn, "SELECT * FROM api_health_monitor WHERE slot_id = 'xieqa_cache'");
if ($q_cache && $cache = mysqli_fetch_assoc($q_cache)) {
    $cache['cooldown_seconds'] = 0;
    $cache['last_used_time'] = $cache['last_used'] ? date('H:i:s', strtotime($cache['last_used'])) : '-';
    $data['internal'][] = $cache;
}

// 2. Semua API keys (dari api_keys)
$query = mysqli_query($conn, "SELECT * FROM api_keys ORDER BY provider, id");
$counter = ['gemini' => 0, 'groq' => 0];

while ($row = mysqli_fetch_assoc($query)) {
    $provider = $row['provider'];
    $counter[$provider] = ($counter[$provider] ?? 0) + 1;
    
    // Hitung sisa cooldown
    $remaining = 0;
    if ($row['status'] == 'cooldown' && $row['cooldown_until']) {
        $now = new DateTime();
        $until = new DateTime($row['cooldown_until']);
        $diff = $now->diff($until);
        $remaining = ($diff->invert == 0) ? ($diff->s + ($diff->i * 60) + ($diff->h * 3600)) : 0;
    }

    $row['cooldown_seconds'] = $remaining;
    $row['last_used_time'] = $row['last_used'] ? date('H:i:s', strtotime($row['last_used'])) : '-';
    $row['seconds_since_used'] = $row['last_used'] ? (time() - strtotime($row['last_used'])) : 999999;
    $row['slot_id'] = $provider . '_key_' . $counter[$provider]; // Kompatibilitas dashboard
    
    $data[$provider][] = $row;
}

echo json_encode($data);
?>