<html>
<head>
    <title>Collection Manager - Search</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>Search Items</h1>

    <nav>
        <a href="index.php">Add Item</a> | <a href="search.php">Search/Overview</a>
    </nav>

    <form id="searchForm">
        <input type="hidden" name="action" value="search_items">
        <div>
            <label for="search_term">Search by Name:</label>
            <input type="text" id="search_term" name="q">
        </div>
        <div>
            <label for="search_category_id">Filter by Category:</label>
            <select id="search_category_id" name="category_id">
                <option value="">-- All Categories --</option>
                {{#categories}}
                    <option value="{{id}}">{{name}}</option>
                {{/categories}}
            </select>
        </div>
        <button type="submit">Search</button>
    </form>

    <h2>Search Results</h2>
    <ul id="searchResultsList">
        {{#items}}
            <li>
                <h3>{{name}}</h3>
                <p>Category: {{category_name}}</p>
                <p>{{description}}</p>
            </li>
        {{/items}}
        {{^items}}
            <li>No items found.</li>
        {{/items}}
    </ul>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const searchForm = document.getElementById('searchForm');
            const searchResultsList = document.getElementById('searchResultsList');
            const searchCategoryIdSelect = document.getElementById('search_category_id');

            // Function to fetch categories (needed for the dropdown)
            function fetchCategories() {
                // Use the same endpoint as index.php to get categories
                fetch('index.php?action=get_categories')
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.categories) {
                        searchCategoryIdSelect.innerHTML = '<option value="">-- All Categories --</option>'; // Reset
                        data.categories.forEach(cat => {
                            const option = document.createElement('option');
                            option.value = cat.id;
                            option.textContent = cat.name;
                            searchCategoryIdSelect.appendChild(option);
                        });
                    }
                })
                .catch(error => console.error('Error fetching categories:', error));
            }

            // Handle search form submission
            searchForm.addEventListener('submit', function(e) {
                e.preventDefault();
                const formData = new FormData(searchForm);
                const params = new URLSearchParams();
                formData.forEach((value, key) => {
                    params.append(key, value);
                });
                params.append('action', 'search_items'); // Ensure action is set

                fetch('index.php?' + params.toString(), {
                    method: 'GET'
                })
                .then(response => response.json())
                .then(data => {
                    displayResults(data.items || []);
                })
                .catch(error => {
                    console.error('Error searching items:', error);
                    searchResultsList.innerHTML = '<li>Error searching items.</li>';
                });
            });

            // Display Search Results
            function displayResults(items) {
                searchResultsList.innerHTML = ''; // Clear previous results
                if (items.length === 0) {
                    searchResultsList.innerHTML = '<li>No items found.</li>';
                    return;
                }
                items.forEach(item => {
                    const li = document.createElement('li');
                    li.innerHTML = `<h3>${item.name}</h3>
                                  <p>Category: ${item.category_name || 'Uncategorized'}</p>
                                  <p>${item.description || 'No description available.'}</p>`;
                    searchResultsList.appendChild(li);
                });
            }

            // Initial fetch of categories for the dropdown
            fetchCategories();
        });
    </script>
</body>
</html>
