<?php
declare(strict_types=1);

/** ========== CORS MUST COME FIRST ========== */
require_once __DIR__ . '/_cors.php';
header('Content-Type: application/json; charset=utf-8');

/** ========== HELPERS ========== */
function respond(int $status, array $payload): void {
  http_response_code($status);
  echo json_encode($payload, JSON_UNESCAPED_SLASHES);
  exit;
}

function pickSessionName(): ?string {
  if (!empty($_COOKIE['PHPSESSADM'])) return 'PHPSESSADM';
  if (!empty($_COOKIE['PHPSESSCLI'])) return 'PHPSESSCLI';
  if (!empty($_COOKIE['PHPSESSAFF'])) return 'PHPSESSAFF';
  return null;
}

/** ========== DB CONNECTION ========== */
$connPath = __DIR__ . '/conn.php';
if (!file_exists($connPath)) {
  respond(500, ['error' => 'conn.php not found']);
}
require_once $connPath; // expects $db (PDO)

/** ========== SESSION ========== */
$sessionName = pickSessionName();
if (!$sessionName) respond(401, ['error' => 'Not authenticated']);
session_name($sessionName);
session_start();

$userId = (int)($_SESSION['user_id'] ?? 0);
if ($userId <= 0) $userId = (int)($_SESSION['SESS_MEMBER_ID'] ?? 0);
if ($userId <= 0) respond(401, ['error' => 'Not authenticated']);

/** ========== INPUT ========== */
$raw = file_get_contents('php://input');
$data = json_decode($raw, true);

$recipientId = (int)($data['recipientId'] ?? 0);

if ($recipientId <= 0 || $recipientId === $userId) {
  respond(400, ['error' => 'recipientId is required']);
}

/** ========== ENSURE RECIPIENT EXISTS ========== */
$checkUser = $db->prepare("SELECT id, name FROM users WHERE id = :id LIMIT 1");
$checkUser->execute([':id' => $recipientId]);
$recipient = $checkUser->fetch(PDO::FETCH_ASSOC);

if (!$recipient) {
  respond(404, ['error' => 'Recipient not found']);
}

/** ========== DETERMINISTIC DM KEY ========== */
/**
 * IMPORTANT:
 * We use underscore format to match auto-heal logic:
 * dm:small_big
 */
$a = min($userId, $recipientId);
$b = max($userId, $recipientId);
$roomKey = "dm:{$a}_{$b}";

try {
  $db->beginTransaction();

  /** ========== FIND EXISTING DM ROOM ========== */
  $find = $db->prepare("
    SELECT id
    FROM pth_party_room
    WHERE room_key = :rk
      AND room_type = 'dm'
    LIMIT 1
  ");
  $find->execute([':rk' => $roomKey]);
  $roomId = (int)($find->fetchColumn() ?: 0);

  /** ========== CREATE ROOM IF NOT EXISTS ========== */
  if ($roomId === 0) {

    $insRoom = $db->prepare("
      INSERT INTO pth_party_room
        (room_key, room_name, room_type, scope_level, created_by, created_at)
      VALUES
        (:rk, :rn, 'dm', 'custom', :cb, NOW())
    ");

    $insRoom->execute([
      ':rk' => $roomKey,
      ':rn' => 'Direct Message',
      ':cb' => $userId,
    ]);

    $roomId = (int)$db->lastInsertId();

    /** ========== INSERT MEMBERS ========== */
    $insMember = $db->prepare("
      INSERT INTO pth_party_room_members
        (room_id, user_id, role, joined_at)
      VALUES
        (:rid, :uid, 'member', NOW())
    ");

    $insMember->execute([':rid' => $roomId, ':uid' => $userId]);
    $insMember->execute([':rid' => $roomId, ':uid' => $recipientId]);
  }

  $db->commit();

  respond(200, [
    'ok' => true,
    'conversation' => [
      'roomId'          => (string)$roomId,
      'participantName' => (string)$recipient['name'],
      'lastMessage'     => '—',
      'updatedAt'       => gmdate('c'),
      'unread'          => false,
      'archived'        => false,
    ],
  ]);

} catch (Throwable $e) {
  if ($db->inTransaction()) $db->rollBack();

  respond(500, [
    'error'   => 'Failed to create conversation',
    'message' => $e->getMessage(), // remove in production
  ]);
}
