<?php
requireAdmin();

// ========== 以下是正常页面显示 ==========
$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
");

// 统计数据
$stats = [
    'total' => $db->fetchOne("SELECT COUNT(*) as cnt FROM orders")['cnt'],
    'pending' => $db->fetchOne("SELECT COUNT(*) as cnt FROM orders WHERE status = 'pending'")['cnt'],
    'paid' => $db->fetchOne("SELECT COUNT(*) as cnt FROM orders WHERE status = 'paid'")['cnt'],
    'total_amount' => $db->fetchOne("SELECT COALESCE(SUM(amount), 0) as total FROM orders WHERE status = 'paid'")['total'] ?? 0,
];
?>

<div class="orders-manager">
    <!-- 页面头部 -->
    <div class="page-header">
        <h2>
            <img src="https://api.iconify.design/mdi:package-variant.svg?color=%23667eea" width="26" height="26" style="vertical-align: middle; margin-right: 10px;" alt="">
            订单管理
        </h2>
        <p class="text-muted">管理所有订单，可删除待支付订单</p>
    </div>
    
    <!-- 统计卡片 -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:package-variant.svg?color=%23667eea" width="28" height="28" alt="">
            </div>
            <div class="stat-content">
                <span class="stat-value"><?php echo $stats['total']; ?></span>
                <span class="stat-label">总订单数</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:clock-outline.svg?color=%23f59e0b" width="28" height="28" alt="">
            </div>
            <div class="stat-content">
                <span class="stat-value"><?php echo $stats['pending']; ?></span>
                <span class="stat-label">待支付</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="28" height="28" alt="">
            </div>
            <div class="stat-content">
                <span class="stat-value"><?php echo $stats['paid']; ?></span>
                <span class="stat-label">已支付</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:cash-multiple.svg?color=%238b5cf6" width="28" height="28" alt="">
            </div>
            <div class="stat-content">
                <span class="stat-value">¥<?php echo number_format($stats['total_amount'], 2); ?></span>
                <span class="stat-label">总成交金额</span>
            </div>
        </div>
    </div>
    
    <!-- 筛选栏 -->
    <div class="filter-bar">
        <div class="filter-group">
            <img src="https://api.iconify.design/mdi:filter.svg?color=%236b7280" width="16" height="16" alt="">
            <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>
        </div>
        <div class="filter-group">
            <img src="https://api.iconify.design/mdi:tag.svg?color=%236b7280" width="16" height="16" alt="">
            <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>
        <?php if ($status || $type): ?>
            <a href="?page=orders" class="btn btn-secondary btn-sm">
                <img src="https://api.iconify.design/mdi:close.svg?color=currentColor" width="14" height="14" style="margin-right: 4px;" alt="">
                清空筛选
            </a>
        <?php endif; ?>
    </div>
    
    <!-- 订单列表 -->
    <div class="table-wrapper">
        <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>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($orders)): ?>
                    <tr>
                        <td colspan="9">
                            <div class="empty-state">
                                <img src="https://api.iconify.design/mdi:package-variant-closed.svg?color=%239ca3af" width="48" height="48" alt="">
                                <p>暂无订单</p>
                            </div>
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($orders as $order): ?>
                        <tr id="order-row-<?php echo $order['id']; ?>">
                            <td class="order-no">
                                <img src="https://api.iconify.design/mdi:receipt.svg?color=%236b7280" width="14" height="14" alt="">
                                <code><?php echo htmlspecialchars($order['order_no']); ?></code>
                            </td>
                            <td>
                                <div class="user-info">
                                    <img src="https://api.iconify.design/mdi:account.svg?color=%236b7280" width="14" height="14" alt="">
                                    <?php echo htmlspecialchars($order['username']); ?>
                                </div>
                            </td>
                            <td><?php echo htmlspecialchars($order['item_name'] ?: ($order['type'] == 'recharge' ? '余额充值' : '-')); ?></td>
                            <td><span class="amount">¥<?php echo number_format($order['amount'], 2); ?></span></td>
                            <td>
                                <?php 
                                $type_map = [
                                    'app' => ['icon' => 'application', 'label' => '应用', 'color' => '667eea'],
                                    'group' => ['icon' => 'account-group', 'label' => '会员', 'color' => '8b5cf6'],
                                    'recharge' => ['icon' => 'cash', 'label' => '充值', 'color' => '10b981']
                                ];
                                $t = $type_map[$order['type']] ?? ['icon' => 'circle', 'label' => $order['type'], 'color' => '6b7280'];
                                ?>
                                <span class="type-badge type-<?php echo $order['type']; ?>">
                                    <img src="https://api.iconify.design/mdi:<?php echo $t['icon']; ?>.svg?color=%23<?php echo $t['color']; ?>" width="12" height="12" alt="">
                                    <?php echo $t['label']; ?>
                                </span>
                            </td>
                            <td>
                                <span class="status-badge status-<?php echo $order['status']; ?>">
                                    <span class="status-dot"></span>
                                    <?php echo $order['status'] == 'paid' ? '已支付' : ($order['status'] == 'pending' ? '待支付' : '已取消'); ?>
                                </span>
                            </td>
                            <td><?php echo date('Y-m-d H:i', strtotime($order['created_at'])); ?></td>
                            <td><?php echo $order['paid_at'] ? date('Y-m-d H:i', strtotime($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="删除订单">
                                        <img src="https://api.iconify.design/mdi:delete.svg?color=%23ef4444" width="16" height="16" alt="">
                                    </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 if ($page > 1): ?>
                <a href="?page=orders&p=<?php echo $page - 1; ?>&status=<?php echo $status; ?>&type=<?php echo $type; ?>" class="page-link page-prev">
                    <img src="https://api.iconify.design/mdi:chevron-left.svg?color=currentColor" width="16" height="16" alt="">
                </a>
            <?php endif; ?>
            
            <?php
            $total_pages = ceil($total / $perpage);
            $start_page = max(1, $page - 2);
            $end_page = min($total_pages, $page + 2);
            
            if ($start_page > 1): ?>
                <a href="?page=orders&p=1&status=<?php echo $status; ?>&type=<?php echo $type; ?>" class="page-link">1</a>
                <?php if ($start_page > 2): ?>
                    <span class="page-ellipsis">...</span>
                <?php endif; ?>
            <?php endif; ?>
            
            <?php for ($i = $start_page; $i <= $end_page; $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; ?>
            
            <?php if ($end_page < $total_pages): ?>
                <?php if ($end_page < $total_pages - 1): ?>
                    <span class="page-ellipsis">...</span>
                <?php endif; ?>
                <a href="?page=orders&p=<?php echo $total_pages; ?>&status=<?php echo $status; ?>&type=<?php echo $type; ?>" class="page-link"><?php echo $total_pages; ?></a>
            <?php endif; ?>
            
            <?php if ($page < $total_pages): ?>
                <a href="?page=orders&p=<?php echo $page + 1; ?>&status=<?php echo $status; ?>&type=<?php echo $type; ?>" class="page-link page-next">
                    <img src="https://api.iconify.design/mdi:chevron-right.svg?color=currentColor" width="16" height="16" alt="">
                </a>
            <?php endif; ?>
        </div>
    <?php endif; ?>
</div>

<style>
/* 基础变量 */
:root {
    --primary-color: #667eea;
    --primary-hover: #5a67d8;
    --danger-color: #ef4444;
    --success-color: #10b981;
    --warning-color: #f59e0b;
    --bg-primary: #ffffff;
    --bg-secondary: #f9fafb;
    --text-primary: #1f2937;
    --text-secondary: #6b7280;
    --text-muted: #9ca3af;
    --border-color: #e5e7eb;
    --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
    --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    --radius-sm: 8px;
    --radius-md: 12px;
    --radius-lg: 16px;
}

.orders-manager {
    max-width: 100%;
    padding: 4px;
}

/* 页面头部 */
.page-header {
    margin-bottom: 20px;
}
.page-header h2 {
    display: flex;
    align-items: center;
    font-size: 24px;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0 0 6px;
}
.text-muted {
    color: var(--text-muted);
    font-size: 13px;
}

/* 统计卡片 */
.stats-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
    margin-bottom: 24px;
}
.stat-card {
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    padding: 20px;
    border: 1px solid var(--border-color);
    display: flex;
    align-items: center;
    gap: 16px;
    transition: all 0.2s;
    box-shadow: var(--shadow-sm);
}
.stat-card:hover {
    box-shadow: var(--shadow-md);
    transform: translateY(-2px);
}
.stat-icon {
    width: 52px;
    height: 52px;
    border-radius: var(--radius-md);
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(102, 126, 234, 0.05) 100%);
}
.stat-content {
    display: flex;
    flex-direction: column;
}
.stat-value {
    font-size: 26px;
    font-weight: 700;
    color: var(--text-primary);
    line-height: 1.2;
}
.stat-label {
    font-size: 13px;
    color: var(--text-muted);
    margin-top: 4px;
}

/* 筛选栏 */
.filter-bar {
    display: flex;
    gap: 16px;
    margin-bottom: 24px;
    align-items: center;
    flex-wrap: wrap;
}
.filter-group {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 16px;
    background: var(--bg-primary);
    border: 1px solid var(--border-color);
    border-radius: var(--radius-md);
}
.filter-group select {
    border: none;
    background: transparent;
    font-size: 14px;
    color: var(--text-primary);
    padding: 4px 0;
    cursor: pointer;
}
.filter-group select:focus {
    outline: none;
}

/* 按钮 */
.btn {
    display: inline-flex;
    align-items: center;
    padding: 10px 20px;
    border-radius: var(--radius-md);
    font-size: 14px;
    font-weight: 500;
    text-decoration: none;
    cursor: pointer;
    transition: all 0.2s;
    border: 1px solid transparent;
}
.btn-secondary {
    background: var(--bg-primary);
    color: var(--text-primary);
    border-color: var(--border-color);
}
.btn-secondary:hover {
    background: var(--bg-secondary);
    border-color: var(--text-muted);
}
.btn-sm {
    padding: 8px 16px;
    font-size: 13px;
}

/* 表格 */
.table-wrapper {
    overflow-x: auto;
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    border: 1px solid var(--border-color);
    box-shadow: var(--shadow-sm);
}
.data-table {
    width: 100%;
    border-collapse: collapse;
    min-width: 1100px;
}
.data-table th {
    padding: 16px 16px;
    text-align: left;
    font-weight: 600;
    font-size: 13px;
    color: var(--text-secondary);
    background: var(--bg-secondary);
    border-bottom: 1px solid var(--border-color);
    white-space: nowrap;
    text-transform: uppercase;
    letter-spacing: 0.3px;
}
.data-table td {
    padding: 16px;
    border-bottom: 1px solid var(--border-color);
    font-size: 14px;
    vertical-align: middle;
}
.data-table tbody tr {
    transition: background 0.2s;
}
.data-table tbody tr:hover {
    background: var(--bg-secondary);
}
.data-table tbody tr:last-child td {
    border-bottom: none;
}

/* 单元格样式 */
.order-no {
    display: flex;
    align-items: center;
    gap: 8px;
}
.order-no code {
    font-family: 'Monaco', 'Menlo', 'Courier New', monospace;
    font-size: 13px;
    background: var(--bg-secondary);
    padding: 4px 8px;
    border-radius: var(--radius-sm);
    color: var(--primary-color);
}
.user-info {
    display: flex;
    align-items: center;
    gap: 6px;
}
.amount {
    font-weight: 600;
    color: var(--success-color);
}
.type-badge {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 4px 10px;
    border-radius: 30px;
    font-size: 12px;
    font-weight: 500;
}
.type-app {
    background: #e0e7ff;
    color: #4338ca;
}
.type-group {
    background: #ede9fe;
    color: #6d28d9;
}
.type-recharge {
    background: #d1fae5;
    color: #065f46;
}

/* 状态徽章 */
.status-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 5px 12px;
    border-radius: 30px;
    font-size: 12px;
    font-weight: 500;
    white-space: nowrap;
}
.status-dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
}
.status-paid {
    background: #d1fae5;
    color: #065f46;
}
.status-paid .status-dot {
    background: #10b981;
    box-shadow: 0 0 0 2px rgba(16, 185, 129, 0.2);
}
.status-pending {
    background: #fef3c7;
    color: #92400e;
}
.status-pending .status-dot {
    background: #f59e0b;
    box-shadow: 0 0 0 2px rgba(245, 158, 11, 0.2);
}
.status-cancelled {
    background: #fee2e2;
    color: #991b1b;
}
.status-cancelled .status-dot {
    background: #ef4444;
    box-shadow: 0 0 0 2px rgba(239, 68, 68, 0.2);
}

