<?php
require_once("../config/config.php");

$query = trim($_GET['name'] ?? '');

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

$stmt = $conn->prepare("
    SELECT 
        id, 
        name, 
        sku, 
        hsn_sac, 
        category, 
        uom, 
        model_no, 
        description,
        current_stock
    FROM inventory_master 
    WHERE name LIKE ? 
       OR model_no LIKE ? 
       OR sku LIKE ?
    ORDER BY 
        CASE 
            WHEN model_no LIKE ? THEN 1
            WHEN name LIKE ? THEN 2
            ELSE 3
        END,
        name ASC
    LIMIT 12
");

$like = "%" . $query . "%";

$stmt->bind_param("sssss", $like, $like, $like, $like, $like);
$stmt->execute();
$result = $stmt->get_result();

$items = [];
while ($row = $result->fetch_assoc()) {
    $items[] = $row;
}

echo json_encode($items);