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

$redirectTarget = safe_redirect_target((string) ($_POST['redirect'] ?? $_GET['redirect'] ?? 'index.php'));
if (current_user()) {
    redirect($redirectTarget);
}

$email = normalize_email((string) ($_POST['email'] ?? $_GET['email'] ?? ($_SESSION['last_signup_email'] ?? '')));

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        verify_csrf_or_fail();
        $action = (string) ($_POST['action'] ?? 'verify_signup');
        $email = normalize_email((string) ($_POST['email'] ?? ''));

        if ($action === 'resend_signup') {
            resend_signup_verification($email);
            flash('success', '新的验证码已经发送，请查收邮箱。');
            redirect(verify_page_url($email, $redirectTarget));
        }

        complete_signup_verification($email, (string) ($_POST['code'] ?? ''));
        flash('success', '邮箱验证成功，账号已经创建完成，请使用密码登录。');
        redirect(login_page_url($redirectTarget, ['email' => $email]));
    } catch (Throwable $exception) {
        flash('danger', $exception->getMessage());
        if ($email !== '') {
            redirect(verify_page_url($email, $redirectTarget));
        }
        redirect(register_page_url($redirectTarget));
    }
}

$latestRequest = null;
if ($email !== '') {
    try {
        $latestRequest = latest_signup_verification($email, false);
    } catch (Throwable $exception) {
        $latestRequest = null;
    }
}

render_layout_start('邮箱验证码', '邮箱验证码页，输入 6 位数字后完成注册激活。', 'auth');
?>
<section class="app-page-section auth-page-shell">
  <article class="app-card gradient-card hero-card">
    <div class="tiny-eyebrow">Step 3 / 4</div>
    <h1 class="app-hero-title compact-title">邮箱验证码</h1>
    <?php if ($email !== ''): ?>
      <p class="app-hero-copy mb-0">验证码已经发送到 <strong><?= h(mask_email($email)) ?></strong>。把邮件里的 6 位数字填进来，验证通过后系统才会真正创建账号。</p>
    <?php else: ?>
      <p class="app-hero-copy mb-0">这一页负责“确认你真的拥有这个邮箱”。如果你还没发验证码，请先返回注册页。</p>
    <?php endif; ?>
  </article>
</section>

<section class="app-page-section auth-page-shell">
  <div class="auth-stack auth-page-grid">
    <article class="app-card auth-card-panel">
      <div class="auth-panel-head">
        <div>
          <div class="list-title-strong">输入 6 位数字验证码</div>
          <div class="list-meta-line">验证码错误次数过多或过期后，需要重新发送。</div>
        </div>
        <span class="tag-chip">验证</span>
      </div>

      <?php if ($email === ''): ?>
        <div class="empty-tip">还没有待验证的邮箱记录。请先回到注册页填写邮箱和密码。</div>
        <div class="auth-link-grid mt-3">
          <a class="btn btn-gradient" href="<?= h(register_page_url($redirectTarget)) ?>">去注册</a>
          <a class="btn btn-outline-light" href="<?= h(start_page_url($redirectTarget)) ?>">返回启动页</a>
        </div>
      <?php else: ?>
        <form method="post" class="auth-form-grid">
          <input type="hidden" name="csrf_token" value="<?= h(csrf_token()) ?>">
          <input type="hidden" name="action" value="verify_signup">
          <input type="hidden" name="redirect" value="<?= h($redirectTarget) ?>">
          <input type="hidden" name="email" value="<?= h($email) ?>">
          <div>
            <label class="form-label" for="signup-code">验证码</label>
            <input class="form-control auth-code-input" id="signup-code" type="text" name="code" inputmode="numeric" autocomplete="one-time-code" maxlength="6" pattern="\d{6}" placeholder="请输入 6 位数字" required>
          </div>
          <button class="btn btn-gradient" type="submit">确认验证码</button>
        </form>

        <form method="post" class="mt-3">
          <input type="hidden" name="csrf_token" value="<?= h(csrf_token()) ?>">
          <input type="hidden" name="action" value="resend_signup">
          <input type="hidden" name="redirect" value="<?= h($redirectTarget) ?>">
          <input type="hidden" name="email" value="<?= h($email) ?>">
          <button class="btn btn-outline-light w-100" type="submit">重新发送验证码</button>
        </form>
      <?php endif; ?>
    </article>

    <article class="app-card auth-card-panel">
      <div class="auth-panel-head">
        <div>
          <div class="list-title-strong">当前说明</div>
          <div class="list-meta-line">为了让你更容易理解，我把“验证码页”翻译成了 3 句话。</div>
        </div>
        <span class="tag-chip secondary-chip">说明</span>
      </div>

      <div class="app-list-stack">
        <div class="app-list-item static-row">
          <span>
            <span class="list-title-strong">为什么要这一步</span>
            <span class="list-meta-line">它用来确认邮箱归属，避免随便填一个邮箱就直接生成账号。</span>
          </span>
        </div>
        <div class="app-list-item static-row">
          <span>
            <span class="list-title-strong">验证成功后会发生什么</span>
            <span class="list-meta-line">系统会真实写入用户表、生成 6 位 ID、自动创建钱包并把账号标记为已验证。</span>
          </span>
        </div>
        <div class="app-list-item static-row">
          <span>
            <span class="list-title-strong">下一页是什么</span>
            <span class="list-meta-line">验证通过后，会跳到登录页。你再输入密码，就能进入 5 个主页面。</span>
          </span>
        </div>
      </div>

      <?php if ($latestRequest && !empty($latestRequest['expires_at'])): ?>
        <div class="app-inline-note mt-3">最近一次验证码过期时间：<?= h(format_datetime((string) $latestRequest['expires_at'])) ?></div>
      <?php else: ?>
        <div class="app-inline-note mt-3">如果没收到邮件，请先检查垃圾箱，再点击“重新发送验证码”。</div>
      <?php endif; ?>

      <div class="auth-link-grid mt-3">
        <a class="btn btn-outline-light" href="<?= h(register_page_url($redirectTarget, $email !== '' ? ['email' => $email] : [])) ?>">返回注册页</a>
        <a class="btn btn-outline-light" href="<?= h(login_page_url($redirectTarget, $email !== '' ? ['email' => $email] : [])) ?>">去登录页</a>
      </div>
    </article>
  </div>
</section>
<?php render_layout_end(); ?>
