<?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)($_POST["conversation_id"] ?? 0);
$body = trim($_POST["body"] ?? "");

$file_path = trim($_POST["file_path"] ?? "");
$file_name = trim($_POST["file_name"] ?? "");
$mime_type = trim($_POST["mime_type"] ?? "");
$file_size = (int)($_POST["file_size"] ?? 0);

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

// اجازه بده فایل بدون متن هم ارسال بشه
if ($body === "" && $file_path === "") {
  http_response_code(400);
  exit("empty");
}
if (mb_strlen($body) > 800) {
  http_response_code(400);
  exit("too long");
}

// چک عضویت در کانورسیشن
$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");
}

$bodySafe = htmlspecialchars($body, ENT_QUOTES, "UTF-8");

$roomId = 1;
$stmt = $conn->prepare("INSERT INTO messages (room_id, conversation_id, user_id, body) VALUES (?,?,?,?)");
$stmt->bind_param("iiis", $roomId, $cid, $me, $bodySafe);
$stmt->execute();
$msgId = (int)$stmt->insert_id;

if ($file_path !== "") {
  $ins = $conn->prepare("INSERT INTO attachments (message_id, file_path, file_name, mime_type, file_size) VALUES (?,?,?,?,?)");
  $ins->bind_param("isssi", $msgId, $file_path, $file_name, $mime_type, $file_size);
  $ins->execute();
}

echo "ok";
