<?php
session_start();
include '../layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    echo json_encode([]);
    exit();
}

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

$like   = '%' . $conn->real_escape_string($q) . '%';

// Return inventory_id aliased as item_id so the JS cart works
// without changes — the frontend uses item_id as the cart key
$result = $conn->query("
    SELECT
        inventory_id        AS item_id,
        item_name,
        generic_name,
        strength,
        unit_of_measure,
        dosage_form         AS category,
        current_stock       AS quantity_in_stock
    FROM pharmacy_inventory
    WHERE (item_name    LIKE '$like'
        OR generic_name LIKE '$like'
        OR brand_name   LIKE '$like')
      AND is_active      = 1
      AND current_stock  > 0
    ORDER BY item_name
    LIMIT 12
");

echo json_encode($result ? $result->fetch_all(MYSQLI_ASSOC) : []);