<?php
/**
 * admin/search-member.php
 * Search members by membership_id, full_name, or phone.
 * Returns JSON array of matching rows.
 */

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

requireLogin();

header('Content-Type: application/json');

$query = trim($_GET['q'] ?? '');

if (strlen($query) < 1) {
    $stmt = $pdo->query("SELECT id, membership_id, full_name, gender, phone, kindred, date_joined FROM members ORDER BY created_at DESC");
    $results = $stmt->fetchAll();
    echo json_encode(['success' => true, 'data' => $results]);
    exit;
}

$search = '%' . $query . '%';
$sql = "SELECT id, membership_id, full_name, gender, phone, kindred, date_joined
        FROM members
        WHERE membership_id LIKE ?
           OR full_name LIKE ?
           OR phone LIKE ?
        ORDER BY created_at DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute([$search, $search, $search]);
$results = $stmt->fetchAll();

echo json_encode(['success' => true, 'data' => $results]);