<?php
session_start();

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

// =========================================================================
// 🔑 MASUKKAN API KEY GEMINI ANDA YANG BARU DI SINI
// =========================================================================
$gemini_api_key = 'AIzaSyB7-2jK0s7ddsAnCUWS9RoK5c3wWLL-bOw'; 

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'simulate_ai') {
    $prompt = trim($_POST['prompt']);
    $tone = $_POST['tone'];
    
    if ($gemini_api_key === 'TARUH_API_KEY_BARU_ANDA_DISINI' || empty($gemini_api_key)) {
        echo json_encode(['status' => 'error', 'message' => 'API Key Gemini belum diisi di kode PHP!']);
        exit;
    }

    $customers = ['Bapak Budi', 'Ibu Siti', 'Kak Andi'];
    $results = [];

    // =========================================================================
    // MENGGUNAKAN MODEL YANG SUDAH TERBUKTI AKTIF DI AKUN ANDA
    // =========================================================================
    $api_url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-flash-latest:generateContent?key=' . $gemini_api_key;

    foreach ($customers as $nama) {
        $system_instruction = "Anda adalah Customer Service profesional dari perusahaan internet A&S Group. ";
        $system_instruction .= "Buatkan 1 pesan WhatsApp singkat untuk pelanggan bernama '$nama'. ";
        $system_instruction .= "Inti pesan yang harus disampaikan: '$prompt'. ";
        
        if ($tone == 'friendly') {
            $system_instruction .= "Gaya bahasa santai, akrab, dan wajib gunakan banyak emoji. ";
        } elseif ($tone == 'urgent') {
            $system_instruction .= "Gaya bahasa tegas, formal, dan berikan kesan sangat mendesak. ";
        } else {
            $system_instruction .= "Gaya bahasa sangat profesional, sopan, dan baku. ";
        }
        $system_instruction .= "Berikan langsung isi pesannya saja tanpa tanda kutip dan tanpa teks penjelasan tambahan.";

        $data = [
            "contents" => [
                [
                    "parts" => [
                        ["text" => $system_instruction]
                    ]
                ]
            ]
        ];

        $ch = curl_init($api_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);

        $response = curl_exec($ch);
        $curl_error = curl_error($ch);
        curl_close($ch);

        $pesan_balasan = "";
        if ($curl_error) {
            $pesan_balasan = "🚨 Error Server/cURL: " . $curl_error;
        } else {
            $hasil_ai = json_decode($response, true);
            
            if (isset($hasil_ai['candidates'][0]['content']['parts'][0]['text'])) {
                $pesan_balasan = trim($hasil_ai['candidates'][0]['content']['parts'][0]['text']);
            } elseif (isset($hasil_ai['error'])) {
                $pesan_balasan = "🚨 Ditolak Google: " . $hasil_ai['error']['message'];
            } else {
                $pesan_balasan = "🚨 Respon Tidak Dikenal: " . htmlspecialchars($response);
            }
        }

        $results[] = [
            'target' => $nama,
            'message' => $pesan_balasan
        ];

        // Jeda 1.5 detik agar Google tidak mendeteksi sebagai spam
        sleep(1.5);
    }

    echo json_encode(['status' => 'success', 'data' => $results]);
    exit;
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Blast Sandbox - OmniDesk</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">
    <style>
        body { background-color: #f0f4f8; font-family: 'Inter', sans-serif; color: #1e293b; padding-bottom: 50px; }
        .playground-header { background: linear-gradient(135deg, #059669 0%, #10b981 100%); padding: 40px; border-radius: 24px; color: white; margin-top: 20px; margin-bottom: 30px; box-shadow: 0 15px 30px rgba(16, 185, 129, 0.2); }
        .glass-card { background: white; border-radius: 20px; padding: 30px; box-shadow: 0 10px 30px rgba(0,0,0,0.03); border: 1px solid rgba(226,232,240,0.8); height: 100%; }
        .form-control, .form-select { border-radius: 12px; padding: 15px; border-color: #e2e8f0; background: #f8fafc; font-weight: 500; }
        .form-control:focus, .form-select:focus { border-color: #10b981; box-shadow: 0 0 0 4px rgba(16,185,129,0.1); background: white; }
        .btn-ai { background: linear-gradient(135deg, #059669 0%, #34d399 100%); color: white; font-weight: bold; border: none; border-radius: 12px; padding: 15px; transition: 0.2s; }
        .btn-ai:hover { transform: translateY(-2px); box-shadow: 0 8px 20px rgba(52,211,153,0.3); color: white;}
        .mockup-chat { background: #efeae2; border-radius: 16px; padding: 15px; margin-bottom: 15px; border: 1px solid #e9edef; position: relative; }
        .mockup-bubble { background: #d9fdd3; padding: 12px 16px; border-radius: 10px; border-top-right-radius: 0; box-shadow: 0 1px 1px rgba(0,0,0,0.1); font-size: 0.9rem; color: #111b21; display: inline-block; max-width: 90%; }
        .mockup-title { font-weight: 700; font-size: 0.8rem; color: #64748b; margin-bottom: 8px; text-transform: uppercase; letter-spacing: 1px;}
        #loader { display: none; }
    </style>
</head>
<body>

<div class="container">
    <div class="playground-header d-flex justify-content-between align-items-center flex-wrap gap-3">
        <div>
            <h1 class="fw-bold mb-1">✨ Real AI Sandbox (Online)</h1>
            <p class="mb-0 opacity-75">Sistem sudah terkoneksi langsung dengan otak Google Gemini.</p>
        </div>
        <a href="admin_panel.php" class="btn btn-light fw-bold" style="border-radius: 12px;">Kembali ke Admin</a>
    </div>

    <div class="row g-4">
        <div class="col-lg-5">
            <div class="glass-card">
                <h5 class="fw-bold mb-4">⚙️ Perintahkan AI Anda</h5>
                <form id="aiForm">
                    <div class="mb-4">
                        <label class="form-label text-muted">Ketik Instruksi Bebas</label>
                        <textarea id="promptInput" class="form-control" rows="5" placeholder="Contoh: Tolong buatkan info bahwa besok jaringan wifi mati jam 10 pagi karena pemadaman PLN." required></textarea>
                    </div>
                    <div class="mb-4">
                        <label class="form-label text-muted">Gaya Bahasa (Tone)</label>
                        <select id="toneInput" class="form-select">
                            <option value="professional">👔 Profesional & Sopan</option>
                            <option value="friendly">😊 Santai & Akrab (Banyak Emoji)</option>
                            <option value="urgent">🚨 Tegas & Mendesak</option>
                        </select>
                    </div>
                    <button type="submit" class="btn btn-ai w-100 d-flex justify-content-center align-items-center gap-2">
                        <span id="btnText">🪄 Suruh AI Menulis Pesan</span>
                        <div id="loader" class="spinner-border spinner-border-sm text-light" role="status"></div>
                    </button>
                </form>
            </div>
        </div>

        <div class="col-lg-7">
            <div class="glass-card d-flex flex-column">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h5 class="fw-bold mb-0">📱 Jawaban Asli Gemini</h5>
                    <span class="badge bg-success">Online & Connected</span>
                </div>
                
                <div id="resultArea" class="flex-grow-1" style="background: #e2e8f0; border-radius: 16px; padding: 20px; overflow-y: auto; min-height: 400px;">
                    <div class="text-center text-muted" style="margin-top: 100px;">
                        <div class="fs-1 mb-2">🧠</div>
                        Silakan ketik instruksi di sebelah kiri dan lihat bagaimana keajaiban AI bekerja.
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.getElementById('aiForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const prompt = document.getElementById('promptInput').value;
    const tone = document.getElementById('toneInput').value;
    const btnText = document.getElementById('btnText');
    const loader = document.getElementById('loader');
    const resultArea = document.getElementById('resultArea');

    btnText.innerText = "Gemini sedang mengetik...";
    loader.style.display = "inline-block";
    this.querySelector('button').disabled = true;

    const formData = new FormData();
    formData.append('action', 'simulate_ai');
    formData.append('prompt', prompt);
    formData.append('tone', tone);

    fetch('test_ai_blast.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if(data.status === 'success') {
            resultArea.innerHTML = ''; 
            data.data.forEach(item => {
                const formattedMessage = item.message.replace(/\n/g, '<br>');
                const chatHtml = `
                    <div class="mockup-chat">
                        <div class="mockup-title">Kirim ke: ${item.target}</div>
                        <div class="text-end">
                            <div class="mockup-bubble text-start">
                                ${formattedMessage}
                            </div>
                        </div>
                    </div>
                `;
                resultArea.innerHTML += chatHtml;
            });
        } else {
            alert(data.message);
        }
    })
    .catch(error => {
        alert("Terjadi kesalahan jaringan/Koneksi terputus!");
        console.error(error);
    })
    .finally(() => {
        btnText.innerText = "🪄 Suruh AI Menulis Pesan";
        loader.style.display = "none";
        this.querySelector('button').disabled = false;
    });
});
</script>

</body>
</html>