<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/bootstrap.php';

dbnToolsRequireMethod('GET');
dbnToolsRequireAuth();

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');

try {
    $documentId = isset($_GET['document_id']) ? (int)$_GET['document_id'] : 0;
    if ($documentId <= 0) {
        echo json_encode(['ok' => false, 'error' => 'document_id is required']);
        exit;
    }

    $ragDb = dbnToolsRagDb();

    $docStmt = $ragDb->prepare("SELECT id, title FROM documents WHERE id = ? LIMIT 1");
    $docStmt->execute([$documentId]);
    $doc = $docStmt->fetch(PDO::FETCH_ASSOC);
    if (!$doc) {
        echo json_encode(['ok' => false, 'error' => 'Document not found']);
        exit;
    }

    $chunkStmt = $ragDb->prepare("
        SELECT chunk_index, section_title, content
        FROM chunks
        WHERE document_id = ?
        ORDER BY chunk_index ASC
    ");
    $chunkStmt->execute([$documentId]);
    $chunks = [];
    foreach ($chunkStmt as $row) {
        $chunks[] = [
            'chunk_index'   => (int)$row['chunk_index'],
            'section_title' => $row['section_title'] ?? null,
            'content'       => (string)$row['content'],
        ];
    }

    echo json_encode([
        'ok'       => true,
        'document' => ['id' => (int)$doc['id'], 'title' => (string)$doc['title']],
        'chunks'   => $chunks,
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

} catch (Throwable $e) {
    error_log('DBN document-chunks error: ' . $e->getMessage());
    echo json_encode(['ok' => false, 'error' => 'Internal error']);
}
