document.addEventListener("DOMContentLoaded", function() {
    const searchInput = document.getElementById('searchInput');
    const searchForm = document.getElementById('searchForm');
    const tableContainer = document.getElementById('tableContainer');
    const pagination = document.getElementById('pagination');

    let currentPage = 1;

    function fetchLeads(page = 1, query = '') {
        currentPage = page;
        const xhr = new XMLHttpRequest();
        xhr.open('POST', 'fetch_leads.php', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onload = function() {
            if (xhr.status === 200) {
                const response = JSON.parse(xhr.responseText);
                tableContainer.innerHTML = response.tableData;
                pagination.innerHTML = response.pagination;
            }
        };
        xhr.send('page=' + page + '&query=' + encodeURIComponent(query));
    }

    searchForm.addEventListener('input', function(event) {
        event.preventDefault();
        fetchLeads(1, searchInput.value);
    });

    pagination.addEventListener('click', function(event) {
        if (event.target.tagName === 'A') {
            event.preventDefault();
            const page = event.target.getAttribute('data-page');
            fetchLeads(page, searchInput.value);
        }
    });

    // Initial fetch
    fetchLeads();
});