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

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

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

// Cek AI_PROVIDER
if (!defined('AI_PROVIDER')) {
    echo "❌ ERROR: AI_PROVIDER tidak didefinisikan di config/config.php\n";
    echo "   Tambahkan: define('AI_PROVIDER', 'gemini');\n\n";
    exit();
}

echo "📋 Provider: " . AI_PROVIDER . "\n";

if (AI_PROVIDER === 'gemini') {
    if (!defined('GEMINI_API_KEY') || GEMINI_API_KEY === 'YOUR_GEMINI_API_KEY_HERE') {
        echo "❌ ERROR: GEMINI_API_KEY belum diisi di config/config.php\n";
        echo "   Dapatkan API Key dari: https://aistudio.google.com/\n\n";
        exit();
    }
    
    echo "✅ API Key: " . substr(GEMINI_API_KEY, 0, 10) . "...\n";
    echo "✅ Model: " . GEMINI_MODEL . "\n";
    echo "✅ URL: " . GEMINI_API_URL . "\n\n";
    
    $payload = [
        'contents' => [
            ['role' => 'user', 'parts' => [['text' => 'Balas dengan "OK - Gemini API working!"']]]
        ],
        'generationConfig' => [
            'temperature' => 0.3,
            'maxOutputTokens' => 50
        ]
    ];
    
    $url = GEMINI_API_URL . '?key=' . GEMINI_API_KEY;
    
    echo "📤 Sending test request...\n";
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $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']);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    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);
    curl_close($ch);
    
    echo "📥 HTTP Code: " . $httpCode . "\n\n";
    
    if ($error) {
        echo "❌ CURL Error: " . $error . "\n";
        exit();
    }
    
    if ($httpCode === 200) {
        echo "✅ SUCCESS!\n";
        $data = json_decode($response, true);
        if (isset($data['candidates'][0]['content']['parts'][0]['text'])) {
            echo "   Response: " . $data['candidates'][0]['content']['parts'][0]['text'] . "\n";
        }
        echo "\n🎉 API berfungsi dengan baik!\n";
    } else {
        echo "❌ HTTP Error: " . $httpCode . "\n";
        echo "Response: " . substr($response, 0, 500) . "\n";
        
        if ($httpCode === 503) {
            echo "\n💡 REKOMENDASI: Model sedang sibuk. Coba model lain di config/config.php:\n";
            echo "   - 'gemini-2.0-flash' (Paling stabil)\n";
            echo "   - 'gemini-1.5-flash' (Sangat stabil)\n";
            echo "   - 'gemini-2.5-flash' (Versi terbaru yang stabil)\n";
        } elseif ($httpCode === 429) {
            echo "\n💡 REKOMENDASI: Kuota habis. Tunggu beberapa menit atau upgrade.\n";
        } elseif ($httpCode === 401 || $httpCode === 403) {
            echo "\n💡 REKOMENDASI: API Key tidak valid. Buat API Key baru di:\n";
            echo "   https://aistudio.google.com/\n";
        } elseif ($httpCode === 404) {
            echo "\n💡 REKOMENDASI: Model tidak ditemukan. Periksa nama model di config/config.php\n";
        }
    }
} else {
    echo "❌ Provider '" . AI_PROVIDER . "' tidak didukung di test ini\n";
}

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