<?php
declare(strict_types=1);
require_once __DIR__ . '/app.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string) ($_POST['action'] ?? '');

    try {
        verify_csrf_or_fail();

        if ($action === 'purchase_vip') {
            $user = require_user();
            $targetLevel = (int) ($_POST['level'] ?? 0);
            $purchase = purchase_vip_upgrade((int) $user['id'], $targetLevel);
            $upgradedVip = vip_info((int) ($purchase['to_level'] ?? $targetLevel));
            $paidAmount = (float) ($purchase['price_usdt'] ?? 0);
            flash('success', $upgradedVip['name'] . ' 开通成功，已从可用余额扣除 ' . number_format($paidAmount, 2) . ' USDT。');
            redirect('vip.php?level=' . $targetLevel . '#vip-history');
        }
    } catch (Throwable $exception) {
        $targetLevel = (int) ($_POST['level'] ?? 0);
        flash('danger', $exception->getMessage());
        redirect('vip.php' . ($targetLevel > 0 ? '?level=' . $targetLevel . '#vip-checkout' : '#vip-checkout'));
    }
}

$user = current_user();
$previewMode = !$user;
$catalog = vip_catalog();
$currentVip = $user ? (int) $user['vip_level'] : 3;
$defaultLevel = $currentVip > 0 ? $currentVip : 1;
$selectedLevel = (int) ($_GET['level'] ?? $defaultLevel);
if (!isset($catalog[$selectedLevel]) || $selectedLevel === 0) {
    $selectedLevel = $defaultLevel;
}
$selectedVip = $catalog[$selectedLevel];
$wallet = $user ? wallet_snapshot((int) $user['id']) : ['available_balance' => 5560.25, 'frozen_balance' => 120.00];
$availableBalance = (float) ($wallet['available_balance'] ?? 0);
$selectedPrice = (float) $selectedVip['price'];
$balanceGap = max(0, $selectedPrice - $availableBalance);
$isCurrentOrLower = !$previewMode && $selectedLevel <= $currentVip;
$canPurchase = !$previewMode && !$isCurrentOrLower && $balanceGap <= 0;
$vipOrders = $user ? get_user_vip_orders((int) $user['id'], 8) : [];
$latestVipOrder = $vipOrders[0] ?? null;
$nextVip = (!$previewMode && isset($catalog[$currentVip + 1])) ? $catalog[$currentVip + 1] : null;

render_layout_start('VIP', 'VIP 等级页，支持真实余额开通、写入数据库、升级等级与查看升级记录。', 'vip');
?>
<section class="app-page-section">
  <article class="app-card gradient-card hero-card">
    <div class="tiny-eyebrow">VIP 等级</div>
    <h1 class="app-hero-title compact-title">余额直接开通更高返佣等级</h1>
    <p class="app-hero-copy mb-0">现在这个页面已经接上真实数据库：开通后会写入 VIP 订单记录、扣减钱包余额，并立即升级你的账号等级。</p>
    <?php if ($previewMode): ?>
      <div class="app-inline-note mt-3">当前是视觉预览模式。登录后可以使用真实钱包余额开通 VIP，并在下方看到升级记录。</div>
    <?php else: ?>
      <div class="app-inline-note mt-3">当前账号是 <?= h(vip_info($currentVip)['name']) ?>。如果余额充足，点一次“立即开通”就会直接完成升级。</div>
    <?php endif; ?>
  </article>
</section>

<section class="app-page-section">
  <article class="app-card vip-highlight-card">
    <div class="d-flex align-items-center justify-content-between gap-3 flex-wrap">
      <div>
        <div class="tiny-eyebrow">当前等级</div>
        <div class="vip-banner-title"><?= h(vip_info($currentVip)['name']) ?></div>
        <div class="list-meta-line">可用余额 <?= h(number_format($availableBalance, 2)) ?> USDT · 冻结余额 <?= h(number_format((float) ($wallet['frozen_balance'] ?? 0), 2)) ?> USDT</div>
      </div>
      <span class="vip-chip-large"><?= h(vip_info($currentVip)['name']) ?></span>
    </div>

    <div class="detail-meta-grid mt-3">
      <div>
        <div class="mini-label">目标等级</div>
        <div class="detail-mini-value"><?= h((string) $selectedVip['name']) ?></div>
      </div>
      <div>
        <div class="mini-label">开通金额</div>
        <div class="detail-mini-value"><?= h(number_format($selectedPrice, 2)) ?> USDT</div>
      </div>
      <div>
        <div class="mini-label">最近升级</div>
        <div class="detail-mini-value"><?= h($latestVipOrder ? vip_info((int) $latestVipOrder['to_level'])['name'] : '暂无') ?></div>
      </div>
    </div>
  </article>
