76 lines
2.3 KiB
PHP
76 lines
2.3 KiB
PHP
<?php
|
|
|
|
/**
|
|
* api_teacher_search_users.php
|
|
* --------------------------------------------------------------------------
|
|
* Ricerca utenti per nome e/o cognome (OR). Solo staff (Admin=1 / teacher=3).
|
|
* Replica searchemail.php della webapp.
|
|
*
|
|
* Posizione: public/api/api_teacher_search_users.php
|
|
* Metodo: GET
|
|
* Auth: Bearer token (Sanctum) via _bootstrap.php
|
|
* Query: ?first=<str>&last=<str> (min 2 caratteri in almeno uno)
|
|
* --------------------------------------------------------------------------
|
|
*/
|
|
|
|
require_once __DIR__ . '/_bootstrap.php';
|
|
|
|
// Gate staff
|
|
$roleId = (int) $user->role_id;
|
|
if (!in_array($roleId, [1, 3], true)) {
|
|
http_response_code(403);
|
|
echo json_encode(['success' => false, 'message' => 'Forbidden']);
|
|
exit;
|
|
}
|
|
|
|
$firstName = trim($_GET['first'] ?? '');
|
|
$lastName = trim($_GET['last'] ?? '');
|
|
|
|
// Serve almeno 2 caratteri in uno dei due campi
|
|
if (mb_strlen($firstName) < 2 && mb_strlen($lastName) < 2) {
|
|
echo json_encode(['success' => true, 'results' => []], JSON_UNESCAPED_UNICODE);
|
|
exit;
|
|
}
|
|
|
|
try {
|
|
$conditions = [];
|
|
$params = [];
|
|
|
|
if (mb_strlen($firstName) >= 2) {
|
|
$conditions[] = "first_name LIKE :fn";
|
|
$params[':fn'] = '%' . $firstName . '%';
|
|
}
|
|
if (mb_strlen($lastName) >= 2) {
|
|
$conditions[] = "last_name LIKE :ln";
|
|
$params[':ln'] = '%' . $lastName . '%';
|
|
}
|
|
|
|
$where = implode(' OR ', $conditions);
|
|
|
|
$sql = "SELECT id, first_name, last_name, email
|
|
FROM auth_users
|
|
WHERE $where
|
|
ORDER BY last_name, first_name
|
|
LIMIT 15";
|
|
|
|
$stmt = $db->prepare($sql);
|
|
$stmt->execute($params);
|
|
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
|
|
|
$results = [];
|
|
foreach ($rows as $r) {
|
|
$results[] = [
|
|
'id' => (int) $r['id'],
|
|
'first_name' => (string) ($r['first_name'] ?? ''),
|
|
'last_name' => (string) ($r['last_name'] ?? ''),
|
|
'email' => (string) ($r['email'] ?? ''),
|
|
];
|
|
}
|
|
|
|
echo json_encode(['success' => true, 'results' => $results], JSON_UNESCAPED_UNICODE);
|
|
} catch (Throwable $ex) {
|
|
error_log('api_teacher_search_users error: ' . $ex->getMessage());
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Errore ricerca']);
|
|
}
|