<?php
/**
 * AJAX Remedy Search for Autocomplete
 * Used when adding remedies to rubrics
 */

require_once '../../config/config.php';
require_once '../../includes/functions.php';

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

if (!isLoggedIn()) {
    echo json_encode([]);
    exit;
}

$query = $_POST['query'] ?? '';

if (strlen($query) < 2) {
    echo json_encode([]);
    exit;
}

$pdo = getDB();
$searchTerm = $query . '%';

$stmt = $pdo->prepare("SELECT id, name, abbreviation 
                      FROM remedies 
                      WHERE name LIKE ? 
                      ORDER BY name 
                      LIMIT 20");
$stmt->execute([$searchTerm]);
$remedies = $stmt->fetchAll();

echo json_encode($remedies);
?>