/**
 * Refunds Page JavaScript
 * Handles dynamic refund loading, search, filtering, and pagination
 */

let currentPage = 1;
let searchTimeout = null;

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

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

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

/**
 * Load refunds from API
 */
async function loadRefunds(page = 1) {
    currentPage = page;

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

    // Get filter values
    const search = document.getElementById('searchRefunds')?.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/refunds.php?${params.toString()}`);
        const data = await response.json();

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

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

/**
 * Render refunds in table
 */
function renderRefunds(refunds) {
    const tbody = document.getElementById('refundsTableBody');

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

    tbody.innerHTML = refunds.map(refund => `
        <tr>
            <td><a href="refund-details.php?id=${refund.id}" class="text-primary fw-semibold">${escapeHtml(refund.refund_number)}</a></td>
            <td><a href="order-details.php?id=${refund.order_id}">#${escapeHtml(refund.order_number)}</a></td>
            <td>${refund.created_at}</td>
            <td>${escapeHtml(refund.customer_name)}</td>
            <td>$${refund.amount}</td>
            <td>
                <span class="badge ${getStatusClass(refund.status)}">
                    ${capitalizeFirst(refund.status)}
                </span>
            </td>
            <td>${escapeHtml(refund.reason)}</td>
        </tr>
    `).join('');
}

/**
 * Get status badge class
 */
function getStatusClass(status) {
    switch (status) {
        case 'approved': return 'bg-success-subtle text-success';
        case 'refunded': return 'bg-success-subtle text-success';
        case 'pending': return 'bg-warning-subtle text-warning';
        case 'declined': return 'bg-danger-subtle text-danger';
        case 'cancelled': return 'bg-secondary-subtle text-secondary';
        default: return 'bg-secondary-subtle text-secondary';
    }
}

/**
 * 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="loadRefunds(${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="loadRefunds(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="loadRefunds(${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="loadRefunds(${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="loadRefunds(${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>
    `;
}
