<?php
session_start();

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

// 2. KONFIGURASI DATABASE & API
$host = 'localhost';
$user = 'majapahi_omnich';
$pass = 'A1b2c3d4.,@';
$db   = 'majapahi_omnich';
$conn = new mysqli($host, $user, $pass, $db);

// AMBIL API KEY & NOMOR BOT DARI DATABASE / SETTINGS
$res_setting = $conn->query("SELECT setting_value FROM settings WHERE setting_key = 'default_bot_number'");
$sender_bot = ($res_setting && $res_setting->num_rows > 0) ? $res_setting->fetch_assoc()['setting_value'] : '';
$gemini_api_key = 'AIzaSyB7-2jK0s7ddsAnCUWS9RoK5c3wWLL-bOw'; // Gantilah dengan Key terbaru Anda

// 3. LOGIKA AJAX: GENERATE PREVIEW DENGAN AI
if (isset($_POST['action']) && $_POST['action'] === 'generate_preview') {
    $label = $conn->real_escape_string($_POST['label']);
    $prompt = trim($_POST['prompt']);
    $tone = $_POST['tone'];

    // Ambil daftar pelanggan berdasarkan Label
    $sql = "SELECT name, phone_number FROM contacts WHERE label = '$label' LIMIT 20"; // Limit 20 untuk uji coba
    if ($label === 'ALL') $sql = "SELECT name, phone_number FROM contacts LIMIT 20";
    
    $query = $conn->query($sql);
    $targets = [];
    while ($row = $query->fetch_assoc()) {
        $targets[] = $row;
    }

    if (empty($targets)) {
        echo json_encode(['status' => 'error', 'message' => 'Tidak ada pelanggan dengan label tersebut.']);
        exit;
    }

    $preview_data = [];
    $api_url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-flash-latest:generateContent';

    foreach ($targets as $t) {
        $nama = $t['name'];
        $instruksi = "Anda adalah CS A&S Group. Buat 1 pesan WA singkat untuk $nama. Isi: $prompt. Gaya: $tone. HANYA isi pesan tanpa tanda kutip.";

        $data_ai = ["contents" => [["parts" => [["text" => $instruksi]]]]];

        $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_ai));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'X-goog-api-key: ' . $gemini_api_key]);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $response = curl_exec($ch);
        curl_close($ch);

        $res_ai = json_decode($response, true);
        $pesan_final = $res_ai['candidates'][0]['content']['parts'][0]['text'] ?? "Gagal generate pesan.";

        $preview_data[] = [
            'name' => $nama,
            'phone' => $t['phone_number'],
            'message' => trim($pesan_final)
        ];
        usleep(500000); // Jeda 0.5 detik agar API tidak overload
    }

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

