<?php
session_start();

require_once __DIR__ . '/../../includes/helpers.php';

header('Content-Type: application/json; charset=utf-8');

if (!isset($_SESSION['authenticated'])) {
    echo json_encode(['success' => false, 'users' => []], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$userId = current_user_id();
if ($userId <= 0) {
    echo json_encode(['success' => false, 'users' => []], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$query = trim((string) ($_GET['q'] ?? ''));
$search = '%' . $query . '%';

$sql = 'SELECT id, business_name, email
        FROM users
        WHERE COALESCE(NULLIF(TRIM(email), ""), "") <> ""';
$types = '';
$params = [];

if ($query !== '') {
    $sql .= ' AND (
        business_name LIKE ?
        OR email LIKE ?
    )';
    $types = 'ss';
    $params = [$search, $search];
}

$sql .= ' ORDER BY id DESC LIMIT 25';

$rows = fetch_all($sql, $types, $params);
$users = [];

foreach ($rows as $row) {
    $name = trim((string) ($row['business_name'] ?? ''));
    $email = trim((string) ($row['email'] ?? ''));

    $users[] = [
        'id' => (int) ($row['id'] ?? 0),
        'email' => $email,
        'business_name' => $name,
        'display_name' => $name !== '' ? $name : $email,
        'avatar_url' => asset_url('images/img1.jpg'),
        'search' => strtolower(trim($name . ' ' . $email)),
    ];
}

echo json_encode([
    'success' => true,
    'users' => $users,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