/* 操作按钮 */
.action-buttons {
    white-space: nowrap;
}
.action-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 34px;
    height: 34px;
    background: var(--bg-secondary);
    border: 1px solid var(--border-color);
    border-radius: var(--radius-sm);
    cursor: pointer;
    transition: all 0.2s;
}
.action-btn:hover {
    background: var(--bg-primary);
    border-color: var(--primary-color);
    transform: translateY(-1px);
    box-shadow: var(--shadow-sm);
}
.delete-btn:hover {
    border-color: var(--danger-color);
    background: #fef2f2;
}
.disabled-action {
    color: var(--text-muted);
    font-size: 12px;
}

/* 空状态 */
.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 20px;
    text-align: center;
}
.empty-state img {
    opacity: 0.4;
    margin-bottom: 16px;
}
.empty-state p {
    color: var(--text-muted);
    font-size: 15px;
    margin: 0;
}

/* 分页 */
.pagination {
    display: flex;
    gap: 6px;
    justify-content: center;
    margin-top: 28px;
}
.page-link {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 38px;
    height: 38px;
    padding: 0 8px;
    border: 1px solid var(--border-color);
    border-radius: var(--radius-sm);
    text-decoration: none;
    color: var(--text-primary);
    font-size: 14px;
    font-weight: 500;
    background: var(--bg-primary);
    transition: all 0.2s;
}
.page-link:hover {
    border-color: var(--primary-color);
    color: var(--primary-color);
    background: rgba(102, 126, 234, 0.05);
}
.page-link.active {
    background: var(--primary-color);
    color: white;
    border-color: var(--primary-color);
}
.page-ellipsis {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 38px;
    height: 38px;
    color: var(--text-muted);
}

