<?php
declare(strict_types=1);
// 中文注释：我的余额页面（PC端，统一使用现有UC样式）
if (session_status() !== PHP_SESSION_ACTIVE && !headers_sent()) { session_start(); }
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/includes/Database.php';
require_once __DIR__ . '/includes/Wallet.php';

$userId = isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : 0;
if ($userId <= 0) {
  http_response_code(403);
  echo '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8"><title>权限不足</title></head><body>';
  echo '<div style="max-width:800px;margin:80px auto;font-size:16px;line-height:1.8;">错误：未检测到登录用户，请先登录后访问我的余额。</div>';
  echo '</body></html>';
  exit;
}

$db = Database::getInstance();
$pdo = $db->pdo();
Wallet::ensureTables($pdo);
$balance = Wallet::getBalance($pdo, $userId);
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$list = Wallet::listTransactions($pdo, $userId, $page, 20);
// 中文注释：中文映射（类型与状态）
function tx_type_cn(string $t): string {
  $map = [ 'recharge'=>'充值', 'withdrawal'=>'提现', 'purchase'=>'消费', 'adjust'=>'调整' ];
  return $map[$t] ?? $t;
}
function tx_status_cn(string $s): string {
  $map = [ 'pending'=>'待处理', 'completed'=>'已完成', 'failed'=>'失败' ];
  return $map[$s] ?? $s;
}
function tx_status_style(string $s): string {
  $styles = [
    'pending'   => 'background:#f3f4f6;color:#374151;',
    'completed' => 'background:#d1fae5;color:#065f46;',
    'failed'    => 'background:#fee2e2;color:#991b1b;',
  ];
  $st = isset($styles[$s]) ? $styles[$s] : 'background:#f3f4f6;color:#374151;';
  return 'display:inline-block;padding:2px 10px;border-radius:12px;font-size:12px;' . $st;
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <title>我的余额</title>
  <link href="/fontawesome/css/all.min.css" rel="stylesheet" />
  <link rel="stylesheet" href="/css/main.css" />
  <link rel="stylesheet" href="/css/header.css" />
  <link rel="stylesheet" href="/css/footer.css" />
  <script src="/libs/jquery-3.7.1.min.js"></script>
  <script src="/js/header.js"></script>
</head>
<body>
<?php require_once __DIR__ . '/includes/site-header.php'; ?>
<main class="user-center">
  <div class="container uc-layout">
    <?php require __DIR__ . '/includes/uc-nav.php'; ?>
    <section class="uc-content">
      <h2 class="uc-title">我的余额</h2>
      <div class="uc-card" style="margin-top:10px;">
        <div style="font-size:16px;">当前余额：<strong style="color:#0a8;">￥<?php echo number_format($balance, 2, '.', ''); ?></strong></div>
        <div style="margin-top:8px;font-size:13px;color:#666;">如需充值请前往“立即充值”页面。</div>
      </div>

      <div class="uc-card" style="margin-top:12px;">
        <div style="font-size:15px;margin-bottom:8px;">交易流水（仅显示已完成）</div>
        <table class="table" style="width:100%;">
          <thead>
            <tr>
              <th style="text-align:left;padding:8px;">时间</th>
              <th style="text-align:left;padding:8px;">类型</th>
              <th style="text-align:right;padding:8px;">发生前余额</th>
              <th style="text-align:right;padding:8px;">发生金额</th>
              <th style="text-align:right;padding:8px;">发生后余额</th>
              <th style="text-align:left;padding:8px;">说明</th>
            </tr>
          </thead>
          <tbody>
            <?php if (empty($list)): ?>
              <tr><td colspan="6" style="padding:10px;color:#999;">暂无流水</td></tr>
            <?php else: foreach ($list as $r): ?>
              <?php $before = isset($r['balance_before']) ? (float)$r['balance_before'] : null; $after = isset($r['balance_after']) ? (float)$r['balance_after'] : null; $delta = (isset($before) && isset($after)) ? ($after - $before) : null; $signAmt = ($delta !== null) ? $delta : ((string)$r['type'] === 'purchase' ? -((float)$r['amount']) : (float)$r['amount']); ?>
              <tr>
                <td style="padding:8px;"><?php echo htmlspecialchars((string)$r['transaction_time']); ?></td>
                <td style="padding:8px;"><?php echo htmlspecialchars(tx_type_cn((string)$r['type'])); ?></td>
                <td style="padding:8px;text-align:right;">￥<?php echo number_format((float)($before ?? 0), 2, '.', ''); ?></td>
                <td style="padding:8px;text-align:right; color:<?php echo ($signAmt>=0)?'#0a8':'#b00'; ?>;"><?php echo ($signAmt>=0?'+':'-'); ?>￥<?php echo number_format(abs((float)$signAmt), 2, '.', ''); ?></td>
                <td style="padding:8px;text-align:right;">￥<?php echo number_format((float)($after ?? 0), 2, '.', ''); ?></td>
                <td style="padding:8px;"><?php echo htmlspecialchars((string)($r['description'] ?? '')); ?></td>
              </tr>
            <?php endforeach; endif; ?>
          </tbody>
        </table>
      </div>
    </section>
  </div>
</main>
<?php require_once __DIR__ . '/includes/site-footer.php'; ?>
</body>
</html>
<?php /* 中文注释：页面结束 */ ?>
