<?php
// chat_api/_db.php
// Conexão PG para chat. (Depois você troca por env/arquivo fora do webroot.)
declare(strict_types=1);

function chat_pg(): PgSql\Connection {
  static $conn = null;
  if ($conn) return $conn;

  $host = '127.0.0.1';
  $port = '5432';
  $db   = 'ia_pdf';
  $user = 'ia_pdf_user';
  $pass = 'EJ@2026#IApdf123';

  $cs = sprintf("host=%s port=%s dbname=%s user=%s password=%s", $host, $port, $db, $user, $pass);
  $conn = @pg_connect($cs);
  if (!$conn) {
    http_response_code(500);
    echo "DB_CONNECT_FAIL";
    exit;
  }

  // garante schema no search_path
  @pg_query($conn, "SET search_path TO ia, public");
  return $conn;
}

function json_out(array $data, int $code = 200): void {
  http_response_code($code);
  header("Content-Type: application/json; charset=utf-8");
  header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
  header("Pragma: no-cache");
  header("Expires: 0");
  echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  exit;
}

function read_json(): array {
  $raw = file_get_contents("php://input");
  if ($raw === false) return [];
  $j = json_decode($raw, true);
  return is_array($j) ? $j : [];
}
