<?php
/**
 * AJAX endpoint for searching users by name or phone
 */

session_start();
header('Content-Type: application/json');

// Check if admin is logged in
if(!isset($_SESSION['user_id']) || $_SESSION['role'] != 'admin') {
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

require_once '../../db_connect.php';

$query = isset($_GET['q']) ? trim($_GET['q']) : '';

if(strlen($query) < 2) {
    echo json_encode([]);
    exit;
}

$search = mysqli_real_escape_string($conn, $query);

// Search users by name, username, or phone
$sql = "SELECT id, full_name, username, phone, email
        FROM users
        WHERE role IN ('user', 'broker')
        AND status = 'approved'
        AND (
            full_name LIKE '%$search%'
            OR username LIKE '%$search%'
            OR phone LIKE '%$search%'
        )
        ORDER BY full_name ASC
        LIMIT 10";

$result = mysqli_query($conn, $sql);
$users = [];

while($row = mysqli_fetch_assoc($result)) {
    $users[] = [
        'id' => $row['id'],
        'full_name' => $row['full_name'],
        'username' => $row['username'],
        'phone' => $row['phone'],
        'email' => $row['email']
    ];
}

echo json_encode($users);
?>