// AMBIL DAFTAR LABEL UNTUK FILTER
$labels = $conn->query("SELECT DISTINCT label FROM contacts WHERE label IS NOT NULL AND label != ''");
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Broadcast Center - A&S Group</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;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">
    <style>
        :root { --primary: #059669; --bg: #f8fafc; }
        body { background: var(--bg); font-family: 'Inter', sans-serif; color: #1e293b; }
        .nav-back { padding: 20px 0; }
        .card-custom { border-radius: 20px; border: none; box-shadow: 0 10px 25px rgba(0,0,0,0.05); background: white; padding: 30px; }
        .btn-send { background: linear-gradient(135deg, #059669 0%, #10b981 100%); color: white; border: none; padding: 12px 25px; border-radius: 12px; font-weight: 700; }
        .preview-box { background: #f1f5f9; border-radius: 15px; padding: 20px; max-height: 500px; overflow-y: auto; }
        .chat-bubble { background: #d9fdd3; padding: 12px; border-radius: 10px; margin-bottom: 10px; font-size: 0.9rem; border-left: 4px solid #059669; }
        .loader { display: none; }
    </style>
</head>
<body>

<div class="container">
    <div class="nav-back">
        <a href="admin_panel.php" class="text-decoration-none text-muted fw-bold">← Kembali ke Dashboard</a>
    </div>

    <div class="row g-4">
        <div class="col-lg-5">
            <div class="card-custom">
                <h4 class="fw-800 mb-4">🚀 AI Broadcast Campaign</h4>
                
                <form id="broadcastForm">
                    <div class="mb-3">
                        <label class="form-label fw-bold">1. Pilih Target Pelanggan</label>
                        <select id="targetLabel" class="form-select form-select-lg">
                            <option value="ALL">Semua Pelanggan</option>
                            <?php while($l = $labels->fetch_assoc()): ?>
                                <option value="<?= $l['label'] ?>">Label: <?= $l['label'] ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold">2. Instruksi Pesan (AI Prompt)</label>
                        <textarea id="aiPrompt" class="form-control" rows="4" placeholder="Contoh: Infokan gangguan wifi di area pusat karena kabel optik putus. Sampaikan maaf."></textarea>
                    </div>

                    <div class="mb-4">
                        <label class="form-label fw-bold">3. Gaya Bahasa</label>
                        <select id="aiTone" class="form-select">
                            <option value="professional">Profesional & Sopan</option>
                            <option value="friendly">Santai & Akrab (Banyak Emoji)</option>
                            <option value="urgent">Mendesak & Penting</option>
                        </select>
                    </div>

                    <button type="submit" class="btn btn-send w-100 py-3">
                        <span>🪄 Generate Pratinjau Pesan</span>
                    </button>
                </form>
            </div>
        </div>

        <div class="col-lg-7">
            <div class="card-custom">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5 class="fw-bold mb-0">📱 Pratinjau Pesan Massal</h5>
                    <div class="loader spinner-border spinner-border-sm text-success"></div>
                </div>

                <div id="previewArea" class="preview-box">
                    <div class="text-center py-5 text-muted">
                        <p>Belum ada pratinjau. Atur kampanye di sebelah kiri dan klik Generate.</p>
                    </div>
                </div>

                <button id="btnExecute" class="btn btn-dark w-100 mt-4 py-3 fw-bold d-none">
                    🚀 Kirim Sekarang ke Semua Target
                </button>
            </div>
        </div>
    </div>
</div>

<script>
const form = document.getElementById('broadcastForm');
const previewArea = document.getElementById('previewArea');
const loader = document.querySelector('.loader');
const btnExecute = document.getElementById('btnExecute');

form.addEventListener('submit', async (e) => {
    e.preventDefault();
    
    // UI Loading
    previewArea.innerHTML = '<div class="text-center py-5">AI sedang menyusun pesan satu per satu...</div>';
    loader.style.display = 'block';
    btnExecute.classList.add('d-none');

    const formData = new FormData();
    formData.append('action', 'generate_preview');
    formData.append('label', document.getElementById('targetLabel').value);
    formData.append('prompt', document.getElementById('aiPrompt').value);
    formData.append('tone', document.getElementById('aiTone').value);

    try {
        const response = await fetch('ai_broadcast.php', { method: 'POST', body: formData });
        const res = await response.json();

        if (res.status === 'success') {
            previewArea.innerHTML = '';
            res.data.forEach(item => {
                previewArea.innerHTML += `
                    <div class="mb-3">
                        <small class="fw-bold text-muted">Kepada: ${item.name} (${item.phone})</small>
                        <div class="chat-bubble">${item.message}</div>
                    </div>
                `;
            });
            btnExecute.classList.remove('d-none');
        } else {
            alert(res.message);
            previewArea.innerHTML = `<p class="text-danger text-center">${res.message}</p>`;
        }
    } catch (err) {
        alert("Terjadi kesalahan sistem.");
    } finally {
        loader.style.display = 'none';
    }
});

btnExecute.addEventListener('click', () => {
    alert('Uji Coba Berhasil! Di versi produksi, tombol ini akan mengirimkan pesan asli melalui API WhatsApp Anda.');
});
</script>

</body>
</html>