<?php
requireAdmin();

// ========== 处理删除订单请求（必须在任何输出之前） ==========
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'delete') {
    header('Content-Type: application/json');
    
    $order_id = intval($_POST['order_id'] ?? 0);
    $order_no = $_POST['order_no'] ?? '';
    
    if ($order_id > 0) {
        $order = $db->fetchOne("SELECT status FROM orders WHERE id = $order_id");
        if ($order && $order['status'] == 'pending') {
            $db->query("DELETE FROM orders WHERE id = $order_id");
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'message' => '只能删除待支付的订单']);
        }
    } elseif (!empty($order_no)) {
        $order = $db->fetchOne("SELECT status FROM orders WHERE order_no = '$order_no'");
        if ($order && $order['status'] == 'pending') {
            $db->query("DELETE FROM orders WHERE order_no = '$order_no'");
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'message' => '只能删除待支付的订单']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => '参数错误']);
    }
    exit;
}

// ========== 以下是正常页面显示 ==========
$page = isset($_GET['p']) ? intval($_GET['p']) : 1;
$status = isset($_GET['status']) ? $_GET['status'] : '';
$type = isset($_GET['type']) ? $_GET['type'] : '';
$perpage = 20;

// 构建查询条件
$where = "1=1";
if ($status) {
    $where .= " AND o.status = '$status'";
}
if ($type) {
    $where .= " AND o.type = '$type'";
}

// 获取总数
$total_result = $db->query("SELECT COUNT(*) as cnt FROM orders o WHERE $where");
$total = $total_result->fetch_assoc()['cnt'];
$offset = ($page - 1) * $perpage;

