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

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

$j = read_json();

$room = isset($j['room']) ? trim((string)$j['room']) : 'geral';
$body = isset($j['body']) ? trim((string)$j['body']) : '';
$temp_id = isset($j['temp_id']) ? trim((string)$j['temp_id']) : '';

$uid   = isset($j['uid']) ? trim((string)$j['uid']) : '';
$email = isset($j['email']) ? trim((string)$j['email']) : '';
$name  = isset($j['name']) ? trim((string)$j['name']) : '';
$photo = isset($j['photo_url']) ? trim((string)$j['photo_url']) : '';

if ($body === '') json_out(['ok'=>false,'error'=>'empty_body'], 400);
if ($uid === '')  json_out(['ok'=>false,'error'=>'missing_uid'], 400);

$conn = chat_pg();

$res = pg_query_params($conn, "SELECT id, slug, title 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);
}
$r = pg_fetch_assoc($res);
$room_id = (int)$r['id'];

pg_query_params(
  $conn,
  "INSERT INTO ia.chat_users(uid,email,name,photo_url,last_seen_at)
   VALUES($1,$2,$3,$4,now())
   ON CONFLICT (uid) DO UPDATE SET
     email=EXCLUDED.email,
     name=EXCLUDED.name,
     photo_url=EXCLUDED.photo_url,
     last_seen_at=now()",
  [$uid, $email, $name, $photo]
);

$ins = pg_query_params(
  $conn,
  "INSERT INTO ia.chat_messages(room_id, uid, sender_name, sender_email, sender_photo_url, body)
   VALUES($1,$2,$3,$4,$5,$6)
   RETURNING id, created_at",
  [$room_id, $uid, $name, $email, $photo, $body]
);

if (!$ins) json_out(['ok'=>false,'error'=>'insert_fail'], 500);
$row = pg_fetch_assoc($ins);

json_out([
  'ok' => true,
  'room' => $room,
  'room_id' => $room_id,
  'id' => (int)$row['id'],
  'created_at' => $row['created_at'],
  'temp_id' => $temp_id,
]);
