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

$search = isset($_REQUEST['search']) ? trim($_REQUEST['search']) : '';

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

// LIKE search এর জন্য
$search_param = "{$search}%";

// Exact device_id match এর জন্য
$exact_device = $search;

$sql = "SELECT * FROM users
        WHERE 
            username LIKE ?
            OR email LIKE ?
            OR device_id = ?
        ORDER BY 
            (device_id = ?) DESC,
            (username LIKE ? OR email LIKE ?) DESC,
            username ASC";

$stmt = $conn->prepare($sql);

$stmt->bind_param(
    "ssssss",
    $search_param,
    $search_param,
    $exact_device,
    $exact_device,
    $search_param,
    $search_param
);

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

$data = [];

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

echo json_encode($data, JSON_UNESCAPED_UNICODE);

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