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

header("Content-Type: application/json; charset=utf-8");

if (!isset($_SESSION["user_id"])) {
  http_response_code(401);
  echo json_encode(["ok"=>false,"error"=>"login required"], JSON_UNESCAPED_UNICODE);
  exit;
}

$me = (int)$_SESSION["user_id"];
$other = (int)($_POST["user_id"] ?? 0);

if ($other <= 0 || $other === $me) {
  http_response_code(400);
  echo json_encode(["ok"=>false,"error"=>"bad user"], JSON_UNESCAPED_UNICODE);
  exit;
}

// پیدا کردن dm موجود
$stmt = $conn->prepare("
  SELECT c.id
  FROM conversations c
  JOIN conversation_participants p1 ON p1.conversation_id = c.id AND p1.user_id = ?
  JOIN conversation_participants p2 ON p2.conversation_id = c.id AND p2.user_id = ?
  WHERE c.type='dm'
  LIMIT 1
");
$stmt->bind_param("ii", $me, $other);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();

if ($row) {
  echo json_encode(["ok"=>true,"conversation_id" => (int)$row["id"]], JSON_UNESCAPED_UNICODE);
  exit;
}

// ساخت dm جدید
$ins = $conn->prepare("INSERT INTO conversations (type) VALUES ('dm')");
$ins->execute();
$cid = (int)$ins->insert_id;

$p = $conn->prepare("INSERT INTO conversation_participants (conversation_id, user_id) VALUES (?,?), (?,?)");
$p->bind_param("iiii", $cid, $me, $cid, $other);
$p->execute();

echo json_encode(["ok"=>true,"conversation_id"=>$cid], JSON_UNESCAPED_UNICODE);
