<?php
/**
 * GET /api/app/members?q=...
 */
require_once __DIR__ . '/../bootstrap.php';
requireApiPermission('members.view');

$q = isset($_GET['q']) ? trim((string) $_GET['q']) : '';
if ($q === '') {
    echo json_encode([]);
    exit;
}

$like = '%' . $q . '%';
$stmt = $pdo->prepare("
    SELECT id, membership_number,
           CONCAT(COALESCE(title,''), ' ', COALESCE(first_name,''), ' ', COALESCE(middle_name,''), ' ', COALESCE(last_name,'')) AS name,
           phone, email
    FROM members
    WHERE first_name LIKE ? OR last_name LIKE ? OR email LIKE ? OR phone LIKE ? OR membership_number LIKE ?
    ORDER BY last_name, first_name
    LIMIT 20
");
$stmt->execute([$like, $like, $like, $like, $like]);
echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
