<?php
require_once '../config/config.php';

// Set header for plain text output
header('Content-Type: text/plain');
header('Access-Control-Allow-Origin: *');

echo "╔══════════════════════════════════════════════════════════════╗\n";
echo "║           GROQ API CONNECTION TEST                         ║\n";
echo "╚══════════════════════════════════════════════════════════════╝\n\n";

// Check API Key
if (GROQ_API_KEY === 'gsk_YOUR_ACTUAL_API_KEY_HERE') {
    echo "❌ ERROR: API Key belum diatur di config/config.php\n";
    echo "   Silakan dapatkan API Key dari: https://console.groq.com\n";
    echo "   Lalu update define('GROQ_API_KEY', 'gsk_...') di config/config.php\n\n";
    exit();
}

echo "✅ API Key: " . substr(GROQ_API_KEY, 0, 10) . "...\n";
echo "✅ Model: " . GROQ_MODEL . "\n";
echo "✅ URL: " . GROQ_API_URL . "\n\n";

echo "📤 Sending test request...\n";

// Test payload
$payload = [
    'model' => GROQ_MODEL,
    'messages' => [
        ['role' => 'system', 'content' => 'Anda adalah asisten FortiGate yang ahli.'],
        ['role' => 'user', 'content' => 'Halo, ini test koneksi. Balas dengan "OK - Groq API working!"']
    ],
    'temperature' => 0.3,
    'max_tokens' => 50
];

$ch = curl_init(GROQ_API_URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . GROQ_API_KEY
]);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);

echo "📥 HTTP Code: " . $httpCode . "\n\n";

if ($error) {
    echo "❌ CURL Error: " . $error . "\n";
    exit();
}

if ($httpCode === 200) {
    $data = json_decode($response, true);
    if (isset($data['choices'][0]['message']['content'])) {
        echo "✅ SUCCESS!\n";
        echo "   Response: " . $data['choices'][0]['message']['content'] . "\n";
        echo "\n🎉 Groq API berfungsi dengan baik!\n";
        echo "   AI Chat sekarang siap digunakan.\n";
    } else {
        echo "❌ Unexpected response format:\n";
        print_r($data);
    }
} else {
    echo "❌ HTTP Error: " . $httpCode . "\n";
    echo "Response: " . substr($response, 0, 800) . "\n";
    
    // Error handling
    if (strpos($response, 'decommissioned') !== false) {
        echo "\n💡 REKOMENDASI: Model sudah tidak digunakan. Update GROQ_MODEL di config/config.php:\n";
        echo "   - 'llama3-70b-8192' (Recommended)\n";
        echo "   - 'llama3-8b-8192' (Fastest)\n";
        echo "   - 'gemma2-9b-it' (Alternative)\n";
    } elseif (strpos($response, 'invalid_api_key') !== false) {
        echo "\n💡 REKOMENDASI: API Key tidak valid.\n";
        echo "   - Periksa kembali API Key di config/config.php\n";
        echo "   - Dapatkan key baru dari: https://console.groq.com\n";
    } elseif (strpos($response, 'rate_limit') !== false) {
        echo "\n💡 REKOMENDASI: Rate limit exceeded.\n";
        echo "   - Tunggu beberapa menit sebelum mencoba lagi\n";
        echo "   - Kurangi frekuensi request\n";
    }
}

echo "\n";
echo "╔══════════════════════════════════════════════════════════════╗\n";
echo "║  Untuk bantuan: cek logs/ai-chat.log                       ║\n";
echo "╚══════════════════════════════════════════════════════════════╝\n";
?>