<?php
include("../db/cn.php");
session_start();

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

// Get the search term
$searchTerm = isset($_POST['term']) ? mysqli_real_escape_string($connection, $_POST['term']) : '';

if (empty($searchTerm)) {
    echo json_encode([]);
    exit;
}

// Query to search products (get distinct product details)
$query = "SELECT DISTINCT 
            product_name, 
            category, 
            company, 
            supplier, 
            product_unit
          FROM products 
          WHERE product_name LIKE '%$searchTerm%' 
             OR product_id LIKE '%$searchTerm%'
          ORDER BY product_name ASC 
          LIMIT 20";

$result = mysqli_query($connection, $query);

$products = [];

if ($result && mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        $products[] = [
            'label' => $row['product_name'] . ' (' . ($row['company'] ?: 'No Company') . ')',
            'value' => $row['product_name'],
            'product_name' => $row['product_name'],
            'category' => $row['category'],
            'company' => $row['company'],
            'supplier' => $row['supplier'],
            'product_unit' => $row['product_unit']
        ];
    }
}

echo json_encode($products);
?>