<?php
// chat_api/presence.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';

$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 ($uid === '') json_out(['ok'=>false,'error'=>'missing_uid'], 400);

$conn = chat_pg();

// acha room_id
$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);

// atualiza/garante user no catálogo
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]
);

// marca presença por sala
pg_query_params(
  $conn,
  "INSERT INTO ia.chat_presence(uid, room_id, last_seen_at)
   VALUES($1,$2,now())
   ON CONFLICT (uid, room_id) DO UPDATE SET last_seen_at=now()",
  [$uid, $room_id]
);

json_out(['ok'=>true,'room'=>$room,'room_id'=>$room_id,'ts'=>gmdate('c')]);
