<?php
declare(strict_types=1);
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/SiteConfig.php';

// 中文注释：读取后台配置的预设金额与最低金额
$cfg = SiteConfig::getMany(['recharge_preset_amounts','recharge_min_amount']);
$presetStr = trim((string)($cfg['recharge_preset_amounts'] ?? ''));
$minStr = trim((string)($cfg['recharge_min_amount'] ?? ''));
$minVal = ($minStr !== '') ? max(0.01, (float)$minStr) : 0.01;
$presets = [];
if ($presetStr !== '') {
  foreach (explode(',', $presetStr) as $seg) {
    $v = (float)trim($seg);
    if ($v > 0) { $presets[] = number_format($v, 2, '.', ''); }
  }
}
?>
<!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="/libs/qrcode/qrcode.js"></script>
  <script src="/js/pay-modal.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:14px;margin-bottom:8px;color:#333;">请选择或输入充值金额</div>
        <div id="preset-amounts" style="display:grid;grid-template-columns:repeat(6,1fr);gap:10px;">
          <?php if (!empty($presets)): ?>
            <?php foreach ($presets as $p): ?>
              <button type="button" class="amt-chip" data-val="<?php echo htmlspecialchars($p, ENT_QUOTES); ?>" style="height:40px;border:1px solid #e5e7eb;border-radius:10px;background:#fff;font-weight:600;color:#111;">￥<?php echo htmlspecialchars($p, ENT_QUOTES); ?></button>
            <?php endforeach; ?>
          <?php else: ?>
            <div class="text-muted" style="grid-column:1/-1;color:#b00;">未配置预设金额，请在后台“充值设置”页面填写。</div>
          <?php endif; ?>
        </div>
        <div style="display:flex;gap:10px;align-items:center;margin-top:12px;">
          <label for="custom-amount" style="font-size:14px;">自定义金额：</label>
          <input type="number" id="custom-amount" min="<?php echo number_format($minVal, 2, '.', ''); ?>" step="0.01" placeholder="请输入金额(最低￥<?php echo number_format($minVal, 2, '.', ''); ?>)" style="flex:0 0 180px;padding:8px 10px;border:1px solid #e5e7eb;border-radius:10px;" />
        </div>
        <div id="confirm-line" style="margin-top:12px;padding:10px 12px;border:1px dashed #e5e7eb;border-radius:10px;background:#fafafa;color:#374151;">
          充值确认金额：<strong id="confirm-amt" style="color:#e53935;">—</strong>
        </div>
        <div style="margin-top:12px;display:flex;gap:10px;align-items:center;">
          <input type="hidden" id="amount" value="" />
          <button type="button" id="btn-recharge" class="btn" style="min-width:140px;background:#cfd2d6;color:#888;cursor:not-allowed;border:none;border-radius:8px;">立即充值</button>
          <div id="recharge-status" style="color:#666;font-size:13px;">请选择或输入金额后确认</div>
        </div>
      </div>

      <div id="pay-modal-wrap" style="display:none;"></div>
    </section>
  </div>
</main>
<?php require_once __DIR__ . '/includes/site-footer.php'; ?>
<script>
(function(){
  var chips = [];
  function setActiveChip(el){ chips.forEach(function(c){ c.classList.remove('active'); c.style.borderColor = '#e5e7eb'; c.style.boxShadow = 'none'; }); el.classList.add('active'); el.style.borderColor = '#c3a06b'; el.style.boxShadow = '0 0 0 2px rgba(195,160,107,.18) inset'; }
  var MIN_AMT = <?php echo json_encode($minVal); ?>;
  function setAmount(val){ var hid=document.getElementById('amount'); var conf=document.getElementById('confirm-amt'); var btn=document.getElementById('btn-recharge'); if (val < MIN_AMT) { hid.value=''; conf.textContent='—'; btn.disabled=true; btn.style.background='#cfd2d6'; btn.style.color='#888'; btn.style.cursor='not-allowed'; return; } hid.value = val > 0 ? String(val.toFixed(2)) : ''; conf.textContent = val > 0 ? ('￥' + val.toFixed(2)) : '—'; if (val > 0) { btn.disabled = false; btn.style.background = '#ff6b00'; btn.style.color = '#fff'; btn.style.cursor = 'pointer'; } else { btn.disabled = true; btn.style.background = '#cfd2d6'; btn.style.color = '#888'; btn.style.cursor = 'not-allowed'; } }
  function bindUI(){
    var ps = document.querySelectorAll('#preset-amounts .amt-chip'); chips = Array.prototype.slice.call(ps);
    chips.forEach(function(btn){ btn.addEventListener('click', function(){ setActiveChip(btn); var v = parseFloat(btn.getAttribute('data-val')||'0'); var ci = document.getElementById('custom-amount'); if (ci) { ci.value=''; } setAmount(v); }); });
    var ci = document.getElementById('custom-amount'); if (ci){ ['input','change','keyup'].forEach(function(ev){ ci.addEventListener(ev, function(){ chips.forEach(function(c){ c.classList.remove('active'); c.style.borderColor = '#e5e7eb'; c.style.boxShadow = 'none'; }); var v = parseFloat(ci.value||'0'); setAmount((v>0)?v:0); }); }); }
  }
  function createRecharge(){
    var amtStr = document.getElementById('amount').value || '';
    var amt = parseFloat(amtStr || '0');
    if (!(amt > 0)) { document.getElementById('recharge-status').textContent = '请先选择或输入有效金额'; return; }
    var ch = (window.PayModal && typeof window.PayModal.chooseChannel === 'function') ? window.PayModal.chooseChannel() : (function(){ var ua=navigator.userAgent||''; var wx=/MicroMessenger/i.test(ua); var m=/Android|iPhone|iPad|iPod|Windows Phone|Mobile/i.test(ua); return wx? 'wechat_jsapi' : (m? 'mobile_h5' : 'pc'); })();
    fetch('/api/recharge-create.php', { method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8'}, body:'amount='+encodeURIComponent(amt.toFixed(2))+'&pay_channel='+encodeURIComponent(ch) })
      .then(function(r){ return r.json(); })
      .then(function(resp){
        if (!resp || !resp.success){ document.getElementById('recharge-status').textContent = (resp&&resp.message)||'下单失败'; return; }
        if (ch === 'pc') {
          if (window.PayModal && typeof window.PayModal.openRecharge === 'function') { window.PayModal.openRecharge(resp, amt.toFixed(2)); }
          else { document.getElementById('recharge-status').textContent = '支付弹窗未加载'; }
        } else if (ch === 'wechat_jsapi') {
          var url = (resp.wx && resp.wx.oauth_url) ? resp.wx.oauth_url : '';
          if (!url) { document.getElementById('recharge-status').textContent = '微信授权链接缺失'; return; }
          window.location.href = url;
        } else if (ch === 'mobile_h5') {
          var wxUrl = resp.wx && resp.wx.h5_url; var aliUrl = resp.alipay && resp.alipay.h5_url;
          if (wxUrl) { window.location.href = wxUrl; }
          else if (aliUrl) { window.location.href = aliUrl; }
          else { document.getElementById('recharge-status').textContent = 'H5支付链接缺失'; }
        }
      })
      .catch(function(){ document.getElementById('recharge-status').textContent = '下单接口异常'; });
  }
  document.addEventListener('DOMContentLoaded', function(){
    if (window.PayModal && typeof window.PayModal.init==='function') window.PayModal.init();
    bindUI();
    var btn = document.getElementById('btn-recharge');
    if (btn) { btn.disabled = true; btn.addEventListener('click', createRecharge); }
  });
})();
</script>
</body>
</html>