</section>

<section class="app-page-section">
  <div class="app-task-list">
    <?php foreach ($catalog as $level => $vip): ?>
      <?php if ($level === 0) { continue; } ?>
      <article class="app-card vip-level-row<?= $selectedLevel === (int) $level ? ' is-selected' : '' ?>">
        <div class="d-flex align-items-start gap-3">
          <span class="task-platform-icon <?= (int) $level === 1 ? 'accent-gold' : ((int) $level === 2 ? 'accent-blue' : ((int) $level === 3 ? 'accent-violet' : 'accent-pink')) ?>"><?= app_icon_svg('vip') ?></span>
          <div class="flex-grow-1 min-w-0">
            <div class="d-flex align-items-center gap-2 flex-wrap">
              <div class="task-row-title"><?= h((string) $vip['name']) ?></div>
              <?php if (!$previewMode && $currentVip === (int) $level): ?>
                <span class="status-pill tone-success">当前等级</span>
              <?php elseif (!$previewMode && $currentVip > (int) $level): ?>
                <span class="status-pill tone-muted">已解锁</span>
              <?php endif; ?>
            </div>
            <div class="task-row-subtitle mt-1"><?= h((string) $vip['benefit']) ?></div>
            <div class="d-flex flex-wrap gap-2 mt-2">
              <span class="tag-chip">单任务佣金 <?= h(number_format((float) $vip['reward'], 2)) ?> USDT</span>
              <span class="tag-chip secondary-chip">每日 <?= h((string) $vip['daily_tasks']) ?> 单</span>
            </div>
          </div>
          <div class="text-end ms-auto">
            <div class="reward-strong"><?= h(number_format((float) $vip['price'], 0)) ?> USDT</div>
            <?php if ($selectedLevel === (int) $level): ?>
              <span class="status-pill tone-warning mt-2">已选中</span>
            <?php else: ?>
              <a class="btn btn-outline-light btn-sm px-3 mt-2" href="vip.php?level=<?= h((string) $level) ?>#vip-checkout">选择</a>
            <?php endif; ?>
          </div>
        </div>
      </article>
    <?php endforeach; ?>
  </div>
</section>

