<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/bootstrap.php';
requireLogin();

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

$typeId = (int)($_GET['type_id'] ?? 0);
$q = trim((string)($_GET['q'] ?? ''));

if ($typeId <= 0) {
    echo json_encode(['ok' => false, 'error' => 'type_id مطلوب'], JSON_UNESCAPED_UNICODE);
    exit;
}

// limit length to avoid abuse
if (mb_strlen($q) > 60) {
    $q = mb_substr($q, 0, 60);
}

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

if ($q !== '') {
    // if query looks numeric => search by file_number too
    $digits = preg_replace('/\D+/', '', $q) ?? '';
    $where .= ' AND (b.full_name LIKE ? OR b.id_number LIKE ? OR b.phone LIKE ?';
    $params[] = '%' . $q . '%';
    $params[] = '%' . $q . '%';
    $params[] = '%' . $q . '%';

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

$st = $pdo->prepare("
    SELECT b.id, b.full_name, b.file_number
    FROM beneficiaries b
    WHERE {$where}
    ORDER BY b.file_number ASC, b.id ASC
    LIMIT 200
");
$st->execute($params);
$data = $st->fetchAll(PDO::FETCH_ASSOC);

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