<?php
require_once '../includes/auth.php';

$auth = new Auth();
$auth->requireLogin();

echo "<h1>GPT API 測試</h1>";

try {
    require_once '../includes/gpt_api.php';
    $gpt_api = new GPTAPI();
    
    echo "<h2>API Key 檢查</h2>";
    $api_key = $gpt_api->getApiKey();
    if ($api_key) {
        echo "<p style='color: green;'>✅ API Key 已設置</p>";
        echo "<p>Key 前10字符: " . substr($api_key, 0, 10) . "...</p>";
    } else {
        echo "<p style='color: red;'>❌ API Key 未設置</p>";
    }
    
    echo "<h2>API 連接測試</h2>";
    $test_prompt = "請簡單回答：什麼是SEO？";
    echo "<p>測試提示: " . htmlspecialchars($test_prompt) . "</p>";
    
    $result = $gpt_api->generateContent($test_prompt, 100);
    
    if (isset($result['success']) && $result['success']) {
        echo "<p style='color: green;'>✅ API 調用成功</p>";
        echo "<div style='background: #f8f9fa; padding: 15px; border-radius: 5px; margin: 10px 0;'>";
        echo "<strong>回應內容:</strong><br>";
        echo nl2br(htmlspecialchars($result['content']));
        echo "</div>";
        
        if (isset($result['usage'])) {
            echo "<p><strong>Token 使用量:</strong> " . json_encode($result['usage']) . "</p>";
        }
    } else {
        echo "<p style='color: red;'>❌ API 調用失敗</p>";
        echo "<div style='background: #f8f9fa; padding: 15px; border-radius: 5px; margin: 10px 0;'>";
        echo "<strong>錯誤詳情:</strong><br>";
        echo "<pre>" . htmlspecialchars(print_r($result, true)) . "</pre>";
        echo "</div>";
    }
    
} catch (Exception $e) {
    echo "<p style='color: red;'>❌ 發生錯誤: " . htmlspecialchars($e->getMessage()) . "</p>";
    echo "<p>錯誤追蹤:</p>";
    echo "<pre>" . htmlspecialchars($e->getTraceAsString()) . "</pre>";
}

echo "<h2>系統資訊</h2>";
echo "<p>PHP 版本: " . phpversion() . "</p>";
echo "<p>cURL 支援: " . (extension_loaded('curl') ? '✅ 是' : '❌ 否') . "</p>";
echo "<p>JSON 支援: " . (extension_loaded('json') ? '✅ 是' : '❌ 否') . "</p>";

echo "<h2>網路連接測試</h2>";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_NOBODY, true);
$result = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);

if ($http_code > 0) {
    echo "<p style='color: green;'>✅ 可以連接到 OpenAI API (HTTP $http_code)</p>";
} else {
    echo "<p style='color: red;'>❌ 無法連接到 OpenAI API</p>";
    if ($error) {
        echo "<p>錯誤: " . htmlspecialchars($error) . "</p>";
    }
}
?>