<section class="app-page-section" id="vip-checkout">
  <article class="app-card payment-preview-card">
    <div class="section-heading-app mb-3">
      <div class="tiny-eyebrow">开通支付</div>
      <h2 class="app-section-title"><?= h((string) $selectedVip['name']) ?> 结算卡</h2>
    </div>

    <div class="payment-hero-box">
      <div class="vip-banner-title mb-2"><?= h((string) $selectedVip['name']) ?></div>
      <div class="payment-price"><?= h(number_format($selectedPrice, 2)) ?> USDT</div>
      <div class="list-meta-line mt-2">单任务佣金 <?= h(number_format((float) $selectedVip['reward'], 2)) ?> USDT · 每日 <?= h((string) $selectedVip['daily_tasks']) ?> 单</div>
    </div>

    <div class="detail-meta-grid mt-3">
      <div>
        <div class="mini-label">支付方式</div>
        <div class="detail-mini-value">钱包可用余额</div>
      </div>
      <div>
        <div class="mini-label">当前可用</div>
        <div class="detail-mini-value"><?= h(number_format($availableBalance, 2)) ?> USDT</div>
      </div>
      <div>
        <div class="mini-label"><?= $isCurrentOrLower ? '升级状态' : '还差金额' ?></div>
        <div class="detail-mini-value"><?= $isCurrentOrLower ? h('已开通或更高等级') : h(number_format($balanceGap, 2) . ' USDT') ?></div>
      </div>
    </div>

    <?php if ($previewMode): ?>
      <div class="app-inline-note mt-3">要真正开通 VIP，需要先登录。登录后这个按钮会直接连到数据库：生成订单记录、扣款并升级你的等级。</div>
      <div class="d-grid gap-2 mt-3">
        <a class="btn btn-gradient" href="<?= h(login_page_url(current_request_target())) ?>">先登录账号</a>
        <a class="btn btn-outline-light" href="task.php">先查看任务大厅</a>
      </div>
    <?php elseif ($isCurrentOrLower): ?>
      <div class="app-inline-note mt-3">当前账号已经是 <?= h(vip_info($currentVip)['name']) ?>。无需重复开通，直接去做更高等级任务即可。</div>
      <div class="d-grid gap-2 mt-3">
        <a class="btn btn-gradient" href="task.php">去做任务</a>
        <?php if ($nextVip): ?>
          <a class="btn btn-outline-light" href="vip.php?level=<?= h((string) $nextVip['level']) ?>#vip-checkout">查看 <?= h((string) $nextVip['name']) ?></a>
        <?php else: ?>
          <a class="btn btn-outline-light" href="wallet.php#history-panel">查看钱包流水</a>
        <?php endif; ?>
      </div>
    <?php elseif ($balanceGap > 0): ?>
      <div class="app-inline-note mt-3">当前余额还差 <?= h(number_format($balanceGap, 2)) ?> USDT，暂时不能直接开通。等你下一步把充值流程接上后，这里就能完整跑通。</div>
      <div class="d-grid gap-2 mt-3">
        <a class="btn btn-gradient" href="wallet.php#deposit-panel">去钱包查看充值入口</a>
        <a class="btn btn-outline-light" href="profile.php#support-panel">联系专属客服</a>
      </div>
    <?php else: ?>
      <div class="app-inline-note mt-3">确认后会立刻执行 3 件事：1）写入 VIP 订单；2）从可用余额扣款；3）更新你的账号等级。</div>
      <form method="post" class="d-grid gap-2 mt-3">
        <input type="hidden" name="csrf_token" value="<?= h(csrf_token()) ?>">
        <input type="hidden" name="action" value="purchase_vip">
        <input type="hidden" name="level" value="<?= h((string) $selectedLevel) ?>">
        <button class="btn btn-gradient" type="submit" data-confirm="确认使用钱包可用余额开通 <?= h((string) $selectedVip['name']) ?>？扣款后会立即升级，且此动作不可撤销。">立即开通 <?= h((string) $selectedVip['name']) ?></button>
        <a class="btn btn-outline-light" href="wallet.php#history-panel">先看资金流水</a>
      </form>
    <?php endif; ?>
  </article>
</section>

<section class="app-page-section" id="vip-history">
  <article class="app-card">
    <div class="section-heading-app mb-3">
      <div class="tiny-eyebrow">升级记录</div>
      <h2 class="app-section-title">最近 VIP 订单</h2>
    </div>

    <?php if ($previewMode): ?>
      <div class="app-inline-note">登录后这里会显示你的真实 VIP 订单时间线，例如“VIP0 → VIP1、扣款金额、开通时间”。</div>
    <?php elseif ($vipOrders): ?>
      <div class="app-list-stack">
        <?php foreach ($vipOrders as $order): ?>
          <div class="app-list-item align-items-start">
            <span>
              <span class="list-title-strong"><?= h(vip_info((int) $order['from_level'])['name']) ?> → <?= h(vip_info((int) $order['to_level'])['name']) ?></span>
              <span class="list-meta-line"><?= h(format_datetime((string) ($order['completed_at'] ?: $order['created_at']))) ?> · 扣款 <?= h(number_format((float) $order['price_usdt'], 2)) ?> USDT</span>
              <span class="list-meta-line"><?= h((string) $order['note']) ?></span>
            </span>
            <span class="d-inline-flex flex-column align-items-end gap-2">
              <span class="status-pill tone-success">已升级</span>
              <span class="ledger-value-inline is-negative">-<?= h(number_format((float) $order['price_usdt'], 2)) ?> USDT</span>
            </span>
          </div>
        <?php endforeach; ?>
      </div>
    <?php else: ?>
      <div class="empty-tip">你还没有 VIP 升级记录。等余额充足后，第一次开通就会自动写入这里。</div>
    <?php endif; ?>
  </article>
</section>
<?php render_layout_end(); ?>
