<?php
require_once __DIR__ . '/../MPHX/common.php';

$user = check_user();
?>

<link rel="stylesheet" href="/static/css/bootstrap.min.css">
<link rel="stylesheet" href="/static/css/all.min.css">
<link rel="stylesheet" href="css/style.css">

<style>
    /* 确保所有元素始终可见 */
    * {
        opacity: 1 !important;
        visibility: visible !important;
    }
    
    .filter-bar {
        margin-bottom: 20px;
    }
    .filter-bar .row {
        display: flex;
        gap: 12px;
        flex-wrap: wrap;
        align-items: center;
    }
    .filter-bar .form-control {
        flex: 1;
        min-width: 180px;
        opacity: 1 !important;
        visibility: visible !important;
    }
    .filter-bar .btn {
        opacity: 1 !important;
        visibility: visible !important;
    }
    .btn-clear-pending {
        background: #dc3545;
        color: #fff;
        border: none;
        padding: 6px 16px;
        border-radius: 4px;
        font-size: 13px;
        cursor: pointer;
        transition: background 0.2s;
        display: inline-flex;
        align-items: center;
        gap: 6px;
    }
    .btn-clear-pending:hover {
        background: #c82333;
    }
    .btn-clear-pending:disabled {
        background: #6c757d;
        cursor: not-allowed;
    }
    .status-badge {
        display: inline-block;
        padding: 4px 12px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: 600;
        opacity: 1 !important;
        visibility: visible !important;
    }
    .status-badge.pending {
        background: #fce8e6;
        color: #c5221f;
    }
    .status-badge.paid {
        background: #e6f4ea;
        color: #137333;
    }
    .status-badge.failed {
        background: #fce8e6;
        color: #c5221f;
    }
    .status-badge.cancelled {
        background: #f5f7fa;
        color: #5f6368;
    }
    .payment-method-icon {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        opacity: 1 !important;
        visibility: visible !important;
    }
    .payment-method-icon.alipay {
        color: #1677ff;
    }
    .payment-method-icon.wechat {
        color: #07c160;
    }
    .pagination {
        display: flex;
        justify-content: center;
        gap: 8px;
        margin-top: 20px;
    }
    .pagination button {
        padding: 8px 16px;
        border: 1px solid #e8eaed;
        background: #fff;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.2s;
        font-size: 13px;
        opacity: 1 !important;
        visibility: visible !important;
    }
    .pagination button:hover {
        background: #f5f7fa;
    }
    .pagination button.active {
        background: #188038;
        color: #fff;
        border-color: #188038;
    }
    .pagination button:disabled {
        background: #f5f7fa;
        color: #ccc;
        cursor: not-allowed;
    }
    .table, .table th, .table td, .table tr {
        opacity: 1 !important;
        visibility: visible !important;
    }
    .alert {
        padding: 12px 15px;
        border-radius: 4px;
        margin-bottom: 15px;
        font-size: 14px;
    }
    .alert-success {
        background: #d4edda;
        color: #155724;
        border: 1px solid #c3e6cb;
    }
    /* 确认对话框 */
    .modal-confirm {
        display: none;
        position: fixed;
        z-index: 9999;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0,0,0,0.5);
    }
    .modal-confirm-content {
        background-color: #fff;
        margin: 15% auto;
        padding: 0;
        border-radius: 8px;
        width: 90%;
        max-width: 400px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.15);
    }
    .modal-confirm-header {
        padding: 16px 20px;
        border-bottom: 1px solid #e8eaed;
        display: flex;
        align-items: center;
        gap: 10px;
    }
    .modal-confirm-header i {
        color: #dc3545;
        font-size: 20px;
    }
    .modal-confirm-header h4 {
        margin: 0;
        font-size: 16px;
        color: #202124;
    }
    .modal-confirm-body {
        padding: 20px;
        color: #5f6368;
        font-size: 14px;
    }
    .modal-confirm-footer {
        padding: 15px 20px;
        border-top: 1px solid #e8eaed;
        display: flex;
        justify-content: flex-end;
        gap: 10px;
    }
    .modal-confirm-footer .btn {
        padding: 8px 20px;
        border-radius: 4px;
        font-size: 14px;
        cursor: pointer;
        border: none;
    }
    .modal-confirm-footer .btn-cancel {
        background: #f1f3f4;
        color: #5f6368;
    }
    .modal-confirm-footer .btn-cancel:hover {
        background: #e8eaed;
    }
    .modal-confirm-footer .btn-confirm {
        background: #dc3545;
        color: #fff;
    }
    .modal-confirm-footer .btn-confirm:hover {
        background: #c82333;
    }
    @media (max-width: 768px) {
        .filter-bar .row {
            flex-direction: column;
        }
        .filter-bar .form-control {
            min-width: 100%;
        }
    }
