<?php
// reconocer_ocr.php
// OCR con OpenAI Vision (no depende de extensión; descarga binario y manda base64)

if (!defined('OPENAI_API_KEY')) {
    // si config.php define OPENAI_API_KEY, esto ya está
    // si no, podés levantarla desde env:
    $k = getenv('OPENAI_API_KEY');
    if ($k) define('OPENAI_API_KEY', $k);
}

define('OPENAI_VISION_MODEL', 'gpt-4o-mini'); // modelo con visión
define('OPENAI_CHAT_URL', 'https://api.openai.com/v1/chat/completions');

function ocr_descargar_imagen($url) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_SSL_VERIFYPEER => 0,
        CURLOPT_HEADER => true,
    ]);
    $resp = curl_exec($ch);
    $err  = curl_error($ch);
    $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $headerSize = (int)curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $ct   = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
    curl_close($ch);

    if ($err) return ['ok'=>0,'error'=>$err,'http'=>$code];
    if ($code < 200 || $code >= 300) return ['ok'=>0,'error'=>"HTTP $code",'http'=>$code];

    $headers = substr($resp, 0, $headerSize);
    $body    = substr($resp, $headerSize);

    // Content-Type real (a veces viene con charset)
    $mime = '';
    if (is_string($ct) && $ct !== '') {
        $mime = trim(explode(';', $ct)[0]);
    } else {
        // fallback: buscar en headers
        if (preg_match('/Content-Type:\s*([^\r\n;]+)/i', $headers, $m)) {
            $mime = trim($m[1]);
        }
    }

    if ($body === '' || strlen($body) < 50) {
        return ['ok'=>0,'error'=>'Imagen vacía o muy chica','http'=>$code];
    }

    return ['ok'=>1,'mime'=>$mime ?: 'image/jpeg','bin'=>$body];
}

function ocr_openai_vision_url($imageUrl) {
    if (!defined('OPENAI_API_KEY') || trim(OPENAI_API_KEY) === '') {
        return ['ok'=>0, 'error'=>'Falta OPENAI_API_KEY'];
    }
    if (!$imageUrl) return ['ok'=>0,'error'=>'Falta imageUrl'];

    $dl = ocr_descargar_imagen($imageUrl);
    if (!$dl['ok']) return ['ok'=>0,'error'=>$dl['error'] ?? 'No se pudo descargar imagen','http'=>$dl['http'] ?? null];

    $mime = $dl['mime'];
    // Si no es image/* igual lo intentamos (por tu caso), pero lo normal sería validar
    $b64  = base64_encode($dl['bin']);
    $dataUrl = "data:" . ($mime ?: 'image/jpeg') . ";base64," . $b64;

    $system = "Extraé todo el texto visible de la imagen. Devolvé solo el texto, sin explicación, sin comillas, sin markdown.";
    $userText = "Extraé el texto del flyer lo más completo posible. Respetá saltos de línea cuando ayuden.";

    $payload = [
        'model' => OPENAI_VISION_MODEL,
        'temperature' => 0.0,
        'max_tokens' => 900,
        'messages' => [
            ['role'=>'system','content'=>$system],
            ['role'=>'user','content'=>[
                ['type'=>'text','text'=>$userText],
                ['type'=>'image_url','image_url'=>['url'=>$dataUrl]]
            ]]
        ],
    ];

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => OPENAI_CHAT_URL,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 60,
        CURLOPT_CONNECTTIMEOUT => 15,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => json_encode($payload),
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'Authorization: Bearer ' . OPENAI_API_KEY
        ],
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_SSL_VERIFYPEER => 0,
    ]);

    $resp = curl_exec($ch);
    $err  = curl_error($ch);
    $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($err) return ['ok'=>0,'error'=>$err,'http'=>$code,'raw'=>$resp];

    $data = json_decode($resp, true);
    if (!is_array($data)) return ['ok'=>0,'error'=>'Respuesta OpenAI inválida','http'=>$code,'raw'=>$resp];
    if ($code < 200 || $code >= 300) {
        $msg = $data['error']['message'] ?? 'Error OpenAI';
        return ['ok'=>0,'error'=>$msg,'http'=>$code,'raw'=>$resp];
    }

    $txt = (string)($data['choices'][0]['message']['content'] ?? '');
    $txt = trim(str_replace(["\r\n","\r"], "\n", $txt));
    $txt = preg_replace('/^```[a-zA-Z]*\n|\n```$/', '', $txt);

    return ['ok'=>1,'text'=>$txt,'http'=>$code,'raw'=>$resp];
}
