/**
 * Customers Page JavaScript
 * Handles dynamic customer loading, search, and pagination
 */

let currentPage = 1;
let searchTimeout = null;

// Load customers on page load
document.addEventListener('DOMContentLoaded', function () {
    loadCustomers();

    // Search functionality
    const searchInput = document.getElementById('searchCustomers');
    if (searchInput) {
        searchInput.addEventListener('input', function () {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                currentPage = 1;
                loadCustomers();
            }, 500);
        });
    }
});

/**
 * Load customers from API
 */
async function loadCustomers(page = 1) {
    currentPage = page;

    // Show loading state
    document.getElementById('loadingState').style.display = 'block';
    document.getElementById('customersTableContainer').style.display = 'none';
    document.getElementById('paginationContainer').style.display = 'none';

    // Get filter values
    const search = document.getElementById('searchCustomers')?.value || '';

    // Build query string
    const params = new URLSearchParams({
        page: currentPage,
        limit: 10,
        search: search
    });

    try {
        const response = await fetch(`api/customers.php?${params.toString()}`);
        const data = await response.json();

        if (data.success) {
            renderCustomers(data.data);
            renderPagination(data.pagination);

            // Hide loading, show table
            document.getElementById('loadingState').style.display = 'none';
            document.getElementById('customersTableContainer').style.display = 'block';
            document.getElementById('paginationContainer').style.display = 'block';
        } else {
            showError(data.message || 'Failed to load customers');
        }
    } catch (error) {
        console.error('Error loading customers:', error);
        showError('An error occurred while loading customers');
    }
}

/**
 * Render customers in table
 */
function renderCustomers(customers) {
    const tbody = document.getElementById('customersTableBody');

    if (customers.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="6" class="text-center py-5">
                    <i class="las la-users fs-1 text-muted"></i>
                    <p class="text-muted mt-2">No customers found</p>
                </td>
            </tr>
        `;
        return;
    }

    tbody.innerHTML = customers.map((customer, index) => `
        <tr>
            <td style="width: 16px;">
                <div class="form-check">
                    <input type="checkbox" class="form-check-input" name="check" id="customCheck${index}">
                </div>
            </td>
            <td class="ps-0">
                <img src="${customer.avatar}" alt="" class="thumb-md d-inline rounded-circle me-1">
                <p class="d-inline-block align-middle mb-0">
                    <span class="font-13 fw-medium">${escapeHtml(customer.name)}</span>
                </p>
            </td>
            <td>${escapeHtml(customer.email)}</td>
            <td>${escapeHtml(customer.country)}</td>
            <td>${customer.orders}</td>
            <td>$${customer.spent}</td>
        </tr>
    `).join('');
}

/**
 * Render pagination
 */
function renderPagination(pagination) {
    const paginationList = document.getElementById('paginationList');

    if (pagination.total_pages <= 1) {
        paginationList.innerHTML = '';
        return;
    }

    let html = '';

    // Previous button
    html += `
        <li class="page-item ${!pagination.has_prev ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="loadCustomers(${currentPage - 1}); return false;" aria-label="Previous">
                <span aria-hidden="true">&laquo;</span>
            </a>
        </li>
    `;

    // Page numbers
    const startPage = Math.max(1, currentPage - 2);
    const endPage = Math.min(pagination.total_pages, currentPage + 2);

    if (startPage > 1) {
        html += `<li class="page-item"><a class="page-link" href="#" onclick="loadCustomers(1); return false;">1</a></li>`;
        if (startPage > 2) {
            html += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
        }
    }

    for (let i = startPage; i <= endPage; i++) {
        html += `
            <li class="page-item ${i === currentPage ? 'active' : ''}">
                <a class="page-link" href="#" onclick="loadCustomers(${i}); return false;">${i}</a>
            </li>
        `;
    }

    if (endPage < pagination.total_pages) {
        if (endPage < pagination.total_pages - 1) {
            html += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
        }
        html += `<li class="page-item"><a class="page-link" href="#" onclick="loadCustomers(${pagination.total_pages}); return false;">${pagination.total_pages}</a></li>`;
    }

    // Next button
    html += `
        <li class="page-item ${!pagination.has_next ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="loadCustomers(${currentPage + 1}); return false;" aria-label="Next">
                <span aria-hidden="true">&raquo;</span>
            </a>
        </li>
    `;

    paginationList.innerHTML = html;
}

/**
 * Escape HTML
 */
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

/**
 * Show error message
 */
function showError(message) {
    document.getElementById('loadingState').innerHTML = `
        <div class="alert alert-danger" role="alert">
            <i class="las la-exclamation-triangle me-2"></i>${message}
        </div>
    `;
}
