<?php

declare(strict_types=1);

require dirname(__DIR__) . '/app/bootstrap.php';
require_login();
require_once DENTAL_ROOT . '/app/medicine_catalog.php';

header('Content-Type: application/json; charset=utf-8');
if (!has_role(['super_admin','clinic_admin','dentist'])) {
    http_response_code(403);
    echo json_encode(['items'=>[],'error'=>'Access denied.']);
    exit;
}
if (!medicine_catalog_schema_ready()) {
    echo json_encode(['items'=>[],'update_required'=>true]);
    exit;
}
$q = trim((string)($_GET['q'] ?? ''));
if (mb_strlen($q) < 2) {
    echo json_encode(['items'=>[]]);
    exit;
}
$like = '%' . $q . '%';
$stmt = db()->prepare(
    'SELECT id,display_name,generic_name,brand_name,form,strength,route,notes '
    . 'FROM `' . table('medicine_catalog') . '` '
    . 'WHERE is_active=1 AND (display_name LIKE ? OR generic_name LIKE ? OR brand_name LIKE ? OR strength LIKE ?) '
    . 'ORDER BY CASE WHEN display_name LIKE ? THEN 0 WHEN generic_name LIKE ? THEN 1 ELSE 2 END,display_name LIMIT 20'
);
$stmt->execute([$like,$like,$like,$like,$q.'%',$q.'%']);
echo json_encode(['items'=>$stmt->fetchAll() ?: []], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
