// Filter and sorting functionality for admin table

let filterTimeout;

// Auto-submit form when filter values change (with debounce)
function setupAutoFilter() {
    const filterInputs = document.querySelectorAll('#filterForm input[type="text"], #filterForm input[type="date"], #filterForm select');
    filterInputs.forEach(input => {
        input.addEventListener('input', function() {
            clearTimeout(filterTimeout);
            filterTimeout = setTimeout(() => {
                document.getElementById('pageInput').value = 1; // Reset to first page
                document.getElementById('filterForm').submit();
            }, 500); // 500ms delay
        });
    });
}

// Sort table by column
function sortTable(column) {
    var form = document.getElementById('filterForm');
    var sortColInput = form.querySelector('input[name="sortColumn"]');
    var sortDirInput = form.querySelector('input[name="sortDirection"]');
    var currentCol = sortColInput.value;
    var currentDir = sortDirInput.value;
    
    if (currentCol === column) {
        sortDirInput.value = currentDir === 'asc' ? 'desc' : 'asc';
    } else {
        sortColInput.value = column;
        sortDirInput.value = 'asc';
    }
    
    form.submit();
    return false;
}

// Navigate to specific page
function goToPage(page) {
    document.getElementById('pageInput').value = page;
    document.getElementById('filterForm').submit();
    return false;
}
