<?php
header('Content-Type: application/json');
include 'config.php';

$search = isset($_REQUEST['search']) ? trim($_REQUEST['search']) : '';
$page = isset($_REQUEST['page']) ? (int)$_REQUEST['page'] : 1;
$per_page = isset($_REQUEST['per_page']) ? (int)$_REQUEST['per_page'] : 10;

if ($page < 1) $page = 1;
if ($per_page < 1) $per_page = 10;

$offset = ($page - 1) * $per_page;

if ($search === '') {
    echo json_encode([]);
    exit;
}

$data = [];

// Exact Match Check
$exact_stmt = $conn->prepare(
    "SELECT uid, username
     FROM users
     WHERE username = ?
     LIMIT 1"
);

$exact_stmt->bind_param("s", $search);
$exact_stmt->execute();
$exact_result = $exact_stmt->get_result();

if ($exact_result->num_rows > 0) {

    $data[] = $exact_result->fetch_assoc();

} else {

    $search_param = $search . "%";

    $stmt = $conn->prepare(
        "SELECT uid, username
         FROM users
         WHERE username LIKE ?
         ORDER BY username ASC
         LIMIT ? OFFSET ?"
    );

    $stmt->bind_param(
        "sii",
        $search_param,
        $per_page,
        $offset
    );

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

    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }

    $stmt->close();
}

echo json_encode([
    "page" => $page,
    "per_page" => $per_page,
    "data" => $data
], JSON_UNESCAPED_UNICODE);

$exact_stmt->close();
$conn->close();
?>