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

if ($connection->connect_error) {
    die("Connection failed: " . $connection->connect_error);
}

$sql12 = "SELECT DISTINCT category FROM products";
$result12 = $connection->query($sql12);

$categories = [];
if ($result12->num_rows > 0) {
    while ($row12 = $result12->fetch_assoc()) {
        $categories[] = $row12['category'];
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Live Search</title>
    <style>
        #searchResults {
            position: absolute;
            background-color: #f9f9f9;
            border: 1px solid #ddd;
            max-height: 200px;
            overflow-y: auto;
            width: 200px;
            display: none;
        }
        #searchResults div {
            padding: 10px;
            cursor: pointer;
        }
        #searchResults div:hover {
            background-color: #f1f1f1;
        }
    </style>
</head>
<body>

<input type="text" id="searchInput" autocomplete="off">
<div id="searchResults"></div>

<script>
    const categories = <?php echo json_encode($categories); ?>;
    const searchInput = document.getElementById('searchInput');
    const searchResults = document.getElementById('searchResults');

    searchInput.addEventListener('input', function() {
        const query = this.value.trim().toLowerCase();
        if (query === '') {
            searchResults.style.display = 'none';
            return;
        }
        const filteredCategories = categories.filter(category => category.toLowerCase().includes(query));
        renderResults(filteredCategories);
    });

    searchInput.addEventListener('focus', function() {
        const query = this.value.trim().toLowerCase();
        if (query !== '') {
            const filteredCategories = categories.filter(category => category.toLowerCase().includes(query));
            renderResults(filteredCategories);
        }
    });

    searchInput.addEventListener('blur', function() {
        setTimeout(() => {
            searchResults.style.display = 'none';
        }, 200); // Delay hiding dropdown to allow click event on dropdown items
    });

    function renderResults(results) {
        let html = '';
        results.forEach(result => {
            html += `<div>${result}</div>`;
        });
        searchResults.innerHTML = html;
        searchResults.style.display = 'block';
    }

    searchResults.addEventListener('click', function(event) {
        const clickedItem = event.target;
        if (clickedItem.tagName === 'DIV') {
            searchInput.value = clickedItem.innerText;
            searchResults.style.display = 'none';
        }
    });
</script>

</body>
</html>
