// addNginxFancyIndexForm.js
// Add a small form to filter and upload files in Nginx FancyIndex page
// © 2017-2023, Modifications for file upload functionality
// Original code by Lilian Besson (Naereen) and contributors,
// open-sourced under the MIT License, https://lbesson.mit-license.org/
// hosted on GitHub, https://GitHub.com/Naereen/Nginx-Fancyindex-Theme

var form = document.createElement('form');
var input = document.createElement('input');
var fileInput = document.createElement('input');
var submitButton = document.createElement('input');

// Search input
input.name = 'filter';
input.id = 'search';
input.placeholder = 'Type to search...';

// File upload input
fileInput.type = 'file';
fileInput.name = 'fileupload';
fileInput.id = 'fileupload';

// Submit button
submitButton.type = 'submit';
submitButton.value = 'Upload';

// Append elements to the form
form.appendChild(input);
form.appendChild(fileInput);
form.appendChild(submitButton);

// Insert the form after the <h1> element
document.querySelector('h1').after(form);

// Filter functionality
var listItems = [].slice.call(document.querySelectorAll('#list tbody tr'));
input.addEventListener('keyup', function () {
    var i,
    e = "(^|.*[^\\pL])" + this.value.trim().split(/\s+/).join("([^\\pL]|[^\\pL].*[^\\pL])") + ".*$",
    n = RegExp(e, "i");
    listItems.forEach(function(item) {
        item.removeAttribute('hidden');
    });
    listItems.filter(function(item) {
        i = item.querySelector('td').textContent.replace(/\s+/g, " ");
        return !n.test(i);
    }).forEach(function(item) {
        item.hidden = true;
    });
});

// Handle file upload submission
form.addEventListener('submit', function(event) {
    event.preventDefault();
    // TODO: Add AJAX request to upload file
    // You need to handle this on the server-side as well
    // Add this inside the form 'submit' event handler
    var formData = new FormData();
    formData.append('fileupload', fileInput.files[0]);

    fetch('/upload', {
        method: 'POST',
        body: formData
    })
    .then(response => response.text())
    .then(data => alert(data))
    .catch(error => console.error('Error:', error));

});
