<?php
ini_set('display_errors', 0);
// File: admin/ai_process.php
require_once '../includes/security.php';
secureSessionStart();
if (!isset($_SESSION['admin_id']) || !validateAdminSession()) {
    echo json_encode(['success' => false, 'message' => 'Sesi habis, silakan login ulang.']);
    exit;
}
require_once '../includes/db_connect.php'; 

header('Content-Type: application/json');

// 1. Validasi Request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid Request']);
    exit;
}

// 2. Ambil API Key dengan Aman
try {
    if (isset($pdo)) {
        $stmt = $pdo->query("SELECT gemini_api_key FROM config_cabang LIMIT 1");
        $apiKey = $stmt->fetchColumn();
    } else {
        // Fallback MySQLi
        global $conn;
        $q = mysqli_query($conn, "SELECT gemini_api_key FROM config_cabang LIMIT 1");
        $r = mysqli_fetch_assoc($q);
        $apiKey = $r['gemini_api_key'] ?? '';
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Gagal koneksi database']);
    exit;
}

// Bersihkan API Key dari spasi kosong (trim)
$apiKey = trim($apiKey);

if (empty($apiKey)) {
    echo json_encode(['success' => false, 'message' => 'API Key kosong. Isi dulu di Pengaturan Cabang.']);
    exit;
}

$mode = $_POST['mode'] ?? 'artikel';
$context = $_POST['context'] ?? '';

// 3. Upload File Sementara
if (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
    echo json_encode(['success' => false, 'message' => 'Gagal upload file. Kode Error: ' . $_FILES['image']['error']]);
    exit;
}

$uploadDir = '../uploads/ai_temp/';
if (!file_exists($uploadDir)) mkdir($uploadDir, 0755, true);

$originalExt = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
$fileName = 'ai_' . time() . '.' . $originalExt;
$targetPath = $uploadDir . $fileName;

if (!move_uploaded_file($_FILES['image']['tmp_name'], $targetPath)) {
    echo json_encode(['success' => false, 'message' => 'Gagal memindahkan file ke folder temp.']);
    exit;
}

// 4. Siapkan Data ke Gemini
$fileData = file_get_contents($targetPath);
$base64Data = base64_encode($fileData);
$mimeType = mime_content_type($targetPath);

// Cek tipe file untuk database Promo (Video/Image)
$isVideo = strpos($mimeType, 'video') !== false;
$tipePromo = $isVideo ? 'video' : 'image';

// Role & Prompt Engineering
$role = "Anda adalah Copywriter Profesional yang berpengalaman membuat artikel blog atau artikel promosi untuk website dengan teknik SEO. Gaya bahasa: Profesional, Persuasif, Ramah, dan Menggunakan Bahasa Indonesia yang natural.";

if ($mode == 'artikel') {
    $prompt = "Analisis gambar yang saya upload ini. Saya ingin membuat ARTIKEL BLOG.
    
    Konteks: '$context'
    
    Tugas:
    1. Buat Judul menarik (keyword: Toyota Ciputat).
    2. Meta Description (max 150 char).
    3. Konten Artikel min 350 kata (HTML format: <p>, <ul>, <li>, <strong>, <h2>). NO Markdown (```).
       - Paragraf 1: Hook visual.
       - Paragraf 2: Fitur/Momen.
       - Paragraf 3: Soft selling kredit Tunas Toyota.
       - Penutup: CTA hubungi sales.
    
    Output JSON: { \"judul\": \"...\", \"meta\": \"...\", \"konten\": \"...\" }";
} else {
    $prompt = "Analisis media ini (Foto/Video). Saya ingin membuat KONTEN SOSMED / PROMO.
    
    Konteks: '$context'
    
    Tugas:
    1. Headline Hard Selling.
    2. Caption Pendek (Meta).
    3. Deskripsi Lengkap (HTML: <p>, <br>, <b>). Fokus urgensi & hashtag #TunasToyotaCiputat.
    
    Output JSON: { \"judul\": \"...\", \"meta\": \"...\", \"konten\": \"...\" }";
}

// 5. Eksekusi API Gemini
// Gunakan model stabil (1.5 Flash), 2.5 belum stabil/publik
$model = "gemini-1.5-flash"; 

// --- URL BERSIH TANPA FORMAT MARKDOWN ---
$baseUrl = "[https://generativelanguage.googleapis.com/v1beta/models/](https://generativelanguage.googleapis.com/v1beta/models/)";
$url = $baseUrl . $model . ":generateContent?key=" . $apiKey;

$payload = [
    "system_instruction" => ["parts" => [["text" => $role]]],
    "contents" => [
        [
            "parts" => [
                ["text" => $prompt],
                ["inline_data" => ["mime_type" => $mimeType, "data" => $base64Data]]
            ]
        ]
    ],
    "generation_config" => ["response_mime_type" => "application/json"]
];

$ch = curl_init($url);
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']);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);

// Bypass SSL (Penting buat hosting cPanel/Localhost)
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);

// 6. Error Handling
if ($response === false) {
    echo json_encode(['success' => false, 'message' => "Koneksi Gagal (CURL Error): " . $curlError]);
    exit;
}

if ($httpCode !== 200) {
    echo json_encode(['success' => false, 'message' => "Error API ($httpCode): " . $response]);
    exit;
}

// 7. Parsing Result
$decoded = json_decode($response, true);
$aiRawText = $decoded['candidates'][0]['content']['parts'][0]['text'] ?? '';
$parsedData = json_decode($aiRawText, true);

if (!$parsedData) {
    echo json_encode(['success' => false, 'message' => 'Gagal generate format JSON valid. Silakan coba lagi.']);
    exit;
}

// --- LOGIKA AUTO SAVE DATABASE ---
// Data dari AI
$judul = $parsedData['judul'] ?? 'Draft Otomatis';
$meta = $parsedData['meta'] ?? '';
$konten = $parsedData['konten'] ?? $aiRawText;

if ($mode == 'artikel') {
    // 1. Pindahkan Gambar ke folder Artikel
    $targetDir = '../uploads/artikel/';
    if (!file_exists($targetDir)) mkdir($targetDir, 0755, true);
    
    $newFileName = 'art_' . time() . '.' . $originalExt;
    $finalPath = $targetDir . $newFileName;
    $dbPath = 'uploads/artikel/' . $newFileName;
    
    rename($targetPath, $finalPath);

    // 2. Insert Database Artikel
    try {
        if (isset($pdo)) {
            $sql = "INSERT INTO artikel (judul, meta_description, konten, status, gambar_cover_url, tanggal_buat) 
                    VALUES (:judul, :meta, :konten, 'published', :gambar, CURDATE())";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':judul' => $judul,
                ':meta' => $meta,
                ':konten' => $konten,
                ':gambar' => $dbPath
            ]);
        } else {
            // Fallback MySQLi
            $judul = mysqli_real_escape_string($conn, $judul);
            $meta = mysqli_real_escape_string($conn, $meta);
            $konten = mysqli_real_escape_string($conn, $konten);
            $query = "INSERT INTO artikel (judul, meta_description, konten, status, gambar_cover_url, tanggal_buat) 
                      VALUES ('$judul', '$meta', '$konten', 'published', '$dbPath', CURDATE())";
            mysqli_query($conn, $query);
        }
        $redirectUrl = 'crud_artikel.php';
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Gagal simpan DB: ' . $e->getMessage()]);
        exit;
    }

} else {
    // Mode PROMO
    // 1. Pindahkan Media ke folder Promo
    $targetDir = '../uploads/promo/';
    if (!file_exists($targetDir)) mkdir($targetDir, 0755, true);
    
    $newFileName = 'prm_' . time() . '.' . $originalExt;
    $finalPath = $targetDir . $newFileName;
    $dbPath = 'uploads/promo/' . $newFileName;
    
    rename($targetPath, $finalPath);

    // Default Expired 1 Bulan
    $expiredDate = date('Y-m-d', strtotime('+1 month'));

    // 2. Insert Database Promo
    try {
        if (isset($pdo)) {
            $sql = "INSERT INTO promo (judul, meta_description, deskripsi, gambar_url, tipe, tanggal_berakhir, is_featured) 
                    VALUES (:judul, :meta, :konten, :gambar, :tipe, :expired, 1)";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':judul' => $judul,
                ':meta' => $meta,
                ':konten' => $konten,
                ':gambar' => $dbPath,
                ':tipe' => $tipePromo,
                ':expired' => $expiredDate
            ]);
        } else {
            // Fallback MySQLi
            $judul = mysqli_real_escape_string($conn, $judul);
            $meta = mysqli_real_escape_string($conn, $meta);
            $konten = mysqli_real_escape_string($conn, $konten);
            $query = "INSERT INTO promo (judul, meta_description, deskripsi, gambar_url, tipe, tanggal_berakhir, is_featured) 
                      VALUES ('$judul', '$meta', '$konten', '$dbPath', '$tipePromo', '$expiredDate', 1)";
            mysqli_query($conn, $query);
        }
        $redirectUrl = 'crud_promo.php';
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Gagal simpan DB: ' . $e->getMessage()]);
        exit;
    }
}

// 8. Return Sukses & Redirect
echo json_encode([
    'success' => true,
    'message' => 'Konten berhasil dibuat dan disimpan!',
    'redirect' => $redirectUrl
]);
?>