<?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"];
$q = trim($_GET["q"] ?? "");
$q = mb_substr($q, 0, 50);

if ($q === "") {
  $stmt = $conn->prepare("SELECT id, username FROM users WHERE id <> ? ORDER BY id DESC");
  $stmt->bind_param("i", $me);
} else {
  $like = "%" . $q . "%";
  $stmt = $conn->prepare("SELECT id, username FROM users WHERE id <> ? AND username LIKE ? ORDER BY id DESC");
  $stmt->bind_param("is", $me, $like);
}

$stmt->execute();
$res = $stmt->get_result();

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

echo json_encode(["ok"=>true,"users"=>$out], JSON_UNESCAPED_UNICODE);