// 获取订单列表
$orders = $db->fetchAll("
    SELECT o.*, u.username, 
           CASE 
               WHEN o.type = 'app' THEN (SELECT name FROM apps WHERE id = o.item_id)
               WHEN o.type = 'group' THEN (SELECT name FROM user_groups WHERE id = o.item_id)
               ELSE NULL
           END as item_name
    FROM orders o 
    JOIN users u ON o.user_id = u.id 
    WHERE $where 
    ORDER BY o.id DESC 
    LIMIT $offset, $perpage
");
?>

<div class="orders-manager">
    <div class="page-header">
        <h2>订单管理</h2>
        <p class="text-muted">管理所有订单，可删除待支付订单</p>
    </div>
    
    <!-- 筛选栏 -->
    <div class="filter-bar">
        <select id="statusFilter" onchange="location.href='?page=orders&status='+this.value+'&type=<?php echo $type; ?>'">
            <option value="">全部状态</option>
            <option value="pending" <?php echo $status == 'pending' ? 'selected' : ''; ?>>待支付</option>
            <option value="paid" <?php echo $status == 'paid' ? 'selected' : ''; ?>>已支付</option>
            <option value="cancelled" <?php echo $status == 'cancelled' ? 'selected' : ''; ?>>已取消</option>
        </select>
        <select id="typeFilter" onchange="location.href='?page=orders&status=<?php echo $status; ?>&type='+this.value">
            <option value="">全部类型</option>
            <option value="app" <?php echo $type == 'app' ? 'selected' : ''; ?>>应用购买</option>
            <option value="group" <?php echo $type == 'group' ? 'selected' : ''; ?>>会员购买</option>
            <option value="recharge" <?php echo $type == 'recharge' ? 'selected' : ''; ?>>余额充值</option>
        </select>
    </div>
    
    <div class="table-container">
        <table class="data-table" id="ordersTable">
            <thead>
                <tr>
                    <th>订单号</th>
                    <th>用户</th>
                    <th>商品名称</th>
                    <th>金额</th>
                    <th>类型</th>
                    <th>状态</th>
                    <th>创建时间</th>
                    <th>支付时间</th>
                    <th>操作</th>
                </thead>
            <tbody>
                <?php if (empty($orders)): ?>
                    <tr>
                        <td colspan="9" style="text-align: center; padding: 60px;">暂无订单</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($orders as $order): ?>
                        <tr id="order-row-<?php echo $order['id']; ?>">
                            <td><code><?php echo htmlspecialchars($order['order_no']); ?></code></td>
                            <td><?php echo htmlspecialchars($order['username']); ?></td>
                            <td><?php echo htmlspecialchars($order['item_name'] ?: ($order['type'] == 'recharge' ? '余额充值' : '-')); ?></td>
                            <td>¥<?php echo number_format($order['amount'], 2); ?></td>
                            <td>
                                <?php 
                                $type_map = ['app' => '应用', 'group' => '会员', 'recharge' => '充值'];
                                echo $type_map[$order['type']] ?? $order['type'];
                                ?>
                            </td>
                            <td>
                                <span class="status-badge status-<?php echo $order['status']; ?>">
                                    <?php echo $order['status'] == 'paid' ? '已支付' : ($order['status'] == 'pending' ? '待支付' : '已取消'); ?>
                                </span>
                            </td>
                            <td><?php echo $order['created_at']; ?></td>
                            <td><?php echo $order['paid_at'] ?: '-'; ?></td>
                            <td class="action-buttons">
                                <?php if ($order['status'] == 'pending'): ?>
                                    <button class="action-btn delete-btn" onclick="deleteOrder(<?php echo $order['id']; ?>, '<?php echo $order['order_no']; ?>')" title="删除订单">
                                        🗑️ 删除
                                    </button>
                                <?php else: ?>
                                    <span class="disabled-action">-</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <!-- 分页 -->
    <?php if ($total > $perpage): ?>
        <div class="pagination">
            <?php
            $total_pages = ceil($total / $perpage);
            for ($i = 1; $i <= $total_pages; $i++):
            ?>
                <a href="?page=orders&p=<?php echo $i; ?>&status=<?php echo $status; ?>&type=<?php echo $type; ?>" class="page-link <?php echo $i == $page ? 'active' : ''; ?>">
                    <?php echo $i; ?>
                </a>
            <?php endfor; ?>
        </div>
    <?php endif; ?>
</div>

<style>
.filter-bar {
    display: flex;
    gap: 15px;
    margin-bottom: 20px;
}
.filter-bar select {
    padding: 8px 16px;
    border: 1px solid var(--border-color);
    border-radius: var(--radius-sm);
    background: var(--bg-primary);
}
.status-badge {
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 500;
}
.status-paid {
    background: #d1fae5;
    color: #065f46;
}
.status-pending {
    background: #fef3c7;
    color: #92400e;
}
.status-cancelled {
    background: #fee2e2;
    color: #991b1b;
}
.action-buttons {
    white-space: nowrap;
}
.action-btn {
    background: none;
    border: 1px solid var(--border-color);
    padding: 4px 12px;
    border-radius: 6px;
    cursor: pointer;
    font-size: 12px;
    transition: all 0.2s;
    display: inline-flex;
    align-items: center;
    gap: 4px;
}
.action-btn:hover {
    border-color: var(--primary-color);
    background: var(--primary-light);
}
.delete-btn:hover {
    border-color: var(--danger-color);
    color: var(--danger-color);
    background: #fee2e2;
}
.disabled-action {
    color: var(--text-muted);
    font-size: 12px;
}
.pagination {
    display: flex;
    gap: 8px;
    justify-content: center;
    margin-top: 20px;
}
.page-link {
    padding: 6px 12px;
    border: 1px solid var(--border-color);
    border-radius: var(--radius-sm);
    text-decoration: none;
    color: var(--text-primary);
}
.page-link.active {
    background: var(--primary-color);
    color: white;
    border-color: var(--primary-color);
}
.loading-spinner {
    display: inline-block;
    width: 14px;
    height: 14px;
    border: 2px solid #fff;
    border-radius: 50%;
    border-top-color: transparent;
    animation: spin 0.6s linear infinite;
}
@keyframes spin {
    to { transform: rotate(360deg); }
}
</style>

<script>
// 删除订单
function deleteOrder(orderId, orderNo) {
    if (!confirm('确定要删除此订单吗？此操作不可恢复。')) {
        return;
    }
    
    const row = document.getElementById('order-row-' + orderId);
    if (!row) return;
    
    const deleteBtn = row.querySelector('.delete-btn');
    if (!deleteBtn) return;
    
    const originalText = deleteBtn.innerHTML;
    deleteBtn.innerHTML = '<span class="loading-spinner"></span> 删除中...';
    deleteBtn.disabled = true;
    
    fetch(window.location.pathname + '?page=orders&action=delete', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'order_id=' + encodeURIComponent(orderId) + '&order_no=' + encodeURIComponent(orderNo)
    })
    .then(response => {
        // 先获取文本，再尝试解析 JSON
        return response.text().then(text => {
            try {
                return JSON.parse(text);
            } catch(e) {
                console.error('JSON解析失败:', text);
                throw new Error('服务器返回了非JSON格式');
            }
        });
    })
    .then(data => {
        if (data.success) {
            row.remove();
            if (window.showToast) {
                window.showToast('订单删除成功', 'success');
            } else {
                alert('订单删除成功');
            }
            // 如果没有数据了，刷新页面
            if (document.querySelectorAll('#ordersTable tbody tr').length === 0) {
                location.reload();
            }
        } else {
            if (window.showToast) {
                window.showToast(data.message || '删除失败', 'error');
            } else {
                alert(data.message || '删除失败');
            }
            deleteBtn.innerHTML = originalText;
            deleteBtn.disabled = false;
        }
    })
    .catch(error => {
        console.error('错误:', error);
        if (window.showToast) {
            window.showToast('网络错误，但订单可能已删除，请刷新页面查看', 'warning');
        } else {
            alert('网络错误，请刷新页面查看');
        }
        // 刷新页面
        location.reload();
    });
}
</script>