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

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

    <form action="index.php" method="post">
        <input type="hidden" name="action" value="add_item">
        <div>
            <label for="item_name">Item Name:</label>
            <input type="text" id="item_name" name="item_name" required>
        </div>
        <div>
            <label for="item_description">Description:</label>
            <textarea id="item_description" name="item_description" rows="3"></textarea>
        </div>
        <div>
            <label for="category_id">Category:</label>
            <select id="category_id" name="category_id" required>
                <option value="">-- Select Category --</option>
                {{#categories}}
                    <option value="{{id}}">{{name}}</option>
                {{/categories}}
            </select>
            <button type="button" id="showAddCategoryFormBtn">+</button>
        </div>
        <div id="addCategoryForm" style="display: none;">
            <label for="new_category_name">New Category:</label>
            <input type="text" id="new_category_name" name="new_category_name">
            <button type="button" id="addCategoryBtn">Add Category</button>
        </div>
        <button type="submit">Add Item</button>
    </form>

    <h2>Existing Items</h2>
    <ul>
        {{#items}}
            <li>
                <h3>{{name}}</h3>
                <p>Category: {{category_name}}</p>
                <p>{{description}}</p>
            </li>
        {{/items}}
        {{^items}}
            <li>No items yet.</li>
        {{/items}}
    </ul>

    <h2>Categories</h2>
    <ul>
        {{#categories}}
            <li>{{name}}</li>
        {{/categories}}
    </ul>
    <div class="add-category-section">
        <label for="new_category_name_direct">New Category:</label>
        <input type="text" id="new_category_name_direct" name="new_category_name_direct">
        <button id="addCategoryDirectBtn">Add Category</button>
    </div>

    <script>
        // JavaScript for dynamic category adding and potentially drag/drop later
        document.addEventListener('DOMContentLoaded', function() {
            const showAddCategoryFormBtn = document.getElementById('showAddCategoryFormBtn');
            const addCategoryForm = document.getElementById('addCategoryForm');
            const newCategoryNameInput = document.getElementById('new_category_name');
            const addCategoryBtn = document.getElementById('addCategoryBtn');
            const newCategoryNameDirectInput = document.getElementById('new_category_name_direct');
            const addCategoryDirectBtn = document.getElementById('addCategoryDirectBtn');

            showAddCategoryFormBtn.addEventListener('click', function() { addCategoryForm.style.display = addCategoryForm.style.display === 'none' ? 'block' : 'none'; });

            function addCategory(name, isDirect) {
                const formData = new FormData();
                formData.append('action', 'add_category');
                formData.append('category_name', name);

                fetch(window.location.href, {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    alert(data.message);
                    if (data.success) {
                        if (isDirect) {
                            newCategoryNameDirectInput.value = '';
                        } else {
                            newCategoryNameInput.value = '';
                            addCategoryForm.style.display = 'none';
                        }
                        // Refresh categories
                        fetchCategories();
                    }
                })
                .catch(error => console.error('Error:', error));
            }

            addCategoryBtn.addEventListener('click', () => addCategory(newCategoryNameInput.value, false));
            addCategoryDirectBtn.addEventListener('click', () => addCategory(newCategoryNameDirectInput.value, true));

            // Function to fetch and update categories in UI
            function fetchCategories() {
                fetch(window.location.href + '?action=get_categories')
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.categories) {
                        const categorySelect = document.getElementById('category_id');
                        const searchCategorySelect = document.getElementById('search_category_id'); // Assuming this exists on search page
                        const categoryListUl = document.querySelector('.category-management ul'); // Assuming this exists on index page

                        // Clear existing options/list items
                        categorySelect.innerHTML = '<option value="">-- Select Category --</option>';
                        if (searchCategorySelect) searchCategorySelect.innerHTML = '<option value="">-- All Categories --</option>';
                        if (categoryListUl) categoryListUl.innerHTML = '';

                        data.categories.forEach(cat => {
                            const opt1 = document.createElement('option');
                            opt1.value = cat.id;
                            opt1.textContent = cat.name;
                            categorySelect.appendChild(opt1);

                            if (searchCategorySelect) {
                                const opt2 = document.createElement('option');
                                opt2.value = cat.id;
                                opt2.textContent = cat.name;
                                searchCategorySelect.appendChild(opt2);
                            }

                            if (categoryListUl) {
                                const li = document.createElement('li');
                                li.textContent = cat.name;
                                categoryListUl.appendChild(li);
                            }
                        });
                    }
                })
                .catch(error => console.error('Error fetching categories:', error));
            }
            
            // Initial fetch
            fetchCategories();
        });
    </script>
</body>
</html>
