<?php
// app/api/analyze_upload.php - uploads + extracts text + optional vision summary
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/openai_client.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { exit; }

$pdo = db();
$storage = __DIR__ . '/../storage/uploads';
if (!is_dir($storage)) @mkdir($storage, 0777, true);

$conversation_id = isset($_POST['conversation_id']) ? intval($_POST['conversation_id']) : 1;
$mode = isset($_POST['mode']) ? $_POST['mode'] : 'summary'; // summary | ocr_only

if (empty($_FILES['files'])) {
    echo json_encode(['error' => 'No files uploaded']); exit;
}

function command_exists($cmd) {
    $where = (stripos(PHP_OS, 'WIN') === 0) ? 'where' : 'command -v';
    $process = proc_open("$where $cmd", [
        1 => ['pipe', 'w'],
        2 => ['pipe', 'w']
    ], $pipes);
    if (is_resource($process)) {
        $output = stream_get_contents($pipes[1]);
        fclose($pipes[1]); fclose($pipes[2]);
        $code = proc_close($process);
        return $code === 0 && trim($output) !== '';
    }
    return false;
}

function extract_text_docx($file) {
    // Fallback docx extractor without external deps
    $zip = new ZipArchive();
    $ok = $zip->open($file);
    if ($ok === TRUE) {
        $xml = $zip->getFromName('word/document.xml');
        $zip->close();
        if ($xml !== false) {
            $xml = preg_replace('~<w:p[^>]*>~', "\n", $xml);
            $xml = strip_tags($xml);
            return html_entity_decode($xml, ENT_QUOTES | ENT_XML1, 'UTF-8');
        }
    }
    return '';
}

function extract_text_generic($path, $mime, $name) {
    $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
    // PDF via pdftotext or pdftohtml
    if ($ext === 'pdf' || $mime === 'application/pdf') {
        if (command_exists('pdftotext')) {
            $tmpOut = tempnam(sys_get_temp_dir(), 'pdf');
            @unlink($tmpOut);
            $cmd = 'pdftotext -layout -nopgbrk ' . escapeshellarg($path) . ' -';
            $out = shell_exec($cmd);
            if ($out) return $out;
        }
        if (command_exists('pdftohtml')) {
            $cmd = 'pdftohtml -q -s -i -stdout ' . escapeshellarg($path);
            $html = shell_exec($cmd);
            if ($html) return trim(strip_tags($html));
        }
        return '';
    }
    // DOC via antiword or catdoc
    if ($ext === 'doc' && in_array($mime, ['application/msword','application/octet-stream','application/vnd.ms-office'])) {
        if (command_exists('antiword')) {
            return shell_exec('antiword ' . escapeshellarg($path));
        }
        if (command_exists('catdoc')) {
            return shell_exec('catdoc ' . escapeshellarg($path));
        }
        return '';
    }
    // DOCX
    if ($ext === 'docx' || $mime === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
        $t = extract_text_docx($path);
        return $t;
    }
    // TXT/CSV
    if (in_array($ext, ['txt','csv','log']) || strpos($mime, 'text/') === 0) {
        return file_get_contents($path);
    }
    // Images -> return base64 data URL (for vision)
    if (strpos($mime, 'image/') === 0) {
        $data = base64_encode(file_get_contents($path));
        return 'data:' . $mime . ';base64,' . $data;
    }
    return '';
}

$summaries = [];
$concat_text = '';
$image_blocks = [];

foreach ($_FILES['files']['tmp_name'] as $idx => $tmp) {
    $name = $_FILES['files']['name'][$idx];
    $mime = $_FILES['files']['type'][$idx];
    $size = $_FILES['files']['size'][$idx];
    if (!is_uploaded_file($tmp)) continue;
    $dest = $storage . '/' . uniqid('f_', true) . '_' . preg_replace('/[^a-zA-Z0-9_\.\-]/','_', $name);
    move_uploaded_file($tmp, $dest);

    $text_or_dataurl = extract_text_generic($dest, $mime, $name);

    // Create a user message record referencing file
    $stmt = $pdo->prepare("INSERT INTO messages (conversation_id, role, content) VALUES (?, 'user', ?)");
    $stmt->execute([$conversation_id, "Uploaded file: $name"]);
    $msg_id = $pdo->lastInsertId();

    $stmt2 = $pdo->prepare("INSERT INTO attachments (message_id, filename, mime, path, extracted_text) VALUES (?, ?, ?, ?, ?)");
    $stmt2->execute([$msg_id, $name, $mime, $dest, (strpos($text_or_dataurl, 'data:') === 0 ? null : $text_or_dataurl)]);

    if (strpos($mime, 'image/') === 0 && strpos($text_or_dataurl, 'data:') === 0) {
        $image_blocks[] = [
            'type' => 'input_image',
            'image_url' => $text_or_dataurl
        ];
        $summaries[] = "Image uploaded: $name";
    } else {
        $len = strlen($text_or_dataurl);
        $summaries[] = $len ? "Text extracted from $name (" . $len . " chars)" : "Stored $name (no extractor available)";
        $concat_text .= "\n\n### " . $name . "\n" . ($len ? substr($text_or_dataurl, 0, 15000) : '[No extractor available]');
    }
}

$result = ['files' => $summaries];

// If mode is summary, ask OpenAI to summarize extracted content and/or images
if ($mode === 'summary' && openai_key()) {
    $content = [];
    if ($concat_text) {
        $content[] = ['type' => 'input_text', 'text' => "Ringkas isi dokumen berikut (buat poin-poin utama, angka penting, entitas, dan rekomendasi singkat):\n" . $concat_text];
    } else {
        $content[] = ['type' => 'input_text', 'text' => "Analisis gambar ini secara ringkas (objek, teks penting, insight)."];
    }
    foreach ($image_blocks as $ib) $content[] = $ib;

    $body = [
        'model' => openai_model(),
        'input' => [
            ['role' => 'user', 'content' => $content]
        ]
    ];
    try {
        $resp = openai_create($body);
        // Try to pull first text
        $summary = '';
        if (isset($resp['output'][0]['content'][0]['text'])) {
            $summary = $resp['output'][0]['content'][0]['text'];
        } elseif (isset($resp['content'][0]['text'])) {
            $summary = $resp['content'][0]['text'];
        } else {
            $summary = json_encode($resp);
        }
        // Save assistant summary
        $stmt = $pdo->prepare("INSERT INTO messages (conversation_id, role, content) VALUES (?, 'assistant', ?)");
        $stmt->execute([$conversation_id, "[Analyzer]\n" . $summary]);
        $result['summary'] = $summary;
    } catch (Exception $e) {
        $result['summary_error'] = $e->getMessage();
    }
}

echo json_encode($result);
