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

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

// 获取明细
$logs = $db->fetchAll("
    SELECT * FROM balance_logs 
    WHERE user_id = $user_id 
    ORDER BY id DESC 
    LIMIT $offset, $perpage
");
?>

<div class="balance-log-container">
    <div class="page-header">
        <h2>余额明细</h2>
        <a href="?page=recharge" class="btn btn-primary">充值</a>
    </div>
    
    <div class="table-container">
        <table class="data-table">
            <thead>
                <tr>
                    <th>时间</th>
                    <th>金额</th>
                    <th>类型</th>
                    <th>备注</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($logs)): ?>
                    <tr><td colspan="4" style="text-align: center;">暂无余额变动记录</td></tr>
                <?php else: ?>
                    <?php foreach ($logs as $log): ?>
                        <tr>
                            <td><?php echo $log['created_at']; ?></td>
                            <td style="color: <?php echo $log['amount'] > 0 ? 'var(--success-color)' : 'var(--danger-color)'; ?>; font-weight: 500;">
                                <?php echo $log['amount'] > 0 ? '+' : ''; ?>¥<?php echo number_format($log['amount'], 2); ?>
                            </td>
                            <td>
                                <?php 
                                $type_map = ['recharge' => '充值', 'consume' => '消费', 'refund' => '退款'];
                                echo $type_map[$log['type']] ?? $log['type'];
                                ?>
                            </td>
                            <td><?php echo htmlspecialchars($log['remark'] ?: '-'); ?></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=balance_log&p=<?php echo $i; ?>" class="page-link <?php echo $i == $page ? 'active' : ''; ?>">
                    <?php echo $i; ?>
                </a>
            <?php endfor; ?>
        </div>
    <?php endif; ?>
</div>

<style>
.balance-log-container .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
}
</style>