<?php
// FILE: tes_debug.php (Simpan di Folder Utama sejajar dengan index.php)
// Tujuannya untuk membypass proteksi folder 'api/'

error_reporting(E_ALL);
ini_set('display_errors', 1);

// Perubahan Path: Tidak pakai '../' karena file ini ada di root
include 'config/database.php';

echo "<h1>🔍 DIAGNOSA KEAMANAN & KONEKSI</h1>";
echo "<hr>";

// 1. CEK KONEKSI DATABASE
echo "<h3>1. Cek Database</h3>";
if (!$conn) {
    die("<span style='color:red'>❌ Koneksi Gagal!</span>");
} else {
    echo "<span style='color:green'>✅ Database Terhubung.</span><br>";
}

// Ambil data settings
$res = mysqli_query($conn, "SELECT * FROM settings WHERE id = 1");
$cfg = mysqli_fetch_assoc($res);

// 2. CEK ISI API KEY (Apakah tersimpan?)
echo "<h3>2. Cek Stok API Key</h3>";
$g_key = $cfg['gemini_api_key'];
$groq_keys = array_filter([
    $cfg['groq_api_key'], $cfg['groq_api_key_2'], 
    $cfg['groq_api_key_3'], $cfg['groq_api_key_4']
]);

if (empty($g_key)) {
    echo "<span style='color:red'>❌ Gemini Key: KOSONG!</span><br>";
} else {
    echo "<span style='color:green'>✅ Gemini Key: Ada (" . substr($g_key, 0, 8) . "...)</span><br>";
}

if (empty($groq_keys)) {
    echo "<span style='color:red'>❌ Groq Keys: KOSONG SEMUA!</span><br>";
} else {
    echo "<span style='color:green'>✅ Groq Keys: Ditemukan " . count($groq_keys) . " biji.</span><br>";
    echo "<ul>";
    foreach($groq_keys as $k) {
        echo "<li>Key: " . substr($k, 0, 10) . "...</li>";
    }
    echo "</ul>";
}

// 3. TES REAL KONEKSI KE GEMINI (Bypass SSL)
echo "<h3>3. Tes Tembus ke Server Gemini</h3>";

// Gunakan URL Model List yang pasti 200 OK jika key benar
$url = "https://generativelanguage.googleapis.com/v1beta/models?key=" . $g_key;

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // PENTING UNTUK LOCALHOST
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$result = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
curl_close($ch);

echo "<b>HTTP Status Code:</b> $http_code <br>";

if ($http_code == 200) {
    echo "<h2 style='color:green'>✅ SUKSES! Server Gemini Merespon.</h2>";
    echo "API Key Anda Valid dan Server Google bisa dihubungi.<br>";
} elseif ($http_code == 400) {
    echo "<h2 style='color:red'>❌ API Key Salah / Kadaluarsa!</h2>";
    echo "Google menolak Key Anda. Cek kembali di tabel settings.<br>";
} elseif ($http_code == 0) {
    echo "<h2 style='color:red'>❌ Koneksi Internet Putus / cURL Error!</h2>";
    echo "Pesan Error: $err <br>";
    echo "Tips: Pastikan XAMPP connect internet (cacerts.pem) atau matikan antivirus sebentar.";
} else {
    echo "<h2 style='color:orange'>⚠️ Masalah Lain (Code: $http_code)</h2>";
    echo "Response: " . substr($result, 0, 200) . "...";
}
?>