<?php
/**
 * 财务明细
 */

$page = max(1, intval($_GET['p'] ?? 1));
$page_size = 15;
$offset = ($page - 1) * $page_size;

// 余额变动记录表
$total = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('balance_log')} WHERE member_id = ?", [$_SESSION['member_id']])['cnt'];
$rows = $db->fetchAll("SELECT * FROM {$db->table('balance_log')} WHERE member_id = ? ORDER BY id DESC LIMIT {$offset}, {$page_size}", [$_SESSION['member_id']]);

$total_pages = ceil($total / $page_size);
?>
<div class="page-header">
    <h1 class="page-title">
        <i class="icon-dollar-sign"></i>
        财务明细
    </h1>
</div>
<div class="page-content">
    <?php if (empty($rows)): ?>
    <div class="empty-state">
        <div class="empty-state-icon">💰</div>
        <div class="empty-state-text">暂无财务记录</div>
    </div>
    <?php else: ?>
    <table class="table">
        <thead>
            <tr>
                <th>ID</th>
                <th>变动金额</th>
                <th>类型</th>
                <th>备注</th>
                <th>时间</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($rows as $row): ?>
            <tr>
                <td><?php echo $row['id']; ?></td>
                <td style="color: <?php echo ($row['amount'] ?? 0) >= 0 ? '#10b981' : '#ef4444'; ?>;">
                    <?php echo ($row['amount'] ?? 0) >= 0 ? '+' : ''; ?>¥<?php echo number_format($row['amount'], 2); ?>
                </td>
                <td><?php echo htmlspecialchars($row['type'] ?? '-'); ?></td>
                <td><?php echo htmlspecialchars($row['note'] ?? ''); ?></td>
                <td><?php echo date('Y-m-d H:i', $row['add_time'] ?? time()); ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <?php if ($total_pages > 1): ?>
    <div class="pagination">
        <?php if ($page > 1): ?><a href="?page=finance&p=<?php echo $page - 1; ?>">上一页</a><?php endif; ?>
        <?php for ($i = 1; $i <= $total_pages; $i++): ?>
        <a href="?page=finance&p=<?php echo $i; ?>" class="<?php echo $i === $page ? 'current' : ''; ?>"><?php echo $i; ?></a>
        <?php endfor; ?>
        <?php if ($page < $total_pages): ?><a href="?page=finance&p=<?php echo $page + 1; ?>">下一页</a><?php endif; ?>
    </div>
    <?php endif; ?>
    <?php endif; ?>
</div>