<?php
// ajax/search_affiliations_rv.php
// Search affiliations table for reviewer affiliation typeahead
require_once __DIR__ . '/../config/db.php';
header('Content-Type: application/json');

$q = trim($_GET['q'] ?? '');
if (strlen($q) < 2) { echo json_encode(['success'=>true,'results'=>[]]); exit; }

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