<?php
require_once dirname(__DIR__, 2) . '/config.php';

$user_id = $_SESSION['user_id'];
$user = currentUser();

if ($user['is_agent'] != 1) {
    redirect('?page=dashboard');
}

$page = isset($_GET['p']) ? intval($_GET['p']) : 1;
$perpage = 20;

$total_result = $db->query("SELECT COUNT(*) as cnt FROM agent_orders WHERE agent_id = $user_id");
$total = $total_result->fetch_assoc()['cnt'];
$offset = ($page - 1) * $perpage;

$orders = $db->fetchAll("
    SELECT ao.*, a.name as app_name, u.username as customer_name
    FROM agent_orders ao
    JOIN apps a ON ao.app_id = a.id
    JOIN users u ON ao.customer_id = u.id
    WHERE ao.agent_id = $user_id
    ORDER BY ao.id DESC
    LIMIT $offset, $perpage
");
?>

<div class="agent-orders-container">
    <div class="page-header">
        <h2>订单管理</h2>
        <p>查看所有客户订单</p>
    </div>
    
    <div class="table-container">
        <table class="data-table">
            <thead>
                <tr>
                    <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="8" style="text-align: center;">暂无订单</td></tr>
                <?php else: ?>
                    <?php foreach ($orders as $order): ?>
                        <tr>
                            <td><code><?php echo $order['order_no']; ?></code></td>
                            <td><?php echo htmlspecialchars($order['customer_name']); ?></td>
                            <td><?php echo htmlspecialchars($order['app_name']); ?></td>
                            <td>¥<?php echo number_format($order['amount'], 2); ?></td>
                            <td>¥<?php echo number_format($order['agent_commission'], 2); ?></td>
                            <td>
                                <span class="status-badge status-<?php echo $order['status']; ?>">
                                    <?php echo $order['status'] == 'paid' ? '已支付' : '待支付'; ?>
                                </span>
                            </td>
                            <td><?php echo $order['created_at']; ?></td>
                            <td><?php echo $order['paid_at'] ?: '-'; ?></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <?php if ($total > $perpage): ?>
        <div class="pagination">
            <?php for ($i = 1; $i <= ceil($total / $perpage); $i++): ?>
                <a href="?page=agent_orders&p=<?php echo $i; ?>" class="page-link <?php echo $i == $page ? 'active' : ''; ?>"><?php echo $i; ?></a>
            <?php endfor; ?>
        </div>
    <?php endif; ?>
</div>