<?php

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

if(!isset($_SESSION['user_id'])){
    echo json_encode(['success'=>false,'error'=>'No autenticado']);
    exit;
}

include '../../config/db.php';

$gemini_key = 'AQ.Ab8RN6K-AqWOsgYvAziMYGglOv6U6WvZ3aKliUGiGa-MQ0W33Q';

$input = json_decode(file_get_contents('php://input'), true);
if(!$input || !isset($input['messages'])){
    echo json_encode(['success'=>false,'error'=>'Datos invalidos']);
    exit;
}

$messages = $input['messages'];
$user_msg = null;
foreach($messages as $msg){
    if($msg['role'] === 'user') $user_msg = $msg;
}

if(!$user_msg){
    echo json_encode(['success'=>false,'error'=>'Sin mensaje']);
    exit;
}

$parts = [];
$content = $user_msg['content'];

if(is_array($content)){
    foreach($content as $part){
        if($part['type'] === 'text'){
            $parts[] = ['text' => $part['text']];
        } elseif($part['type'] === 'image_url'){
            $data_url = $part['image_url']['url'];
            if(strpos($data_url, 'data:') === 0){
                preg_match('/data:([^;]+);base64,(.+)/', $data_url, $matches);
                $mime_type = $matches[1] ?? 'image/jpeg';
                $b64data   = $matches[2] ?? '';
                $parts[] = ['inline_data' => ['mime_type'=>$mime_type, 'data'=>$b64data]];
            }
        } elseif($part['type'] === 'document'){
            $source = $part['source'] ?? [];
            $parts[] = ['inline_data' => ['mime_type'=>'application/pdf', 'data'=>$source['data']??'']];
        }
    }
} else {
    $parts[] = ['text' => $content];
}

$body = [
    'contents' => [['parts' => $parts]],
    'generationConfig' => ['maxOutputTokens'=>2000, 'temperature'=>0.3]
];

// Usar endpoint v1beta con el nuevo formato de key
$url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent";

$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_HTTPHEADER     => [
        'Content-Type: application/json',
        'x-goog-api-key: ' . $gemini_key,
    ],
    CURLOPT_POSTFIELDS => json_encode($body),
    CURLOPT_TIMEOUT    => 120,
]);

$response = curl_exec($ch);
$error    = curl_error($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if($error){
    echo json_encode(['success'=>false,'error'=>'Error conexion: '.$error]);
    exit;
}

$data = json_decode($response, true);

if($httpcode !== 200){
    $msg = $data['error']['message'] ?? 'Error desconocido';
    echo json_encode(['success'=>false,'error'=>'Gemini error '.$httpcode.': '.$msg]);
    exit;
}

$text = $data['candidates'][0]['content']['parts'][0]['text'] ?? '';

echo json_encode([
    'success' => true,
    'data'    => ['content' => [['type'=>'text','text'=>$text]]]
]);