<?php
// =========================================================================
// admin/konfigurasi.php - PENGATURAN API KEY DINAMIS & MODEL XIEQA LLM
// Developer: Sikawarsito, S.Kom
// =========================================================================

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

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../auth/login_page.php");
    exit;
}

// =========================================================================
// HANDLER: Simpan Model Default (di tabel settings)
// =========================================================================
if (isset($_POST['simpan_model'])) {
    $gemini_model = mysqli_real_escape_string($conn, trim($_POST['gemini_model']));
    $groq_model = mysqli_real_escape_string($conn, trim($_POST['groq_model']));
    
    mysqli_query($conn, "UPDATE settings SET gemini_model = '$gemini_model', groq_model = '$groq_model' WHERE id = 1");
    $_SESSION['msg_success'] = "Model default berhasil diperbarui!";
    header("Location: konfigurasi.php"); exit;
}

// =========================================================================
// HANDLER: Tambah Key Baru
// =========================================================================
if (isset($_POST['tambah_key'])) {
    $provider = ($_POST['provider'] === 'groq') ? 'groq' : 'gemini';
    $raw_key = trim($_POST['api_key']);
    $api_key = mysqli_real_escape_string($conn, $raw_key);
    $label = mysqli_real_escape_string($conn, trim($_POST['label'] ?? ''));
    
    if (empty($api_key)) {
        $_SESSION['msg_error'] = "API Key tidak boleh kosong!";
    } else {
        // Cek duplikat
        $check = mysqli_query($conn, "SELECT id FROM api_keys WHERE api_key = '$api_key'");
        if ($check && mysqli_num_rows($check) > 0) {
            $_SESSION['msg_error'] = "API Key sudah terdaftar di sistem!";
        } else {
            // =====================================================
            // VALIDASI: Test ping API key sebelum simpan
            // =====================================================
            $is_valid = false;
            $error_msg = '';
            
            if ($provider === 'gemini') {
                $test_url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=" . urlencode($raw_key);
                $test_payload = json_encode([
                    "contents" => [["parts" => [["text" => "hi"]]]],
                    "generationConfig" => ["maxOutputTokens" => 5]
                ]);
                $ch = curl_init($test_url);
                curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $test_payload);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
                curl_setopt($ch, CURLOPT_TIMEOUT, 15);
                $res = curl_exec($ch);
                $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                curl_close($ch);
                
                if ($http_code == 200 || $http_code == 429) {
                    $is_valid = true;
                } else {
                    $error_msg = "API Key Gemini TIDAK VALID (HTTP $http_code). Pastikan key benar dan aktif.";
                }
            } else {
                $ch = curl_init('https://api.groq.com/openai/v1/chat/completions');
                $test_payload = json_encode([
                    "model" => "llama-3.3-70b-versatile",
                    "messages" => [["role" => "user", "content" => "hi"]],
                    "max_tokens" => 5
                ]);
                curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $raw_key, 'Content-Type: application/json']);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $test_payload);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
                curl_setopt($ch, CURLOPT_TIMEOUT, 15);
                $res = curl_exec($ch);
                $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                curl_close($ch);
                
                if ($http_code == 200 || $http_code == 429) {
                    $is_valid = true;
                } else {
                    $error_msg = "API Key Groq TIDAK VALID (HTTP $http_code). Pastikan key benar dan aktif.";
                }
            }
            
            if ($is_valid) {
                $q = "INSERT INTO api_keys (provider, api_key, label, status, fail_count, last_used) 
                      VALUES ('$provider', '$api_key', '$label', 'ready', 0, '2000-01-01 00:00:00')";
                if (mysqli_query($conn, $q)) {
                    $_SESSION['msg_success'] = "Key $provider VALID dan berhasil ditambahkan!";
                } else {
                    $_SESSION['msg_error'] = "Gagal menambah key: " . mysqli_error($conn);
                }
            } else {
                $_SESSION['msg_error'] = $error_msg;
            }
        }
    }
    header("Location: konfigurasi.php"); exit;
}

// =========================================================================
// HANDLER: Hapus Key
// =========================================================================
if (isset($_POST['hapus_key'])) {
    $id = (int)$_POST['key_id'];
    if (mysqli_query($conn, "DELETE FROM api_keys WHERE id = $id")) {
        $_SESSION['msg_success'] = "API Key berhasil dihapus.";
    } else {
        $_SESSION['msg_error'] = "Gagal menghapus key.";
    }
    header("Location: konfigurasi.php"); exit;
}

