<?php
// chat_api/history.php
declare(strict_types=1);
require_once __DIR__.'/_db.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
  json_out(['ok'=>false,'error'=>'method_not_allowed'], 405);
}

$room = isset($_GET['room']) ? trim((string)$_GET['room']) : 'geral';
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 30;
if ($limit < 10) $limit = 10;
if ($limit > 80) $limit = 80;

$before_id = isset($_GET['before_id']) ? (int)$_GET['before_id'] : 0;

$conn = chat_pg();

$res = pg_query_params($conn, "SELECT id FROM ia.chat_rooms WHERE slug=$1 LIMIT 1", [$room]);
if (!$res || pg_num_rows($res) < 1) {
  json_out(['ok'=>false,'error'=>'room_not_found'], 404);
}
$room_id = (int)pg_fetch_result($res, 0, 0);

if ($before_id > 0) {
  $q = pg_query_params(
    $conn,
    "SELECT id, room_id, uid, sender_name, sender_email, sender_photo_url, body, created_at
     FROM ia.chat_messages
     WHERE room_id=$1 AND id < $2
     ORDER BY id DESC
     LIMIT $3",
    [$room_id, $before_id, $limit]
  );
} else {
  $q = pg_query_params(
    $conn,
    "SELECT id, room_id, uid, sender_name, sender_email, sender_photo_url, body, created_at
     FROM ia.chat_messages
     WHERE room_id=$1
     ORDER BY id DESC
     LIMIT $2",
    [$room_id, $limit]
  );
}

$items = [];
if ($q) {
  while ($row = pg_fetch_assoc($q)) {
    $items[] = [
      'id' => (int)$row['id'],
      'room_id' => (int)$row['room_id'],
      'uid' => (string)$row['uid'],
      'name' => (string)($row['sender_name'] ?? ''),
      'email' => (string)($row['sender_email'] ?? ''),
      'photo_url' => (string)($row['sender_photo_url'] ?? ''),
      'body' => (string)$row['body'],
      'created_at' => (string)$row['created_at'],
    ];
  }
}

// está DESC, o front pode inverter
json_out(['ok'=>true,'room'=>$room,'items'=>$items]);
