56 lines
1.8 KiB
PHP
56 lines
1.8 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
require_once __DIR__ . '/common.php';
|
|
|
|
api_require_method('GET');
|
|
$staff = api_require_staff();
|
|
$pdo = get_db();
|
|
|
|
$search = trim($_GET['q'] ?? '');
|
|
$like = '%' . $search . '%';
|
|
|
|
$regSql = "SELECT u.id, u.name, u.email, o.name AS organization_name,
|
|
(SELECT COUNT(*) FROM tickets t WHERE t.user_id = u.id) AS ticket_count
|
|
FROM users u LEFT JOIN organizations o ON o.id = u.organization_id";
|
|
$regParams = [];
|
|
if ($search !== '') {
|
|
$regSql .= ' WHERE u.name LIKE ? OR u.email LIKE ?';
|
|
$regParams = [$like, $like];
|
|
}
|
|
$regSql .= ' ORDER BY u.name LIMIT 100';
|
|
$regStmt = $pdo->prepare($regSql);
|
|
$regStmt->execute($regParams);
|
|
$registered = array_map(fn(array $row) => [
|
|
'id' => (int) $row['id'],
|
|
'name' => $row['name'],
|
|
'email' => $row['email'],
|
|
'organizationName' => $row['organization_name'],
|
|
'ticketCount' => (int) $row['ticket_count'],
|
|
'isGuest' => false,
|
|
], $regStmt->fetchAll());
|
|
|
|
$guestSql = "SELECT requester_email AS email, MAX(requester_name) AS name, COUNT(*) AS ticket_count
|
|
FROM tickets WHERE user_id IS NULL";
|
|
$guestParams = [];
|
|
if ($search !== '') {
|
|
$guestSql .= ' AND (requester_name LIKE ? OR requester_email LIKE ?)';
|
|
$guestParams = [$like, $like];
|
|
}
|
|
$guestSql .= ' GROUP BY requester_email ORDER BY requester_email LIMIT 100';
|
|
$guestStmt = $pdo->prepare($guestSql);
|
|
$guestStmt->execute($guestParams);
|
|
$guests = array_map(fn(array $row) => [
|
|
'id' => null,
|
|
'name' => $row['name'],
|
|
'email' => $row['email'],
|
|
'organizationName' => null,
|
|
'ticketCount' => (int) $row['ticket_count'],
|
|
'isGuest' => true,
|
|
], $guestStmt->fetchAll());
|
|
|
|
$customers = array_merge($registered, $guests);
|
|
usort($customers, fn($a, $b) => strcasecmp($a['name'] ?? '', $b['name'] ?? ''));
|
|
$customers = array_slice($customers, 0, 100);
|
|
|
|
api_json(['items' => $customers]);
|