/**
 * AJAX Search and Pagination Handler
 * Handles live search and pagination for all CRUD tables
 */

class AjaxTableHandler {
    constructor(config) {
        this.searchInput = document.querySelector(config.searchInput);
        this.tableBody = document.querySelector(config.tableBody);
        this.paginationContainer = document.querySelector(config.paginationContainer);
        this.emptyMessage = document.querySelector(config.emptyMessage);
        this.apiEndpoint = config.apiEndpoint;
        this.renderRow = config.renderRow;
        this.currentPage = 1;
        this.searchTimeout = null;
        
        this.init();
    }
    
    init() {
        if (!this.searchInput || !this.tableBody) return;
        
        // Add search input listener with debounce
        this.searchInput.addEventListener('input', (e) => {
            clearTimeout(this.searchTimeout);
            this.searchTimeout = setTimeout(() => {
                this.currentPage = 1;
                this.loadData(e.target.value);
            }, 300); // 300ms debounce
        });
        
        // Load initial data
        this.loadData('');
    }
    
    async loadData(search = '', page = 1) {
        try {
            const url = `${this.apiEndpoint}?search=${encodeURIComponent(search)}&page=${page}`;
            const response = await fetch(url);
            const result = await response.json();
            
            if (result.success) {
                this.renderTable(result.data);
                this.renderPagination(result.pagination, search);
            }
        } catch (error) {
            console.error('Error loading data:', error);
        }
    }
    
    renderTable(data) {
        if (!data || data.length === 0) {
            this.tableBody.innerHTML = '';
            if (this.emptyMessage) {
                this.emptyMessage.style.display = 'block';
            }
            return;
        }
        
        if (this.emptyMessage) {
            this.emptyMessage.style.display = 'none';
        }
        
        this.tableBody.innerHTML = data.map(item => this.renderRow(item)).join('');
        
        // Re-attach delete button listeners
        this.attachDeleteListeners();
    }
    
    renderPagination(pagination, search) {
        if (!this.paginationContainer) return;
        
        if (pagination.total_pages <= 1) {
            this.paginationContainer.innerHTML = '';
            return;
        }
        
        let html = '<nav aria-label="Page navigation"><ul class="pagination justify-content-center">';
        
        // Previous button
        if (pagination.current_page > 1) {
            html += `<li class="page-item">
                <a class="page-link" href="#" data-page="${pagination.current_page - 1}">
                    <i class="bi bi-chevron-left"></i> Previous
                </a>
            </li>`;
        }
        
        // Page numbers
        const startPage = Math.max(1, pagination.current_page - 2);
        const endPage = Math.min(pagination.total_pages, pagination.current_page + 2);
        
        for (let i = startPage; i <= endPage; i++) {
            const active = i === pagination.current_page ? 'active' : '';
            html += `<li class="page-item ${active}">
                <a class="page-link" href="#" data-page="${i}">${i}</a>
            </li>`;
        }
        
        // Next button
        if (pagination.current_page < pagination.total_pages) {
            html += `<li class="page-item">
                <a class="page-link" href="#" data-page="${pagination.current_page + 1}">
                    Next <i class="bi bi-chevron-right"></i>
                </a>
            </li>`;
        }
        
        html += '</ul>';
        html += `<p class="text-center text-muted">
            Page ${pagination.current_page} of ${pagination.total_pages} (${pagination.total_items} total)
        </p></nav>`;
        
        this.paginationContainer.innerHTML = html;
        
        // Attach pagination click listeners
        this.paginationContainer.querySelectorAll('.page-link').forEach(link => {
            link.addEventListener('click', (e) => {
                e.preventDefault();
                const page = parseInt(e.currentTarget.dataset.page);
                this.currentPage = page;
                this.loadData(this.searchInput.value, page);
            });
        });
    }
    
    attachDeleteListeners() {
        document.querySelectorAll('.btn-delete').forEach(btn => {
            btn.addEventListener('click', function(e) {
                e.preventDefault();
                const itemName = this.dataset.name || 'this item';
                
                Swal.fire({
                    title: 'Are you sure?',
                    text: `Do you want to delete ${itemName}?`,
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#d33',
                    cancelButtonColor: '#3085d6',
                    confirmButtonText: 'Yes, delete it!',
                    cancelButtonText: 'Cancel'
                }).then((result) => {
                    if (result.isConfirmed) {
                        window.location.href = this.href;
                    }
                });
            });
        });
    }
}

// Helper functions for rendering rows
const formatDate = (dateString, format = 'd M Y') => {
    if (!dateString) return '';
    const date = new Date(dateString);
    const day = date.getDate();
    const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    const month = months[date.getMonth()];
    const year = date.getFullYear();
    return `${day} ${month} ${year}`;
};

const formatDateTime = (dateString) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    const day = date.getDate();
    const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    const month = months[date.getMonth()];
    const year = date.getFullYear();
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${day} ${month} ${year} ${hours}:${minutes}`;
};

const escapeHtml = (text) => {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
};
