<?php
session_start();
require __DIR__ . "/../db.php";

if (!isset($_SESSION["user_id"])) {
  http_response_code(401);
  exit("login required");
}

$me = (int)$_SESSION["user_id"];
$cid = (int)($_GET["conversation_id"] ?? 0);
$after = (int)($_GET["after"] ?? 0);

if ($cid <= 0) {
  http_response_code(400);
  exit("bad conversation");
}

// چک عضویت
$chk = $conn->prepare("SELECT 1 FROM conversation_participants WHERE conversation_id=? AND user_id=? LIMIT 1");
$chk->bind_param("ii", $cid, $me);
$chk->execute();
if (!$chk->get_result()->fetch_row()) {
  http_response_code(403);
  exit("not allowed");
}

$stmt = $conn->prepare("
  SELECT m.id, m.body, m.created_at, u.id AS user_id, u.username
  FROM messages m
  JOIN users u ON u.id = m.user_id
  WHERE m.conversation_id=? AND m.id > ?
  ORDER BY m.id ASC
  LIMIT 100
");
$stmt->bind_param("ii", $cid, $after);
$stmt->execute();
$res = $stmt->get_result();

$out = [];
while ($r = $res->fetch_assoc()) {
  $r["attachments"] = [];

  $a = $conn->prepare("SELECT file_path, file_name, mime_type, file_size FROM attachments WHERE message_id=?");
  $mid = (int)$r["id"];
  $a->bind_param("i", $mid);
  $a->execute();
  $ar = $a->get_result();
  while ($att = $ar->fetch_assoc()) $r["attachments"][] = $att;

  $out[] = $r;
}

header("Content-Type: application/json; charset=utf-8");
echo json_encode($out, JSON_UNESCAPED_UNICODE);
