<?php
include "db.php";

$q = isset($_GET['q']) ? $_GET['q'] : '';

// Prepare query to search product name
$sql = "SELECT product_id, product_name, price_per_piece FROM products WHERE product_name LIKE ? ORDER BY product_name ASC";
$stmt = $conn->prepare($sql);
$search = "%$q%";
$stmt->bind_param("s", $search);
$stmt->execute();
$result = $stmt->get_result();

$products = [];
while($row = $result->fetch_assoc()){
    $products[] = [
        'id' => $row['product_id'],
        'name' => $row['product_name'],
        'price' => $row['price_per_piece']
    ];
}

header('Content-Type: application/json');
echo json_encode($products);