<?php
/**
 * AI Image Generation API — Nano Banana Pro (Google Gemini)
 * Generates images from text prompts in the contract chat context.
 */
require_once __DIR__ . '/../config/auth.php';
$user = requireLogin();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(['error' => 'POST only'], 405);
}

validateCsrf();

$input = json_decode(file_get_contents('php://input'), true);
$prompt = trim($input['prompt'] ?? '');
$context = trim($input['context'] ?? 'fire department');

if ($prompt === '') {
    jsonResponse(['error' => 'No prompt provided'], 400);
}

$apiKey = env('GOOGLE_GEMINI_API_KEY', '');
if (!$apiKey) {
    jsonResponse(['error' => 'Gemini API key not configured'], 500);
}

// Build image generation prompt with professional context
$fullPrompt = "Professional, clean, high-quality illustration for a fire department portal. "
    . "Style: modern, corporate, suitable for a command center display. "
    . "Context: {$context}. "
    . "Request: {$prompt}";

$url = "https://generativelanguage.googleapis.com/v1beta/models/nano-banana-pro-preview:generateContent?key={$apiKey}";

$payload = json_encode([
    'contents' => [
        ['parts' => [['text' => $fullPrompt]]]
    ],
    'generationConfig' => [
        'responseModalities' => ['IMAGE', 'TEXT'],
    ],
]);

$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $payload,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 60,
    CURLOPT_SSL_VERIFYPEER => false,
]);

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

if ($error) {
    jsonResponse(['error' => 'API error: ' . $error], 502);
}

$data = json_decode($response, true);

if (!$data || isset($data['error'])) {
    $errMsg = $data['error']['message'] ?? 'Unknown error';
    jsonResponse(['error' => $errMsg], 502);
}

// Extract image and text from response
$parts = $data['candidates'][0]['content']['parts'] ?? [];
$imageData = null;
$mimeType = null;
$textResponse = '';

foreach ($parts as $part) {
    if (isset($part['inlineData'])) {
        $imageData = $part['inlineData']['data'];
        $mimeType = $part['inlineData']['mimeType'] ?? 'image/jpeg';
    }
    if (isset($part['text'])) {
        $textResponse = $part['text'];
    }
}

if (!$imageData) {
    jsonResponse(['error' => 'No image generated', 'text' => $textResponse], 400);
}

auditLog('ai_image', $user['id'], substr($prompt, 0, 200));

jsonResponse([
    'image'    => $imageData,
    'mimeType' => $mimeType,
    'text'     => $textResponse,
    'model'    => 'nano-banana-pro-preview',
]);