</style>

<div class="content-area">
    <div class="page-header">
        <h2><i class="fas fa-list-alt"></i> <?php echo L('title', 'order'); ?></h2>
        <p><?php echo L('order_history', 'menu'); ?></p>
    </div>
    
    <div id="alertContainer"></div>
    
    <div class="card filter-bar">
        <div class="row">
            <select class="form-control" id="statusFilter">
                <option value=""><?php echo L('all', 'common'); ?> <?php echo L('status', 'dashboard'); ?></option>
                <option value="pending"><?php echo L('pending', 'order'); ?></option>
                <option value="paid"><?php echo L('paid', 'order'); ?></option>
                <option value="failed"><?php echo L('error', 'common'); ?></option>
                <option value="cancelled"><?php echo L('cancelled', 'order'); ?></option>
            </select>
            <select class="form-control" id="paymentMethodFilter">
                <option value=""><?php echo L('all', 'common'); ?> <?php echo L('payment_method', 'payment'); ?></option>
                <option value="alipay"><?php echo L('alipay', 'payment'); ?></option>
                <option value="wechat"><?php echo L('wechat', 'payment'); ?></option>
            </select>
            <input type="text" class="form-control" id="orderNoFilter" placeholder="<?php echo L('order_no', 'order'); ?>">
            <button type="button" class="btn btn-primary" data-action="load-orders">
                <i class="fas fa-search"></i> 查询
            </button>
            <button type="button" class="btn btn-secondary" data-action="reset-filters">
                <i class="fas fa-redo"></i> 重置
            </button>
            <button type="button" class="btn-clear-pending" id="btnClearPending" data-action="clear-pending">
                <i class="fas fa-trash-alt"></i> 清空待支付
            </button>
        </div>
    </div>
    
    <div class="card" style="padding: 0; overflow: hidden;">
        <div class="table">
            <table style="width: 100%; margin: 0;">
                <thead>
                    <tr>
                        <th><?php echo L('order_no', 'order'); ?></th>
                        <th>金额</th>
                        <th>支付方式</th>
                        <th>状态</th>
                        <th>创建时间</th>
                        <th>支付时间</th>
                    </tr>
                </thead>
                <tbody id="ordersContent">
                    <tr>
                        <td colspan="6" class="empty-state">
                            <i class="fas fa-spinner fa-spin"></i>
                            <p>加载中...</p>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
    
    <div class="pagination" id="pagination">
    </div>
</div>

<!-- 确认对话框 -->
<div id="confirmModal" class="modal-confirm">
    <div class="modal-confirm-content">
        <div class="modal-confirm-header">
            <i class="fas fa-exclamation-triangle"></i>
            <h4>确认清空</h4>
        </div>
        <div class="modal-confirm-body">
            确定要清空所有待支付订单吗？此操作不可恢复。
        </div>
        <div class="modal-confirm-footer">
            <button type="button" class="btn btn-cancel" onclick="hideConfirmModal()">取消</button>
            <button type="button" class="btn btn-confirm" onclick="confirmClearPending()">确定清空</button>
        </div>
    </div>
</div>

