<?php
// File: admin/ai_generator.php
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(E_ALL);

// WAJIB: load security SEBELUM memanggil secureSessionStart()
require_once '../includes/security.php';
secureSessionStart();

if (!isset($_SESSION['admin_id']) || !validateAdminSession()) {
    header("Location: login.php"); exit;
}

require_once '../includes/db_connect.php';
require_once '../includes/cache.php';
require_once '../includes/functions.php';

$page_title = 'AI Content Generator';
require_once 'includes/header.php';

// Cek API Key
$apiKey = "";
try {
    if (isset($pdo)) {
        $stmt = $pdo->query("SELECT gemini_api_key FROM config_cabang LIMIT 1");
        $config = $stmt->fetch(PDO::FETCH_ASSOC);
        $apiKey = $config['gemini_api_key'] ?? '';
    }
} catch (Exception $e) {}

$mode = isset($_GET['mode']) ? $_GET['mode'] : 'artikel';
?>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<style>
    .ai-wrapper h2, .ai-wrapper h3, .ai-wrapper p { margin-bottom: 0.5rem; }
    .ai-wrapper button:focus { outline: none; }
    video { max-height: 300px; width: 100%; object-fit: contain; background: #000; }
</style>

<div class="content-wrapper ai-wrapper bg-gray-50 p-4">
    <div class="container-fluid">
        
        <!-- Header -->
        <div class="row mb-4">
            <div class="col-12 text-center mt-4">
                <span class="bg-gray-800 text-white px-3 py-1 rounded-full text-xs font-bold tracking-wider">
                    <i class="fas fa-robot mr-1"></i> AI GEN 2026 (FREE TIER)
                </span>
                <h1 class="text-3xl font-extrabold text-gray-900 mt-2">BIKIN KONTEN INSTAN</h1>
                <p class="text-gray-500">Upload foto/video, pilih otak AI gratisan, dan biarkan sistem bekerja.</p>
            </div>
        </div>

        <?php if (empty($apiKey)): ?>
        <div class="alert alert-danger text-center" role="alert">
            <i class="fas fa-exclamation-triangle mr-2"></i> <b>API Key Belum Diset!</b> Isi dulu di menu Web Profile.
        </div>
        <?php endif; ?>

        <!-- Main Card -->
        <div class="row justify-content-center">
            <div class="col-md-8 col-lg-6">
                <div class="card shadow-lg border-0 rounded-lg overflow-hidden">
                    <div class="card-body p-0">
                        
                        <!-- Mode Buttons -->
                        <div class="flex justify-center gap-4 p-6 bg-white">
                            <a href="?mode=artikel" class="px-6 py-2 rounded-lg font-bold transition <?php echo $mode == 'artikel' ? 'bg-red-600 text-white shadow-lg' : 'bg-gray-100 text-gray-500 hover:bg-gray-200'; ?>">
                                <i class="fas fa-newspaper mr-1"></i> Artikel
                            </a>
                            <a href="?mode=promo" class="px-6 py-2 rounded-lg font-bold transition <?php echo $mode == 'promo' ? 'bg-red-600 text-white shadow-lg' : 'bg-gray-100 text-gray-500 hover:bg-gray-200'; ?>">
                                <i class="fas fa-tags mr-1"></i> Promo
                            </a>
                        </div>

                        <!-- Form -->
                        <div class="p-6 pt-0 bg-white">
                            <form id="aiForm" enctype="multipart/form-data">
                                <input type="hidden" name="mode" value="<?php echo $mode; ?>">

                                <!-- Upload Area -->
                                <div class="border-2 border-dashed border-gray-300 rounded-xl p-8 text-center hover:bg-gray-50 transition relative mb-4" id="drop-area">
                                    <input type="file" name="image" id="file-input" 
                                           class="absolute inset-0 w-full h-full opacity-0 cursor-pointer" 
                                           accept="image/*<?php echo $mode == 'promo' ? ',video/mp4' : ''; ?>" required>
                                    
                                    <div id="preview-box" class="hidden mb-2">
                                        <img id="img-preview" src="" class="max-h-48 mx-auto rounded shadow hidden">
                                        <video id="video-preview" controls class="max-h-48 mx-auto rounded shadow hidden"></video>
                                    </div>

                                    <div id="placeholder-box">
                                        <div class="w-12 h-12 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-2 text-gray-400">
                                            <i class="fas fa-cloud-upload-alt text-xl"></i>
                                        </div>
                                        <p class="font-bold text-gray-700">Klik untuk Pilih File</p>
                                    </div>
                                </div>

                                <!-- Context -->
                                <div class="mb-4">
                                    <label class="block text-xs font-bold text-gray-500 uppercase mb-1">2. Info Tambahan (Konteks)</label>
                                    <textarea name="context" class="w-full border border-gray-300 rounded-lg p-3 text-sm focus:border-red-500 focus:ring-1 focus:ring-red-500 outline-none" rows="3" placeholder="<?php echo $mode == 'artikel' ? 'Contoh: Serah terima Innova Zenix...' : 'Contoh: Promo diskon servis 25%...'; ?>"></textarea>
                                </div>

                                <!-- Model AI -->
                                <div class="mb-6">
                                    <label class="block text-xs font-bold text-gray-500 uppercase mb-1">3. Pilih Model AI (Gratis & Cepat)</label>
                                    <div class="relative">
                                        <select name="model_id" class="w-full border border-gray-300 rounded-lg p-3 text-sm focus:border-red-500 focus:ring-1 focus:ring-red-500 outline-none bg-white appearance-none cursor-pointer">
                                            <option value="gemini-2.5-flash" selected>🚀 Gemini 2.5 Flash (Rekomendasi Utama)</option>
                                            <option value="gemini-2.5-flash-lite">✨ Gemini 2.5 Flash-Lite (Versi Paling Ringan)</option>
                                            <option value="gemini-3.0-flash-preview">⚡ Gemini 3.0 Flash Preview (Tercanggih)</option>
                                            <option value="gemini-2.0-flash">🕒 Gemini 2.0 Flash (Backup)</option>
                                        </select>
                                        <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-700">
                                            <i class="fas fa-chevron-down text-xs"></i>
                                        </div>
                                    </div>
                                    <p class="text-[10px] text-gray-400 mt-1 italic">*Semua model di atas masuk kategori Free Tier (Gratis).</p>
                                </div>

                                <!-- Submit -->
                                <button type="submit" id="btn-generate" class="w-full bg-gray-900 hover:bg-black text-white font-bold py-3 rounded-lg shadow-md transition transform hover:-translate-y-0.5 flex justify-center items-center gap-2">
                                    <span>GENERATE & SIMPAN</span>
                                    <i class="fas fa-magic"></i>
                                </button>
                            </form>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    const fileInput = document.getElementById('file-input');
    const previewBox = document.getElementById('preview-box');
    const placeholderBox = document.getElementById('placeholder-box');
    const imgPreview = document.getElementById('img-preview');
    const videoPreview = document.getElementById('video-preview');

    fileInput.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            placeholderBox.classList.add('hidden');
            previewBox.classList.remove('hidden');
            if (file.type.startsWith('video/')) {
                imgPreview.classList.add('hidden');
                videoPreview.classList.remove('hidden');
                videoPreview.src = URL.createObjectURL(file);
            } else {
                videoPreview.classList.add('hidden');
                imgPreview.classList.remove('hidden');
                imgPreview.src = URL.createObjectURL(file);
            }
        }
    });

    document.getElementById('aiForm').addEventListener('submit', async function(e) {
        e.preventDefault();
        const btn = document.getElementById('btn-generate');
        const originalText = btn.innerHTML;

        if (!fileInput.files.length) {
            Swal.fire('Ups!', 'Pilih file dulu Om.', 'warning');
            return;
        }

        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sedang Berpikir & Menyimpan...';
        btn.classList.add('opacity-75');

        try {
            const formData = new FormData(this);
            const response = await fetch('ai_process.php', { method: 'POST', body: formData });
            const textResponse = await response.text();
            let result;
            try {
                result = JSON.parse(textResponse);
            } catch (err) {
                console.error("Server Error:", textResponse);
                throw new Error("Respon Server tidak valid (bukan JSON). Cek console.");
            }

            if (result.success) {
                Swal.fire({
                    icon: 'success',
                    title: 'Berhasil!',
                    text: 'Konten sudah dibuat dan disimpan. Mengalihkan...',
                    timer: 1500,
                    showConfirmButton: false
                }).then(() => { window.location.href = result.redirect; });
            } else {
                throw new Error(result.message);
            }
        } catch (error) {
            Swal.fire('Gagal', error.message || 'Terjadi kesalahan sistem.', 'error');
            btn.disabled = false;
            btn.innerHTML = originalText;
            btn.classList.remove('opacity-75');
        }
    });
</script>

<?php require_once 'includes/footer.php'; ?>
