<?php
// =========================================================================
// api_bot/index.php - SIKA AI DEVELOPER PORTAL (FRICTIONLESS)
// =========================================================================

session_start();
include '../config/database.php';

// 1. Cek Login User (Direct Redirect)
if (!isset($_SESSION['user_id'])) {
    header("Location: ../auth/login_page.php");
    exit;
}

$user_id = $_SESSION['user_id'];

// --- SISTEM CRM (POP-UP ADMIN & STATUS BLOKIR) ---
$q_user_llm = mysqli_query($conn, "SELECT llm_status, llm_message FROM users WHERE id = $user_id");
$user_llm_data = mysqli_fetch_assoc($q_user_llm);

$admin_popup = "";
if (!empty($user_llm_data['llm_message'])) {
    $admin_popup = $user_llm_data['llm_message'];
    mysqli_query($conn, "UPDATE users SET llm_message = NULL WHERE id = $user_id");
}

if ($user_llm_data['llm_status'] == 'blocked') {
    die("
    <!DOCTYPE html>
    <html lang='id'>
    <head><title>Akses Dibekukan</title><link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'></head>
    <body class='bg-light d-flex align-items-center justify-content-center vh-100'>
        <div class='text-center p-5 bg-white rounded-4 shadow' style='max-width: 500px;'>
            <h1 class='text-danger display-1 mb-3'>⛔</h1>
            <h3 class='fw-bold text-dark'>Akses Dibekukan</h3>
            <p class='text-secondary mb-4'>Layanan Developer Portal Anda telah diblokir. $admin_popup</p>
            <a href='../auth/login_page.php' class='btn btn-primary rounded-pill px-4 fw-bold'>Kembali</a>
        </div>
    </body>
    </html>
    ");
}

// 2. Logika Create API Key Baru (TANPA DOMAIN RESTRICTION)
if (isset($_POST['create_key'])) {
    $q_user_tier = mysqli_query($conn, "SELECT status_akun FROM users WHERE id = $user_id");
    $user_tier_data = mysqli_fetch_assoc($q_user_tier);
    $status_akun = $user_tier_data['status_akun'] ?? 'free';
    
    $max_keys = ($status_akun == 'pro') ? 5 : 1;
    $q_count = mysqli_query($conn, "SELECT COUNT(id) as total FROM api_key_bot WHERE user_id = $user_id AND status = 'active'");
    $count_data = mysqli_fetch_assoc($q_count);
    
    // JIKA BATAS TERCAPAI (POP-UP UPSELL)
    if ($count_data['total'] >= $max_keys) {
        if ($status_akun == 'free') {
            $_SESSION['error_limit_popup'] = "Maaf, Anda menggunakan akun FREE yang hanya terbatas untuk membuat 1 API Key. Silakan upgrade ke PRO untuk mendapatkan 5 API Key sekaligus dan kuota Token Unlimited!";
        } else {
            $_SESSION['error_limit_popup'] = "Maaf, akun PRO Anda telah mencapai batas maksimal pembuatan 5 API Key. Silakan hapus salah satu key lama Anda jika ingin membuat yang baru.";
        }
    } else {
        $nama_project = mysqli_real_escape_string($conn, $_POST['nama_project']);
        $model = mysqli_real_escape_string($conn, $_POST['model']);
        $versi = mysqli_real_escape_string($conn, $_POST['versi']);
        
        $new_key = 'sika-' . bin2hex(random_bytes(16));
        
        // INSERT TANPA allowed_domain
        mysqli_query($conn, "INSERT INTO api_key_bot (user_id, api_key, nama_project, model, versi, status) 
                             VALUES ($user_id, '$new_key', '$nama_project', '$model', '$versi', 'active')");
        $_SESSION['notif_api'] = "API Key untuk project '$nama_project' berhasil dibuat dan siap digunakan!";
    }
    header("Location: index.php");
    exit;
}

// Logika Hapus API Key
if (isset($_POST['delete_key'])) {
    $id_key = (int)$_POST['id_key'];
    mysqli_query($conn, "DELETE FROM api_key_bot WHERE id = $id_key AND user_id = $user_id");
    $_SESSION['notif_api'] = "API Key berhasil dihapus secara permanen.";
    header("Location: index.php");
    exit;
}

// Menangkap Notifikasi
$pesan = ""; $error = ""; $popup_limit = "";
if (isset($_SESSION['notif_api'])) { $pesan = $_SESSION['notif_api']; unset($_SESSION['notif_api']); }
if (isset($_SESSION['error_api'])) { $error = $_SESSION['error_api']; unset($_SESSION['error_api']); }
if (isset($_SESSION['error_limit_popup'])) { $popup_limit = $_SESSION['error_limit_popup']; unset($_SESSION['error_limit_popup']); }

// Ambil Semua API Key Milik User
$q_keys = mysqli_query($conn, "SELECT * FROM api_key_bot WHERE user_id = $user_id AND status = 'active' ORDER BY created_at DESC");
$total_keys = mysqli_num_rows($q_keys);

$endpoint_url = "https://generatedpromptpro.online/xieqa/llm/api/bot_api.php";
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>XIEQA LLM - Developer Portal</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github-dark.min.css">
    <style>
        body { background-color: #f0f4f9; font-family: 'Inter', sans-serif; }
        .card-premium { background: #ffffff; border: 1px solid #e2e8f0; border-radius: 20px; box-shadow: 0 4px 20px rgba(0,0,0,0.04); }
        .btn-live-gemini { background: linear-gradient(90deg, #4285f4, #9b72cb, #d96570); border: none; padding: 10px 28px; border-radius: 50px; color: white; font-weight: 700; }
        .mode-btn.active { background: #e8f0fe; color: #1a73e8; font-weight: 600; }
        .code-container { border-radius: 12px; background: #0d1117; padding: 1.5em; font-family: monospace; color: #e6edf3; overflow-x: auto; margin-bottom: 0; }
        .file-badge-info { display: flex; align-items: flex-start; gap: 10px; background: #e8f0fe; color: #1a73e8; padding: 14px 18px; border-radius: 12px; font-size: 13.5px; font-weight: 600; border: 1px solid #d2e3fc; margin-bottom: 15px; line-height: 1.5; }
        .file-badge-info i { font-size: 18px; margin-top: -2px; }
        .nav-api-scroll { flex-wrap: nowrap; overflow-x: auto; white-space: nowrap; padding-bottom: 8px; scrollbar-width: thin; }
        .nav-api-scroll::-webkit-scrollbar { height: 6px; }
        .nav-api-scroll::-webkit-scrollbar-thumb { background-color: #cbd5e1; border-radius: 10px; }
    </style>
</head>
<body>
    <div class="container py-5">
        <div class="row justify-content-center">
            <div class="col-lg-10">
                <div class="d-flex align-items-center justify-content-between mb-4">
                    <h2 class="fw-bold m-0 text-dark"><i class="bi bi-cpu text-primary me-2"></i> XIEQA LLM</h2>
                    <a href="../index.php" class="btn btn-white border rounded-pill fw-bold text-secondary shadow-sm px-4">Kembali</a>
                </div>

                <?php if($pesan): ?><div class="alert alert-success fw-bold"><i class="bi bi-check-circle-fill"></i> <?= $pesan ?></div><?php endif; ?>
                <?php if($error): ?><div class="alert alert-danger fw-bold"><i class="bi bi-exclamation-triangle-fill"></i> <?= $error ?></div><?php endif; ?>

                <div class="row g-4 mb-4">
                    <div class="col-md-4">
                        <div class="card-premium p-4 h-100">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h5 class="fw-bold m-0"><i class="bi bi-plus-circle-dotted text-primary me-2"></i>Buat API Baru</h5>
                                <a href="docs_model.php" class="btn btn-sm btn-outline-info rounded-pill fw-bold" style="font-size: 11px;"><i class="bi bi-journal-text"></i> Panduan Mesin</a>
                            </div>
                            <form method="POST">
                                <div class="mb-3">
                                    <label class="form-label fw-bold small text-dark">Nama Project</label>
                                    <input type="text" name="nama_project" class="form-control form-control-sm bg-light" placeholder="Cth: Bot Telegram" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label fw-bold small text-dark">Model Mesin</label>
                                    <select name="model" class="form-select form-select-sm bg-light">
                                        <option value="xieqaLLM-Go">XieqaLLM-Go (High Speed)</option>
                                        <option value="xieqaLLM-GQ">XieqaLLM-GQ (High Logic)</option>
                                        <option value="xieqaLLM-HIBRYT">XieqaLLM-HIBRYT (Auto-Fallback)</option>
                                    </select>
                                </div>
                                <div class="mb-4">
                                    <label class="form-label fw-bold small text-dark">Versi / Mode</label>
                                    <select name="versi" class="form-select form-select-sm bg-light">
                                        <option value="cepat">Mode Cepat (Singkat)</option>
                                        <option value="penalaran">Mode Penalaran (Analisis)</option>
                                        <option value="pro">Mode Pro (Profesional)</option>
                                        <option value="all">All Mode (Natural / Tanpa Batasan)</option>
                                    </select>
                                </div>
                                <button type="submit" name="create_key" class="btn-live-gemini w-100">Generate Key</button>
                            </form>
                        </div>
                    </div>

                    <div class="col-md-8">
                        <div class="card-premium p-4 h-100">
                            <h5 class="fw-bold mb-3"><i class="bi bi-shield-lock-fill text-warning me-2"></i>Kunci Akses Anda</h5>
                            <div class="table-responsive">
                                <table class="table table-hover align-middle">
                                    <thead><tr><th>Nama Project</th><th>API Key</th><th class="text-end">Aksi</th></tr></thead>
                                    <tbody>
                                        <?php while($row = mysqli_fetch_assoc($q_keys)): ?>
                                        <tr>
                                            <td>
                                                <div class="fw-bold"><?= htmlspecialchars($row['nama_project']) ?></div>
                                                <span class="badge bg-success text-white mt-1 px-2 py-1"><i class="bi bi-globe"></i> Bebas Akses</span>
                                            </td>
                                            <td>
                                                <span class="badge bg-primary px-3 py-2 cursor-pointer" onclick="navigator.clipboard.writeText('<?= $row['api_key'] ?>'); alert('Disalin!');">
                                                    <?= substr($row['api_key'], 0, 10) ?>...
                                                </span>
                                            </td>
                                            <td class="text-end">
                                                <form method="POST"><input type="hidden" name="id_key" value="<?= $row['id'] ?>"><button type="submit" name="delete_key" class="btn btn-sm btn-outline-danger border-0" onclick="return confirm('Hapus?')"><i class="bi bi-trash-fill"></i></button></form>
                                            </td>
                                        </tr>
                                        <?php endwhile; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card-premium p-4">
                    <h5 class="fw-bold mb-4 text-dark"><i class="bi bi-code-square text-primary me-2"></i> Cara Integrasi API</h5>
                    
                    <div class="nav mb-3 d-flex gap-2 nav-api-scroll" role="tablist">
                        <button class="btn btn-outline-primary btn-sm active" data-bs-toggle="pill" data-bs-target="#pills-curl">Terminal (cURL)</button>
                        <button class="btn btn-outline-primary btn-sm" data-bs-toggle="pill" data-bs-target="#pills-php">PHP Native</button>
                        <button class="btn btn-outline-primary btn-sm" data-bs-toggle="pill" data-bs-target="#pills-laravel">Laravel</button>
                        <button class="btn btn-outline-primary btn-sm" data-bs-toggle="pill" data-bs-target="#pills-python">Python</button>
                        <button class="btn btn-outline-primary btn-sm" data-bs-toggle="pill" data-bs-target="#pills-django">Django</button>
                        <button class="btn btn-outline-primary btn-sm" data-bs-toggle="pill" data-bs-target="#pills-android">Android (Kotlin)</button>
                        <button class="btn btn-outline-primary btn-sm" data-bs-toggle="pill" data-bs-target="#pills-arduino">Arduino / ESP</button>
                        <button class="btn btn-outline-primary btn-sm" data-bs-toggle="pill" data-bs-target="#pills-telegram">Telegram Bot</button>
                    </div>

                    <div class="tab-content">
                        <div class="tab-pane fade show active" id="pills-curl">
                            <div class="file-badge-info">
                                <i class="bi bi-info-circle-fill"></i>
                                <div>Buka Terminal/CMD (Command Prompt) di komputer Anda, lalu paste perintah di bawah ini. Ganti variabel <b>{API_KEY_ANDA}</b> sesuai dengan milik Anda.</div>
                            </div>
                            <div class="code-container">
<pre><code class="language-bash">curl -X POST <?= $endpoint_url ?> \
-H "Content-Type: application/json" \
-H "Authorization: Bearer {API_KEY_ANDA}" \
-d '{
    "pesan": "Halo Xieqa LLM"
}'</code></pre>
                            </div>
                        </div>

                        <div class="tab-pane fade" id="pills-php">
                            <div class="file-badge-info">
                                <i class="bi bi-info-circle-fill"></i>
                                <div>Gunakan library <b>cURL</b> bawaan PHP. Anda bisa meletakkan kode ini di file <code>.php</code> manapun. Pastikan ekstensi curl di `php.ini` server Anda sudah aktif.</div>
                            </div>
                            <div class="code-container">
<pre><code class="language-php">&lt;?php
$api_key = "{API_KEY_ANDA}";
$endpoint = "<?= $endpoint_url ?>";

$payload = [ "pesan" => "Halo Xieqa LLM" ];
$ch = curl_init($endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/json",
    "Authorization: Bearer " . $api_key
]);
$response = curl_exec($ch);
curl_close($ch);

// Output berupa format JSON string
echo $response;
?&gt;</code></pre>
                            </div>
                        </div>

                        <div class="tab-pane fade" id="pills-laravel">
                            <div class="file-badge-info">
                                <i class="bi bi-info-circle-fill"></i>
                                <div>Menggunakan <b>Http Facade</b> bawaan Laravel yang sangat rapi. Sangat disarankan untuk meletakkan kode ini di dalam Controller dan memanggil API Key dari file <code>.env</code> Anda.</div>
                            </div>
                            <div class="code-container">
<pre><code class="language-php">use Illuminate\Support\Facades\Http;

// Lakukan request POST dengan Token
$response = Http::withToken('{API_KEY_ANDA}')->post('<?= $endpoint_url ?>', [
    'pesan' => 'Tolong buatkan puisi tentang alam.'
]);

// Ambil jawaban teks secara langsung dari JSON
if ($response->successful()) {
    $hasil_ai = $response->json('choices.0.message.content');
    echo $hasil_ai;
}</code></pre>
                            </div>
                        </div>

                        <div class="tab-pane fade" id="pills-python">
                            <div class="file-badge-info">
                                <i class="bi bi-info-circle-fill"></i>
                                <div>Anda <b>wajib menginstal library requests</b> terlebih dahulu. Buka terminal Anda dan ketikkan perintah: <code>pip install requests</code> sebelum menjalankan script ini.</div>
                            </div>
                            <div class="code-container">
<pre><code class="language-python">import requests

headers = { 
    "Content-Type": "application/json", 
    "Authorization": "Bearer {API_KEY_ANDA}"
}

payload = {
    "pesan": "Tuliskan script python untuk mencari bilangan prima."
}

# Tembak API Server
response = requests.post("<?= $endpoint_url ?>", json=payload, headers=headers)
data = response.json()

# Cetak hasil balasan
if data.get("status") == "success":
    print("Xieqa LLM:", data["choices"][0]["message"]["content"])
else:
    print("Error:", data.get("message"))</code></pre>
                            </div>
                        </div>

                        <div class="tab-pane fade" id="pills-django">
                            <div class="file-badge-info">
                                <i class="bi bi-info-circle-fill"></i>
                                <div>Integrasi ini diletakkan di dalam file <code>views.py</code> Django Anda. Jangan lupa untuk <code>pip install requests</code> dan hubungkan view ini ke <code>urls.py</code> Anda.</div>
                            </div>
                            <div class="code-container">
<pre><code class="language-python">import requests
from django.http import JsonResponse, HttpResponse

def xieqa_view(request):
    url = "<?= $endpoint_url ?>"
    headers = {
        "Content-Type": "application/json",
        "Authorization": "Bearer {API_KEY_ANDA}"
    }
    payload = {"pesan": "Tolong jelaskan MVT di arsitektur Django."}
    
    try:
        response = requests.post(url, json=payload, headers=headers)
        data = response.json()
        
        if data.get("status") == "success":
            ai_reply = data["choices"][0]["message"]["content"]
            return HttpResponse(f"&lt;h3&gt;Jawaban AI:&lt;/h3&gt; &lt;p&gt;{ai_reply}&lt;/p&gt;")
        else:
            return JsonResponse({"error": data.get("message")}, status=403)
            
    except Exception as e:
        return JsonResponse({"error": str(e)}, status=500)</code></pre>
                            </div>
                        </div>

                        <div class="tab-pane fade" id="pills-android">
                            <div class="file-badge-info">
                                <i class="bi bi-info-circle-fill"></i>
                                <div>Buka file <code>build.gradle (Module: app)</code> di Android Studio. Tambahkan baris ini di blok dependencies: <code>implementation("com.squareup.okhttp3:okhttp:4.12.0")</code> lalu klik Sync Now.</div>
                            </div>
                            <div class="code-container">
<pre><code class="language-kotlin">import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import java.io.IOException

val client = OkHttpClient()

// Siapkan pesan JSON
val jsonPayload = JSONObject().put("pesan", "Halo Xieqa, buatkan sapaan di Kotlin")
val requestBody = jsonPayload.toString().toRequestBody("application/json".toMediaTypeOrNull())

// Siapkan Request
val request = Request.Builder()
    .url("<?= $endpoint_url ?>")
    .addHeader("Authorization", "Bearer {API_KEY_ANDA}")
    .post(requestBody)
    .build()

// Eksekusi API secara Asynchronous
client.newCall(request).enqueue(object : Callback {
    override fun onFailure(call: Call, e: IOException) { 
        e.printStackTrace() 
    }
    
    override fun onResponse(call: Call, response: Response) {
        val responseData = response.body?.string()
        if (response.isSuccessful && responseData != null) {
            val jsonResponse = JSONObject(responseData)
            if (jsonResponse.getString("status") == "success") {
                val aiReply = jsonResponse.getJSONArray("choices")
                    .getJSONObject(0).getJSONObject("message").getString("content")
                
                println("Balasan AI: $aiReply")
            }
        }
    }
})</code></pre>
                            </div>
                        </div>

                        <div class="tab-pane fade" id="pills-arduino">
                            <div class="file-badge-info">
                                <i class="bi bi-info-circle-fill"></i>
                                <div>Library <code>&lt;HTTPClient.h&gt;</code> dan <code>&lt;WiFi.h&gt;</code> sudah bawaan dari Board Manager ESP32/ESP8266. Pastikan mikrokontroler Anda terhubung dengan internet WiFi yang stabil.</div>
                            </div>
                            <div class="code-container">
<pre><code class="language-cpp">#include &lt;WiFi.h&gt;
#include &lt;HTTPClient.h&gt;

// Ganti dengan koneksi WiFi Anda
const char* ssid = "NAMA_WIFI_ANDA";
const char* password = "PASSWORD_WIFI_ANDA";

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) { 
    delay(500); 
    Serial.print("."); 
  }
  Serial.println(" Connected!");

  if(WiFi.status() == WL_CONNECTED){
    HTTPClient http;
    http.begin("<?= $endpoint_url ?>");
    
    // Header Wajib
    http.addHeader("Content-Type", "application/json");
    http.addHeader("Authorization", "Bearer {API_KEY_ANDA}");

    // Pesan JSON (Perhatikan penggunaan escape backslash \")
    String payload = "{\"pesan\":\"Tolong tuliskan puisi pendek 2 baris.\"}";
    int httpResponseCode = http.POST(payload);

    if (httpResponseCode > 0) {
      String response = http.getString();
      Serial.println(httpResponseCode);
      Serial.println(response);
    } else {
      Serial.print("Error code: ");
      Serial.println(httpResponseCode);
    }
    http.end();
  }
}

void loop() {
  // Biarkan kosong
}</code></pre>
                            </div>
                        </div>

                        <div class="tab-pane fade" id="pills-telegram">
                            <div class="file-badge-info d-block">
                                <div class="d-flex align-items-center mb-2">
                                    <i class="bi bi-info-circle-fill me-2 fs-5"></i>
                                    <h6 class="mb-0 fw-bold">Panduan Integrasi Webhook Telegram</h6>
                                </div>
                                <ol class="mb-0 ps-3 small text-dark" style="line-height: 1.6;">
                                    <li>Dapatkan <b>Token Bot</b> baru dari aplikasi Telegram dengan chat ke akun resmi <b>@BotFather</b> lalu ketik <code>/newbot</code>.</li>
                                    <li>Karakteristik Webhook mewajibkan kode PHP di bawah ini <b>di-hosting di server/cPanel</b> dan harus menggunakan <b>HTTPS (SSL Aktif)</b>. Bot tidak akan menangkap pesan jika script hanya di localhost/offline.</li>
                                    <li>Simpan dan upload kode di bawah ke hosting Anda. Catat URL tempat file itu berada (contoh: <code>https://domain-anda.com/bot_kamu.php</code>).</li>
                                    <li>Beri perintah kepada Telegram untuk mengirim semua pesan masuk ke file tersebut dengan membuka link ini di Browser Anda:<br>
                                        <code class="d-inline-block mt-1 p-1 bg-white rounded border text-danger" style="user-select:all;">https://api.telegram.org/bot&lt;TOKEN_BOT_ANDA&gt;/setWebhook?url=&lt;URL_FILE_HOSTING_ANDA&gt;</code>
                                    </li>
                                    <li>Selesai! Jika layar menampilkan pesan <code>"Webhook was set"</code>, bot Anda sudah pintar dan siap dicoba!</li>
                                </ol>
                            </div>
                            <div class="code-container">
<pre><code class="language-php">&lt;?php
$bot_token = "TOKEN_BOT_TELEGRAM_ANDA";
$api_key = "{API_KEY_ANDA}";
$endpoint = "<?= $endpoint_url ?>";

// Menangkap kiriman pesan dari Telegram
$update = json_decode(file_get_contents("php://input"), TRUE);
$chat_id = $update["message"]["chat"]["id"] ?? null;
$pesan_user = $update["message"]["text"] ?? null;

if ($chat_id && $pesan_user) {
    // 1. Tembak ke Mesin AI Xieqa
    $payload = [ "pesan" => $pesan_user ];
    $ch = curl_init($endpoint);
    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 " . $api_key
    ]);
    
    $res = curl_exec($ch);
    curl_close($ch);
    $data_ai = json_decode($res, true);
    $jawaban_ai = $data_ai['choices'][0]['message']['content'] ?? 'Sistem AI sedang Maintenance.';

    // 2. Balas ke user Telegram
    $url_bot = "https://api.telegram.org/bot" . $bot_token . "/sendMessage";
    file_get_contents($url_bot . "?chat_id=" . $chat_id . "&text=" . urlencode($jawaban_ai));
}
?&gt;</code></pre>
                            </div>
                        </div>

                    </div>
                </div>

                <div class="text-center mt-5 pt-4 border-top">
                    <p class="text-muted small fw-bold mb-0">&copy; <?= date('Y') ?> XIEQA AI Dev Sikawarsito. All Rights Reserved.</p>
                </div>

            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
    
    <?php if(!empty($admin_popup)): ?>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            Swal.fire({
                title: 'Pesan dari Administrator',
                text: '<?= htmlspecialchars($admin_popup, ENT_QUOTES) ?>',
                icon: 'info',
                confirmButtonColor: '#1a73e8',
                confirmButtonText: 'Saya Mengerti'
            });
        });
    </script>
    <?php endif; ?>

    <?php if(!empty($popup_limit)): ?>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            Swal.fire({
                title: 'Batas Pembuatan Key Tercapai!',
                text: '<?= htmlspecialchars($popup_limit, ENT_QUOTES) ?>',
                icon: 'warning',
                confirmButtonColor: '#d33',
                confirmButtonText: 'Oke, Saya Mengerti'
            });
        });
    </script>
    <?php endif; ?>
    
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            document.querySelectorAll('pre code').forEach((el) => { hljs.highlightElement(el); });

            // Otomatis tambahkan tombol COPY di setiap blok kode API
            document.querySelectorAll('.code-container').forEach(container => {
                container.style.position = 'relative';
                const copyBtn = document.createElement('button');
                copyBtn.className = 'btn btn-sm btn-outline-light copy-code-btn';
                copyBtn.style.cssText = 'position: absolute; top: 15px; right: 20px; font-size: 11px; z-index: 10; background: rgba(0,0,0,0.6);';
                copyBtn.innerHTML = '<i class="bi bi-clipboard"></i> Salin Kode';
                
                copyBtn.addEventListener('click', () => {
                    const codeBlock = container.querySelector('code');
                    navigator.clipboard.writeText(codeBlock.innerText).then(() => {
                        copyBtn.innerHTML = '<i class="bi bi-check-circle text-success"></i> Disalin!';
                        setTimeout(() => { copyBtn.innerHTML = '<i class="bi bi-clipboard"></i> Salin Kode'; }, 2000);
                    });
                });
                container.appendChild(copyBtn);
            });
        });
    </script>
</body>
</html>