<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap_public.php';

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

$q = trim((string)($_GET['q'] ?? ''));
if (mb_strlen($q) > 60) $q = mb_substr($q, 0, 60);

$typeId = 2; // orphans

$params = [$typeId];
$where = 'beneficiary_type_id = ?';

if ($q !== '') {
    $digits = preg_replace('/\D+/', '', $q) ?? '';
    $where .= ' AND (full_name LIKE ? OR phone LIKE ? OR id_number LIKE ?';
    $params[] = '%' . $q . '%';
    $params[] = '%' . $q . '%';
    $params[] = '%' . $q . '%';

    if ($digits !== '') {
        $where .= ' OR file_number = ?';
        $params[] = (int)$digits;
    }
    $where .= ')';
}

$pdo = getPDO();
$st = $pdo->prepare("
    SELECT id, full_name, file_number
    FROM beneficiaries
    WHERE {$where}
    ORDER BY file_number ASC, id ASC
    LIMIT 50
");
$st->execute($params);

echo json_encode(['ok' => true, 'data' => $st->fetchAll()], JSON_UNESCAPED_UNICODE);