<?php
/**
 * debug_cek.php — Diagnostic Tool (Admin Only)
 * Dilindungi: hanya bisa diakses oleh admin yang sudah login.
 */
session_start();
include 'config/database.php';

// Proteksi akses — hanya admin
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    http_response_code(403);
    header('Location: auth/login_page.php');
    exit;
}

echo "<h2>🛠️ Xieqa System Diagnostic — Admin Only</h2><hr>";

// 1. Sesi
echo "<b>1. Sesi:</b> " . (isset($_SESSION['user_id']) ? "✅ OK (ID: " . $_SESSION['user_id'] . ")" : "❌ Tidak aktif") . "<br>";

// 2. Koneksi Database
$dbOk = ($conn && !mysqli_connect_errno());
echo "<b>2. Database:</b> " . ($dbOk ? "✅ Terhubung" : "❌ Gagal: " . mysqli_connect_error()) . "<br>";

// 3. Cek slot LLM aktif (tanpa sebut nama provider)
$resSlot = @mysqli_query($conn, "SELECT COUNT(*) as jml FROM api_health_monitor WHERE status = 'ready'");
$slotAktif = $resSlot ? (mysqli_fetch_assoc($resSlot)['jml'] ?? 0) : 0;
echo "<b>3. Slot LLM Aktif:</b> " . ($slotAktif > 0 ? "✅ $slotAktif slot siap" : "⚠️ Tidak ada slot aktif") . "<br>";

// 4. Cek API Key master tersedia
$resMaster = @mysqli_query($conn, "SELECT COUNT(*) as jml FROM api_key_bot WHERE status = 'active'");
$masterCount = $resMaster ? (mysqli_fetch_assoc($resMaster)['jml'] ?? 0) : 0;
echo "<b>4. Master API Key:</b> " . ($masterCount > 0 ? "✅ $masterCount key aktif" : "❌ Tidak ada key aktif") . "<br>";

// 5. Cache LLM
$resCache = @mysqli_query($conn, "SELECT COUNT(*) as jml FROM cache_llm");
$cacheCount = $resCache ? (mysqli_fetch_assoc($resCache)['jml'] ?? 0) : 0;
echo "<b>5. Cache LLM:</b> ✅ $cacheCount entri tersimpan<br>";

echo "<hr><small>Xieqa Ecosystem Diagnostic v4 | Hanya untuk Administrator</small>";
?>