/* 加载动画 */
.loading-spinner {
    display: inline-block;
    width: 16px;
    height: 16px;
    border: 2px solid rgba(102, 126, 234, 0.3);
    border-radius: 50%;
    border-top-color: var(--primary-color);
    animation: spin 0.6s linear infinite;
}
@keyframes spin {
    to { transform: rotate(360deg); }
}

/* 响应式 */
@media (max-width: 1024px) {
    .stats-grid {
        grid-template-columns: repeat(2, 1fr);
    }
}
@media (max-width: 768px) {
    .stats-grid {
        grid-template-columns: 1fr;
    }
    .filter-bar {
        flex-direction: column;
        align-items: stretch;
    }
}
</style>

<script>
// 更新统计卡片
function updateStatsDisplay() {
    const statValues = document.querySelectorAll('.stat-card .stat-value');
    const totalStat = statValues[0];  // 总订单数
    const pendingStat = statValues[1]; // 待支付
    const paidStat = statValues[2];    // 已支付
    
    if (totalStat) {
        let totalCount = parseInt(totalStat.innerText) || 0;
        totalStat.innerText = Math.max(0, totalCount - 1);
    }
    if (pendingStat) {
        let pendingCount = parseInt(pendingStat.innerText) || 0;
        pendingStat.innerText = Math.max(0, pendingCount - 1);
    }
    // 已支付数量不变（因为删除的是待支付订单）
}

// 删除订单
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 originalHtml = deleteBtn.innerHTML;
    deleteBtn.innerHTML = '<span class="loading-spinner"></span>';
    deleteBtn.disabled = true;
    
    fetch('/api/admin_delete_order.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'order_id=' + encodeURIComponent(orderId) + '&order_no=' + encodeURIComponent(orderNo)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 更新统计卡片（总数-1，待支付-1）
            updateStatsDisplay();
            
            row.style.transition = 'opacity 0.3s';
            row.style.opacity = '0';
            setTimeout(() => {
                row.remove();
                window.showToast && window.showToast('订单删除成功', 'success');
                if (document.querySelectorAll('#ordersTable tbody tr').length === 0) {
                    location.reload();
                }
            }, 300);
        } else {
            window.showToast && window.showToast(data.message || '删除失败', 'error');
            deleteBtn.innerHTML = originalHtml;
            deleteBtn.disabled = false;
        }
    })
    .catch(error => {
        console.error('错误:', error);
        window.showToast && window.showToast('网络错误', 'error');
        deleteBtn.innerHTML = originalHtml;
        deleteBtn.disabled = false;
    });
}
</script>