<?php
// File: public/cek-model.php

// 1. API Key Groq (Gunakan Key Anda yang berawalan gsk_)
$apiKey = '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'; 

// 2. URL Endpoint Groq untuk melihat daftar model
$url = "https://api.groq.com/openai/v1/models";

// 3. Setup Koneksi (CURL)
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// PENTING: Groq meminta API Key di Header, bukan di URL
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer $apiKey",
    "Content-Type: application/json"
]);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Bypass SSL untuk local/hosting tertentu
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

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

// 4. Tampilkan Hasil
echo "<h1 style='font-family:sans-serif;'>Daftar Model AI Groq yang Tersedia</h1>";

if ($error) {
    echo "<h3 style='color:red'>Koneksi Gagal (CURL Error): $error</h3>";
} elseif ($httpCode !== 200) {
    echo "<h3 style='color:red'>API Error (HTTP $httpCode):</h3>";
    echo "<pre>" . htmlspecialchars($response) . "</pre>";
} else {
    $data = json_decode($response, true);
    
    // Groq menyimpan daftar model di dalam array 'data'
    if (isset($data['data'])) {
        echo "<table border='1' cellpadding='10' style='border-collapse:collapse; font-family:sans-serif; width:100%;'>";
        echo "<tr style='background:#f4f4f4;'>
                <th>ID Model (Salin ini ke ai-logic.php)</th>
                <th>Pemilik (Owned By)</th>
                <th>Keterangan</th>
              </tr>";
        
        foreach ($data['data'] as $model) {
            $modelId = $model['id'];
            
            // Rekomendasi model terbaik untuk Modul Ajar
            $isRecommended = ($modelId == 'llama-3.3-70b-versatile');
            $style = $isRecommended ? "style='background-color:#e8f5e9; font-weight:bold;'" : "";
            
            echo "<tr $style>";
            echo "<td><code style='color:#d81b60; font-size:1.1em;'>$modelId</code></td>";
            echo "<td>" . ($model['owned_by'] ?? 'Groq') . "</td>";
            echo "<td>" . ($isRecommended ? "⭐ <b>Sangat Disarankan</b>" : "Tersedia") . "</td>";
            echo "</tr>";
        }
        echo "</table>";
    } else {
        echo "<h3 style='color:red'>Format Data Tidak Dikenal:</h3>";
        echo "<pre>" . print_r($data, true) . "</pre>";
    }
}
?>