<script src="/static/js/jquery.min.js"></script>
<script>
var currentPage = 1;
var pageSize = 20;
var hasPendingOrders = false;

function showAlert(message, type) {
    var alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    var icon = type === 'success' ? '<i class="fas fa-check-circle"></i> ' : '<i class="fas fa-exclamation-circle"></i> ';
    var alertHtml = '<div class="alert ' + alertClass + '">' + icon + message + '</div>';
    $('#alertContainer').html(alertHtml);
    setTimeout(function() {
        $('#alertContainer').html('');
    }, 3000);
}

function showConfirmModal() {
    document.getElementById('confirmModal').style.display = 'block';
}

function hideConfirmModal() {
    document.getElementById('confirmModal').style.display = 'none';
}

function confirmClearPending() {
    hideConfirmModal();
    clearPendingOrders();
}

function clearPendingOrders() {
    var $btn = $('#btnClearPending');
    $btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 清空中...');
    
    $.ajax({
        type: 'POST',
        url: 'api/api_router.php',
        data: {
            action: 'clearpendingorders'
        },
        dataType: 'json',
        success: function(data) {
            $btn.prop('disabled', false).html('<i class="fas fa-trash-alt"></i> 清空待支付');
            if (data.code === 'success') {
                showAlert('已清空 ' + data.count + ' 条待支付订单', 'success');
                loadOrders();
            } else {
                showAlert(data.msg || '操作失败', 'error');
            }
        },
        error: function(xhr, status, error) {
            $btn.prop('disabled', false).html('<i class="fas fa-trash-alt"></i> 清空待支付');
            console.log('AJAX Error:', status, error);
            showAlert('操作失败，请重试', 'error');
        }
    });
}

function updateClearButtonState() {
    if (hasPendingOrders) {
        $('#btnClearPending').prop('disabled', false);
    } else {
        $('#btnClearPending').prop('disabled', true);
    }
}

function loadOrders(page) {
    if (page) {
        currentPage = page;
    }
    
    var status = $('#statusFilter').val();
    var paymentMethod = $('#paymentMethodFilter').val();
    var orderNo = $('#orderNoFilter').val();
    
    $('#ordersContent').html('<tr><td colspan="6" style="text-align: center; padding: 40px;"><i class="fas fa-spinner fa-spin"></i><p>加载中...</p></td></tr>');
    
    $.ajax({
        type: 'POST',
        url: 'api/api_router.php',
        data: {
            action: 'getorders',
            status: status,
            payment_method: paymentMethod,
            order_no: orderNo,
            page: currentPage,
            page_size: pageSize
        },
        dataType: 'json',
        success: function(data) {
            if (data.code === 'success') {
                renderOrders(data.orders);
                renderPagination(data.total, currentPage, pageSize);
                hasPendingOrders = data.has_pending || false;
                updateClearButtonState();
            } else {
                $('#ordersContent').html('<tr><td colspan="6" style="text-align: center; padding: 40px;"><i class="fas fa-exclamation-circle"></i><p>' + (data.msg || data.code) + '</p></td></tr>');
                $('#pagination').html('');
                hasPendingOrders = false;
                updateClearButtonState();
            }
        },
        error: function(xhr, status, error) {
            console.log('AJAX Error:', status, error);
            console.log('Response:', xhr.responseText);
            $('#ordersContent').html('<tr><td colspan="6" style="text-align: center; padding: 40px;"><i class="fas fa-exclamation-circle"></i><p>加载失败，请重试</p></td></tr>');
            $('#pagination').html('');
            hasPendingOrders = false;
            updateClearButtonState();
        }
    });
}

