<?php
require_once __DIR__ . '/layout.php';
$db = db();

if (!hasPermission('view_orders')) {
    echo "权限不足";
    exit;
}

$title = '币币交易管理';
ob_start();
$user_id = isset($_GET['user_id']) ? (int)$_GET['user_id'] : null;

$sql = "SELECT o.*, u.username, u.uid FROM spot_orders o JOIN users u ON o.user_id = u.id";
$params = [];
if ($admin['is_agent']) {
    $sql .= " WHERE u.agent_id = ?";
    $params[] = $admin['id'];
}
if ($user_id) {
    $sql .= (strpos($sql, 'WHERE') === false ? " WHERE" : " AND") . " o.user_id = ?";
    $params[] = $user_id;
}
$sql .= " ORDER BY o.created_at DESC";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$orders = $stmt->fetchAll();
?>
<div class="d-flex justify-content-between align-items-center mb-4">
    <div class="d-flex align-items-center gap-3">
        <a href="<?= $user_id ? 'users.php' : 'index.php' ?>" class="btn btn-outline-secondary btn-sm"><i class="bi bi-arrow-left"></i> 返回</a>
        <h4 class="mb-0">币币订单记录 <?= $user_id ? "(用户ID: $user_id)" : "" ?></h4>
    </div>
</div>
<div class="table-container">
    <table class="table table-hover">
        <thead>
            <tr class="small text-muted">
                <th>ID</th>
                <th>用户</th>
                <th>币种/类型</th>
                <th>价格/数量</th>
                <th>已成交</th>
                <th>状态</th>
                <th>时间</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($orders as $o): ?>
            <tr>
                <td><?= $o['id'] ?></td>
                <td><?= htmlspecialchars($o['username']) ?><br><code class="small"><?= $o['uid'] ?></code></td>
                <td>
                    <strong><?= $o['symbol'] ?></strong><br>
                    <span class="badge <?= $o['side'] === 'buy' ? 'bg-success' : 'bg-danger' ?>"><?= $o['side'] === 'buy' ? '买入' : '卖出' ?></span>
                </td>
                <td><?= $o['price'] ?><br><?= $o['amount'] ?></td>
                <td><?= $o['filled'] ?></td>
                <td><?= $o['status'] ?></td>
                <td><small><?= $o['created_at'] ?></small></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php
$content = ob_get_clean();
renderAdminPage($content, $title);
?>