// =========================================================================
// HANDLER: Reset Semua Status
// =========================================================================
if (isset($_POST['reset_semua'])) {
    mysqli_query($conn, "UPDATE api_keys SET status = 'ready', fail_count = 0, cooldown_until = NULL");
    $_SESSION['msg_success'] = "Semua status API Key berhasil di-reset menjadi PRIMA!";
    header("Location: konfigurasi.php"); exit;
}

// =========================================================================
// AMBIL DATA
// =========================================================================
$q_settings = mysqli_query($conn, "SELECT * FROM settings WHERE id = 1");
$cfg = mysqli_fetch_assoc($q_settings);

$gemini_keys = [];
$groq_keys = [];

$q_keys = mysqli_query($conn, "SELECT * FROM api_keys ORDER BY provider, id");
if ($q_keys) {
    while ($row = mysqli_fetch_assoc($q_keys)) {
        if ($row['provider'] === 'gemini') $gemini_keys[] = $row;
        else $groq_keys[] = $row;
    }
}

$sukses = ""; $error = "";
if (isset($_SESSION['msg_success'])) { $sukses = $_SESSION['msg_success']; unset($_SESSION['msg_success']); }
if (isset($_SESSION['msg_error'])) { $error = $_SESSION['msg_error']; unset($_SESSION['msg_error']); }
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Konfigurasi Engine - Xieqa LLM</title>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&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">
    <style>
        body { background-color: #f8fafc; font-family: 'Plus Jakarta Sans', sans-serif; color: #1e293b; }
        .card-panel { background: #ffffff; border: 1px solid #e2e8f0; border-radius: 20px; box-shadow: 0 10px 25px rgba(0,0,0,0.02); }
        .form-control { border-radius: 10px; border-color: #cbd5e1; background-color: #f8fafc; }
        .form-control:focus { box-shadow: none; border-color: #3b82f6; background-color: #ffffff; }
        .label-custom { font-size: 13px; font-weight: 700; color: #64748b; letter-spacing: 0.5px; text-transform: uppercase; margin-bottom: 8px; }
        .header-gemini { color: #0ea5e9; border-bottom: 2px solid #e0f2fe; padding-bottom: 10px; margin-bottom: 25px; }
        .header-groq { color: #f97316; border-bottom: 2px solid #ffedd5; padding-bottom: 10px; margin-bottom: 25px; }
        .btn-save { background: linear-gradient(135deg, #3b82f6, #2563eb); border: none; padding: 12px 30px; font-weight: 700; border-radius: 50px; color: white; transition: all 0.3s; }
        .btn-save:hover { transform: translateY(-2px); box-shadow: 0 8px 20px rgba(37, 99, 235, 0.3); color: white; }
        
        /* Key Card */
        .key-card {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 12px 16px;
            border-radius: 14px;
            border: 1px solid #e2e8f0;
            background: #f8fafc;
            margin-bottom: 10px;
            transition: all 0.2s;
        }
        .key-card:hover { border-color: #94a3b8; background: #f1f5f9; }
        .key-card .key-number {
            width: 28px; height: 28px; border-radius: 50%;
            display: flex; align-items: center; justify-content: center;
            font-size: 11px; font-weight: 800; flex-shrink: 0;
        }
        .key-gemini .key-number { background: #e0f2fe; color: #0ea5e9; }
        .key-groq .key-number { background: #ffedd5; color: #f97316; }
        .key-card .key-value {
            flex: 1; font-family: 'Courier New', monospace; font-size: 13px;
            color: #475569; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
        }
        .key-card .key-label {
            font-size: 11px; color: #94a3b8; font-weight: 600;
            background: #f1f5f9; padding: 2px 8px; border-radius: 6px; white-space: nowrap;
        }
        .key-card .key-status {
            font-size: 10px; font-weight: 700; padding: 3px 8px; border-radius: 20px; text-transform: uppercase;
        }
        .status-ready { background: #dcfce7; color: #16a34a; }
        .status-cooldown { background: #fef3c7; color: #d97706; }
        .status-suspended { background: #fecaca; color: #dc2626; }
        
        /* Add Key Button */
        .btn-add-key {
            display: flex; align-items: center; justify-content: center; gap: 8px;
            width: 100%; padding: 14px; border: 2px dashed #cbd5e1; border-radius: 14px;
            background: transparent; color: #64748b; font-weight: 600; font-size: 14px;
            cursor: pointer; transition: all 0.2s; margin-top: 10px;
        }
        .btn-add-key:hover { border-color: #3b82f6; color: #3b82f6; background: #eff6ff; }
        .btn-add-key.groq-add:hover { border-color: #f97316; color: #f97316; background: #fff7ed; }
        
        /* Add Key Form (hidden by default) */
        .add-key-form {
            display: none; padding: 16px; margin-top: 10px;
            border: 1px solid #e2e8f0; border-radius: 14px; background: #f8fafc;
        }
        .add-key-form.active { display: block; animation: slideDown 0.3s ease; }
        @keyframes slideDown { from { opacity: 0; transform: translateY(-10px); } to { opacity: 1; transform: translateY(0); } }
        
        .counter-badge {
            font-size: 12px; font-weight: 700; padding: 4px 12px;
            border-radius: 20px; letter-spacing: 0.5px;
        }
    </style>
</head>
<body>

    <div class="container py-5 max-w-7xl">
        <div class="d-flex align-items-center justify-content-between mb-4 flex-wrap gap-3">
            <div class="d-flex align-items-center gap-3">
                <div class="bg-dark text-white rounded-4 d-flex align-items-center justify-content-center shadow" style="width: 55px; height: 55px;">
                    <i class="bi bi-sliders fs-3"></i>
                </div>
                <div>
                    <h2 class="fw-bolder m-0 text-dark">Konfigurasi Engine</h2>
                    <p class="text-secondary m-0 fw-medium">Kapasitas Dinamis: Tambah API Key tanpa batas</p>
                </div>
            </div>
            <div class="d-flex gap-2">
                <form method="POST" style="display:inline;">
                    <button type="submit" name="reset_semua" class="btn btn-outline-warning rounded-pill fw-bold px-4 shadow-sm" onclick="return confirm('Reset semua status ke PRIMA?')">
                        <i class="bi bi-arrow-counterclockwise me-1"></i> Reset Status
                    </button>
                </form>
                <a href="dashboard_llm.php" class="btn btn-white border rounded-pill fw-bold text-secondary shadow-sm px-4 bg-white">
                    <i class="bi bi-arrow-left me-1"></i> Kembali
                </a>
            </div>
        </div>

        <?php if($sukses): ?> <div class="alert alert-success fw-bold shadow-sm rounded-4 mb-4 border-0 bg-success text-white"><i class="bi bi-check-circle-fill me-2"></i> <?= $sukses ?></div> <?php endif; ?>
        <?php if($error): ?> <div class="alert alert-danger fw-bold shadow-sm rounded-4 mb-4 border-0"><i class="bi bi-exclamation-triangle-fill me-2"></i> <?= $error ?></div> <?php endif; ?>

        <!-- MODEL DEFAULT -->
        <form method="POST">
            <div class="card-panel p-4 mb-4">
                <h5 class="fw-bold mb-3"><i class="bi bi-cpu me-2 text-primary"></i>Model Default</h5>
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="label-custom text-info">Gemini Model</label>
                        <input type="text" name="gemini_model" class="form-control fw-bold border-info text-info" value="<?= htmlspecialchars($cfg['gemini_model'] ?? 'gemini-2.0-flash') ?>" required>
                    </div>
                    <div class="col-md-6">
                        <label class="label-custom text-warning">Groq Model</label>
                        <input type="text" name="groq_model" class="form-control fw-bold border-warning text-warning" value="<?= htmlspecialchars($cfg['groq_model'] ?? 'llama-3.3-70b-versatile') ?>" required>
                    </div>
                </div>
                <div class="text-end mt-3">
                    <button type="submit" name="simpan_model" class="btn btn-primary rounded-pill fw-bold px-4">
                        <i class="bi bi-save2-fill me-1"></i> Simpan Model
                    </button>
                </div>
            </div>
        </form>

        <div class="row g-4">
            <!-- ==================== CLUSTER GEMINI ==================== -->
            <div class="col-lg-6">
                <div class="card-panel p-4 p-md-5 h-100">
                    <div class="d-flex align-items-center justify-content-between mb-3">
                        <h4 class="fw-bold header-gemini m-0 border-0 pb-0"><i class="bi bi-google me-2"></i>Cluster Gemini</h4>
                        <span class="counter-badge" style="background: #e0f2fe; color: #0ea5e9;"><?= count($gemini_keys) ?> Key</span>
                    </div>

                    <?php foreach ($gemini_keys as $idx => $gk): ?>
                    <div class="key-card key-gemini">
                        <div class="key-number"><?= $idx + 1 ?></div>
                        <div class="key-value" title="<?= htmlspecialchars($gk['api_key']) ?>"><?= htmlspecialchars(substr($gk['api_key'], 0, 12)) ?>...<?= htmlspecialchars(substr($gk['api_key'], -6)) ?></div>
                        <?php if (!empty($gk['label'])): ?><span class="key-label"><?= htmlspecialchars($gk['label']) ?></span><?php endif; ?>
                        <span class="key-status status-<?= $gk['status'] ?>"><?= strtoupper($gk['status']) ?></span>
                        <form method="POST" style="display:inline;" onsubmit="return confirm('Hapus key ini?')">
                            <input type="hidden" name="key_id" value="<?= $gk['id'] ?>">
                            <button type="submit" name="hapus_key" class="btn btn-sm text-danger p-0"><i class="bi bi-trash3-fill"></i></button>
                        </form>
                    </div>
                    <?php endforeach; ?>

                    <?php if (empty($gemini_keys)): ?>
                    <div class="text-center text-muted py-4">
                        <i class="bi bi-inbox fs-1 d-block mb-2 opacity-50"></i>
                        <p class="small mb-0">Belum ada key Gemini</p>
                    </div>
                    <?php endif; ?>

                    <button class="btn-add-key" onclick="toggleAddForm('gemini')">
                        <i class="bi bi-plus-circle-fill"></i> Tambah Key Gemini
                    </button>

                    <div class="add-key-form" id="form-gemini">
                        <form method="POST">
                            <input type="hidden" name="provider" value="gemini">
                            <div class="mb-2">
                                <input type="text" name="api_key" class="form-control" placeholder="Paste API Key Gemini..." required>
                            </div>
                            <div class="mb-2">
                                <input type="text" name="label" class="form-control form-control-sm" placeholder="Label (opsional, misal: Key Utama)">
                            </div>
                            <div class="d-flex gap-2">
                                <button type="submit" name="tambah_key" class="btn btn-info btn-sm rounded-pill fw-bold px-3 text-white"><i class="bi bi-plus me-1"></i>Tambah</button>
                                <button type="button" class="btn btn-light btn-sm rounded-pill px-3" onclick="toggleAddForm('gemini')">Batal</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <!-- ==================== CLUSTER GROQ ==================== -->
            <div class="col-lg-6">
                <div class="card-panel p-4 p-md-5 h-100">
                    <div class="d-flex align-items-center justify-content-between mb-3">
                        <h4 class="fw-bold header-groq m-0 border-0 pb-0"><i class="bi bi-cpu me-2"></i>Cluster Groq</h4>
                        <span class="counter-badge" style="background: #ffedd5; color: #f97316;"><?= count($groq_keys) ?> Key</span>
                    </div>

                    <?php foreach ($groq_keys as $idx => $grk): ?>
                    <div class="key-card key-groq">
                        <div class="key-number"><?= $idx + 1 ?></div>
                        <div class="key-value" title="<?= htmlspecialchars($grk['api_key']) ?>"><?= htmlspecialchars(substr($grk['api_key'], 0, 12)) ?>...<?= htmlspecialchars(substr($grk['api_key'], -6)) ?></div>
                        <?php if (!empty($grk['label'])): ?><span class="key-label"><?= htmlspecialchars($grk['label']) ?></span><?php endif; ?>
                        <span class="key-status status-<?= $grk['status'] ?>"><?= strtoupper($grk['status']) ?></span>
                        <form method="POST" style="display:inline;" onsubmit="return confirm('Hapus key ini?')">
                            <input type="hidden" name="key_id" value="<?= $grk['id'] ?>">
                            <button type="submit" name="hapus_key" class="btn btn-sm text-danger p-0"><i class="bi bi-trash3-fill"></i></button>
                        </form>
                    </div>
                    <?php endforeach; ?>

                    <?php if (empty($groq_keys)): ?>
                    <div class="text-center text-muted py-4">
                        <i class="bi bi-inbox fs-1 d-block mb-2 opacity-50"></i>
                        <p class="small mb-0">Belum ada key Groq</p>
                    </div>
                    <?php endif; ?>

                    <button class="btn-add-key groq-add" onclick="toggleAddForm('groq')">
                        <i class="bi bi-plus-circle-fill"></i> Tambah Key Groq
                    </button>

                    <div class="add-key-form" id="form-groq">
                        <form method="POST">
                            <input type="hidden" name="provider" value="groq">
                            <div class="mb-2">
                                <input type="text" name="api_key" class="form-control" placeholder="Paste API Key Groq..." required>
                            </div>
                            <div class="mb-2">
                                <input type="text" name="label" class="form-control form-control-sm" placeholder="Label (opsional, misal: Key Cadangan)">
                            </div>
                            <div class="d-flex gap-2">
                                <button type="submit" name="tambah_key" class="btn btn-warning btn-sm rounded-pill fw-bold px-3 text-white"><i class="bi bi-plus me-1"></i>Tambah</button>
                                <button type="button" class="btn btn-light btn-sm rounded-pill px-3" onclick="toggleAddForm('groq')">Batal</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function toggleAddForm(provider) {
            const form = document.getElementById('form-' + provider);
            form.classList.toggle('active');
            if (form.classList.contains('active')) {
                form.querySelector('input[name="api_key"]').focus();
            }
        }
    </script>
</body>
</html>