function renderOrders(orders) {
    if (!orders || orders.length === 0) {
        $('#ordersContent').html('<tr><td colspan="6" style="text-align: center; padding: 60px 20px;"><i class="fas fa-inbox" style="font-size: 48px; color: #dadce0; margin-bottom: 16px; display: block;"></i><h3 style="margin: 0 0 8px 0; color: #202124; font-size: 16px;">暂无订单记录</h3><p style="margin: 0; color: #5f6368; font-size: 13px;">您还没有任何订单记录</p></td></tr>');
        return;
    }
    
    var html = '';
    orders.forEach(function(order) {
        var statusText = '';
        var statusClass = '';
        
        switch(order.status) {
            case 'pending':
                statusText = '待支付';
                statusClass = 'pending';
                break;
            case 'paid':
                statusText = '已支付';
                statusClass = 'paid';
                break;
            case 'failed':
                statusText = '支付失败';
                statusClass = 'failed';
                break;
            case 'cancelled':
                statusText = '已取消';
                statusClass = 'cancelled';
                break;
        }
        
        var paymentMethodHtml = '';
        if (order.payment_method === 'alipay') {
            paymentMethodHtml = '<span class="payment-method-icon alipay"><i class="fab fa-alipay"></i> 支付宝</span>';
        } else if (order.payment_method === 'wechat') {
            paymentMethodHtml = '<span class="payment-method-icon wechat"><i class="fab fa-weixin"></i> 微信支付</span>';
        } else {
            paymentMethodHtml = order.payment_method || '-';
        }
        
        var amount = parseFloat(order.amount);
        if (isNaN(amount)) amount = 0;
        
        html += '<tr>';
        html += '<td>' + (order.order_no || '-') + '</td>';
        html += '<td>¥' + amount.toFixed(2) + '</td>';
        html += '<td>' + paymentMethodHtml + '</td>';
        html += '<td><span class="status-badge ' + statusClass + '">' + statusText + '</span></td>';
        html += '<td>' + (order.create_time || '-') + '</td>';
        html += '<td>' + (order.payment_time || '-') + '</td>';
        html += '</tr>';
    });
    
    $('#ordersContent').html(html);
}

function renderPagination(total, current, size) {
    var totalPages = Math.ceil(total / size);
    
    if (totalPages <= 1) {
        $('#pagination').html('');
        return;
    }
    
    var html = '';
    
    html += '<button class="orders-page" data-page="1" ' + (current === 1 ? 'disabled' : '') + '><i class="fas fa-angle-double-left"></i></button>';
    html += '<button class="orders-page" data-page="' + (current - 1) + '" ' + (current === 1 ? 'disabled' : '') + '><i class="fas fa-angle-left"></i></button>';
    
    for (var i = 1; i <= totalPages; i++) {
        if (i === 1 || i === totalPages || (i >= current - 2 && i <= current + 2)) {
            html += '<button class="orders-page ' + (i === current ? 'active' : '') + '" data-page="' + i + '">' + i + '</button>';
        }
    }
    
    html += '<button class="orders-page" data-page="' + (current + 1) + '" ' + (current === totalPages ? 'disabled' : '') + '><i class="fas fa-angle-right"></i></button>';
    html += '<button class="orders-page" data-page="' + totalPages + '" ' + (current === totalPages ? 'disabled' : '') + '><i class="fas fa-angle-double-right"></i></button>';
    
    $('#pagination').html(html);
}

// 事件委托：订单分页按钮
$(document).on('click', '.orders-page', function() {
    var page = $(this).data('page');
    if (page) loadOrders(parseInt(page));
});

function resetFilters() {
    $('#statusFilter').val('');
    $('#paymentMethodFilter').val('');
    $('#orderNoFilter').val('');
    currentPage = 1;
    loadOrders();
}

$(document).ready(function() {
    loadOrders();
});

$(document).on('click', '[data-action]', function(e){
    var action = $(this).attr('data-action');
    if (!action) return;
    e.preventDefault();
    if (action === 'load-orders') loadOrders();
    if (action === 'reset-filters') resetFilters();
    if (action === 'clear-pending') showConfirmModal();
});

// 点击模态框外部关闭
window.onclick = function(event) {
    var modal = document.getElementById('confirmModal');
    if (event.target == modal) {
        hideConfirmModal();
    }
}
</script>