/**
 * Orders Page JavaScript
 * Handles dynamic order loading, search, filtering, and pagination
 */

let currentPage = 1;
let searchTimeout = null;

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

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

    // Status filter
    const statusFilter = document.getElementById('statusFilter');
    if (statusFilter) {
        statusFilter.addEventListener('change', function () {
            currentPage = 1;
            loadOrders();
        });
    }
});

/**
 * Load orders from API
 */
async function loadOrders(page = 1) {
    currentPage = page;

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

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

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

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

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

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

/**
 * Render orders in table
 */
function renderOrders(orders) {
    const tbody = document.getElementById('ordersTableBody');

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

    tbody.innerHTML = orders.map(order => `
        <tr>
            <td><a href="order-details.php?id=${order.id}">${escapeHtml(order.order_number)}</a></td>
            <td>${order.created_at}</td>
            <td>${escapeHtml(order.customer_name)}</td>
            <td>$${order.total_amount}</td>
            <td>
                <span class="badge ${getPaymentStatusClass(order.payment_status)}">
                    <i class="${getPaymentStatusIcon(order.payment_status)} me-1" style="font-size: 6px;"></i> 
                    ${capitalizeFirst(order.payment_status)}
                </span>
            </td>
            <td>
                <span class="badge ${getFulfillmentStatusClass(order.fulfillment_status)}">
                    <i class="${getFulfillmentStatusIcon(order.fulfillment_status)} me-1" style="font-size: 6px;"></i> 
                    ${capitalizeFirst(order.fulfillment_status)}
                </span>
            </td>
            <td>${order.item_count} item${order.item_count !== 1 ? 's' : ''}</td>
            <td>${capitalizeFirst(order.delivery_status)}</td>
            <td>${order.delivery_method}</td>
        </tr>
    `).join('');
}

/**
 * Get payment status badge class
 */
function getPaymentStatusClass(status) {
    switch (status) {
        case 'paid': return 'bg-success-subtle text-success';
        case 'pending': return 'bg-warning-subtle text-warning';
        case 'refunded': return 'bg-danger-subtle text-danger';
        case 'partially_refunded': return 'bg-info-subtle text-info';
        case 'voided': return 'bg-secondary-subtle text-secondary';
        default: return 'bg-secondary-subtle text-secondary';
    }
}

/**
 * Get payment status icon
 */
function getPaymentStatusIcon(status) {
    switch (status) {
        case 'paid': return 'fas fa-check-circle';
        case 'pending': return 'fas fa-clock';
        case 'refunded': return 'fas fa-undo';
        case 'partially_refunded': return 'fas fa-adjust';
        case 'voided': return 'fas fa-ban';
        default: return 'fas fa-circle';
    }
}

/**
 * Get fulfillment status badge class
 */
function getFulfillmentStatusClass(status) {
    switch (status) {
        case 'fulfilled': return 'bg-success-subtle text-success';
        case 'unfulfilled': return 'bg-warning-subtle text-warning';
        case 'partial': return 'bg-info-subtle text-info';
        case 'scheduled': return 'bg-primary-subtle text-primary';
        case 'on_hold': return 'bg-danger-subtle text-danger';
        default: return 'bg-secondary-subtle text-secondary';
    }
}

/**
 * Get fulfillment status icon
 */
function getFulfillmentStatusIcon(status) {
    switch (status) {
        case 'fulfilled': return 'fas fa-check-circle';
        case 'unfulfilled': return 'fas fa-circle';
        case 'partial': return 'fas fa-box-open';
        case 'scheduled': return 'fas fa-calendar-alt';
        case 'on_hold': return 'fas fa-times-circle';
        default: return 'fas fa-circle';
    }
}

/**
 * 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="loadOrders(${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="loadOrders(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="loadOrders(${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="loadOrders(${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="loadOrders(${currentPage + 1}); return false;" aria-label="Next">
                <span aria-hidden="true">&raquo;</span>
            </a>
        </li>
    `;

    paginationList.innerHTML = html;
}

/**
 * Helper function to capitalize first letter
 */
function capitalizeFirst(string) {
    if (!string) return '';
    return string.charAt(0).toUpperCase() + string.slice(1).replace(/_/g, ' ');
}

/**
 * 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>
    `;
}
