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

// Get API Key
$stmt = $pdo->prepare("SELECT setting_value FROM finggu_settings WHERE setting_key = 'gemini_api_key'");
$stmt->execute();
$apiKey = $stmt->fetchColumn();

if (!$apiKey) {
    die("Error: No API key found in database. Please add it first in the AI Content dashboard.");
}

echo "<h2>🔍 Gemini API Diagnostic Tool</h2>";
echo "<p>Testing API Key: <code>" . substr($apiKey, 0, 5) . "..." . substr($apiKey, -5) . "</code></p>";

$versions = ['v1', 'v1beta'];
foreach ($versions as $v) {
    echo "<h3>Testing Version: $v</h3>";
    $url = "https://generativelanguage.googleapis.com/$v/models?key=$apiKey";
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    echo "<p>HTTP Code: <strong>$httpCode</strong></p>";
    
    if ($httpCode === 200) {
        $data = json_decode($response, true);
        echo "<h4>Available Models:</h4><ul>";
        if (isset($data['models'])) {
            foreach ($data['models'] as $m) {
                echo "<li><code>" . $m['name'] . "</code> (Supports: " . implode(', ', $m['supportedGenerationMethods']) . ")</li>";
            }
        } else {
            echo "<li>No models found in response.</li>";
        }
        echo "</ul>";
    } else {
        echo "<p style='color:red;'>Error: $response</p>";
    }
    echo "<hr>";
}
echo "<p><a href='modern-ai-content.php'>Back to Dashboard</a></p>";
?>
