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

$products = [];
$query = '';

if (isset($_GET['product_input'])) {
    $query = trim($_GET['product_input']);
    if ($query !== '') {
        $query = mysqli_real_escape_string($connection, $query);
        $sql = "SELECT product_id, product_name FROM products WHERE product_id LIKE '%$query%' OR product_name LIKE '%$query%' LIMIT 10";
        $result = mysqli_query($connection, $sql);
        while ($row = mysqli_fetch_assoc($result)) {
            $products[] = $row;
        }
    }
    header('Content-Type: application/json');
    echo json_encode($products);
    exit;
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Product Search</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <style>
        #suggestions {
            max-height: 200px;
            overflow-y: auto;
        }
    </style>
</head>
<body class="p-4">
<div class="position-relative">
    <input type="text" id="productInput" class="form-control form-control-sm" placeholder="Enter product ID" autocomplete="off" />
    <div id="suggestions" class="dropdown-menu w-100 mt-0" style="display: none; position: absolute;"></div>
</div>

<script>
const input = document.getElementById('productInput');
const suggestions = document.getElementById('suggestions');

input.addEventListener('keyup', () => {
    const query = input.value.trim();
    if (!query) {
        suggestions.innerHTML = '';
        suggestions.style.display = 'none';
        return;
    }
    fetch(`?product_input=${encodeURIComponent(query)}`)
        .then(res => res.json())
        .then(products => {
            suggestions.innerHTML = '';
            if (products.length > 0) {
                products.forEach(p => {
                    const div = document.createElement('div');
                    div.className = 'dropdown-item';
                    div.textContent = `${p.product_id} - ${p.product_name}`;
                    suggestions.appendChild(div);
                });
                suggestions.style.display = 'block';
            } else {
                suggestions.style.display = 'none';
            }
        });
});
</script>
</body>
</html>
