<?php
// ============================================================
//  ajax/search_affiliations.php
//  Returns matching affiliations from master table
// ============================================================
require_once __DIR__ . '/../config/db.php';
header('Content-Type: application/json');

$q = trim($_GET['q'] ?? '');
if (strlen($q) < 1) jsonResponse(true, '', ['affiliations' => []]);

try {
    $stmt = db()->prepare(
        "SELECT affiliation_id, name, city, state, country, is_institutional_partner
         FROM affiliations
         WHERE name LIKE ? OR city LIKE ? OR country LIKE ?
         ORDER BY is_institutional_partner DESC, name ASC
         LIMIT 10"
    );
    $like = '%' . $q . '%';
    $stmt->execute([$like, $like, $like]);
    $affiliations = $stmt->fetchAll();
    jsonResponse(true, '', ['affiliations' => $affiliations]);
} catch (PDOException $e) {
    jsonResponse(false, 'DB error: ' . $e->getMessage());
}