<?php
/**
 * 后台 · 账号安全
 */
$admin = current_user();
$smtpReady = setting('smtp_enabled') === '1' && trim((string) setting('smtp_host')) !== '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    check_csrf();
    if (input('act') === 'apply_security_patch') {
        list($patchOk, $patchMsg) = security_patch_apply(true);
        flash($patchMsg, $patchOk ? '' : 'err');
        redirect(admin_url('account_security'));
    }
    if (input('act') === 'save_account_security') {
        // 邮箱验证登录与 TOTP 动态验证已改为用户个人中心自助管理，后台不再提供总开关。
        set_setting('login_lockout_enabled', input('login_lockout_enabled') === '1' ? '1' : '0');
        set_setting('login_lockout_threshold', (string) max(1, min(50, (int) input('login_lockout_threshold', 5))));
        set_setting('login_lockout_minutes', (string) max(1, min(1440, (int) input('login_lockout_minutes', 30))));
        set_setting('security_auto_patch', input('security_auto_patch') === '1' ? '1' : '0');
        if (input('security_auto_patch') === '1') {
            security_patch_apply(false);
        }
        flash('账号安全设置已保存');
        redirect(admin_url('account_security'));
    }
}

$loginLockoutEnabled = setting('login_lockout_enabled', '1') === '1';
$loginLockoutThreshold = max(1, min(50, (int) setting('login_lockout_threshold', '5')));
$loginLockoutMinutes = max(1, min(1440, (int) setting('login_lockout_minutes', '30')));
$securityPatchEnabled = security_patch_auto_enabled();
$securityPatchRealtime = security_patch_realtime_enabled();
$securityPatchVersion = security_patch_current_version();
$securityPatchLast = security_patch_last_version();
$securityPatchAt = security_patch_last_at();
$verifiedEmailUsers = (int) DB::val('SELECT COUNT(*) FROM ' . DB::table('users') . ' WHERE status = 1 AND email <> ? AND email_verified = 1', [''], 0);
$totalUsers = (int) DB::val('SELECT COUNT(*) FROM ' . DB::table('users') . ' WHERE status = 1', [], 0);
$guardDays = muwei_guard_days();
?>
<section class="panel">
  <h2 class="section-title">账号安全</h2>
  <p class="muted">这里只保留登录失败保护与安全补丁设置。登录验证已移到用户个人中心，由每位用户在「我的 → 登录验证」中自行开启或关闭，后台不再统一控制。</p>

  <div class="card-soft security-guard-entry">
    <div>
      <div class="security-guard-entry-title">
        <img class="muwei-logo" src="<?= e(asset('img/muwei-guard-logo.svg')) ?>" alt="木卫守护 Logo">
        <strong>木卫守护</strong>
        <span class="muwei-guard-days">已守护你 <?= number_format($guardDays) ?> 天</span>
      </div>
      <p class="muted">一键检测安装入口、账号令牌、敏感目录、上传目录和配置文件等常见高危项；发现可修复问题时集中处理，检测和修复都在独立页面完成。</p>
    </div>
    <a class="btn-primary" href="<?= e(admin_url('security_guard')) ?>">打开木卫守护 →</a>
  </div>

  <form method="post" class="form-card" action="<?= e(admin_url('account_security')) ?>">
    <?= csrf_field() ?>
    <input type="hidden" name="act" value="save_account_security">
    <label class="switch-line">
      <span class="switch-copy">
        <strong>登录失败保护</strong>
        <small>同一账号连续输入错误密码达到上限后，临时禁止该账号登录；到达限制时长后自动解除，登录成功后失败次数清零。</small>
      </span>
      <span class="switch-control">
        <input type="hidden" name="login_lockout_enabled" value="0">
        <input class="switch-input" type="checkbox" name="login_lockout_enabled" value="1"<?= $loginLockoutEnabled ? ' checked' : '' ?>>
        <span class="switch-track" aria-hidden="true"><span class="switch-thumb"></span></span>
      </span>
    </label>
    <div class="field-row">
      <div class="field">
        <label>连续密码错误次数上限</label>
        <input type="number" name="login_lockout_threshold" min="1" max="50" step="1" value="<?= (int) $loginLockoutThreshold ?>" inputmode="numeric">
        <small class="muted">达到该次数后锁定账号，默认 5 次，范围 1–50。</small>
      </div>
      <div class="field">
        <label>限制登录时长（分钟）</label>
        <input type="number" name="login_lockout_minutes" min="1" max="1440" step="1" value="<?= (int) $loginLockoutMinutes ?>" inputmode="numeric">
        <small class="muted">锁定后需等待该时长才能重新登录，默认 30 分钟，范围 1–1440。</small>
      </div>
    </div>
    <label class="switch-line">
      <span class="switch-copy">
        <strong>自动应用安全补丁</strong>
        <small>默认开启。自动轮换持久登录令牌、启用设备绑定、清理安装向导遗留的管理员登录令牌；仅执行源码内置的幂等加固步骤，不下载远程代码。</small>
      </span>
      <span class="switch-control">
        <input type="hidden" name="security_auto_patch" value="0">
        <input class="switch-input" type="checkbox" name="security_auto_patch" value="1"<?= $securityPatchEnabled ? ' checked' : '' ?>>
        <span class="switch-track" aria-hidden="true"><span class="switch-thumb"></span></span>
      </span>
    </label>
    <div class="card-soft" style="padding:14px 16px;border:1px solid var(--line);border-radius:14px">
      <strong style="font-size:13px">当前状态</strong>
      <p class="muted" style="margin:6px 0 0;font-size:12px;line-height:1.9">
        登录失败保护：<b><?= $loginLockoutEnabled ? '已开启' : '已关闭' ?></b> · 连续错误 <b><?= (int) $loginLockoutThreshold ?></b> 次锁定 <b><?= (int) $loginLockoutMinutes ?></b> 分钟<br>
        自动安全补丁：<b><?= $securityPatchEnabled ? '已开启' : '已关闭' ?></b> · 实时更新：<b><?= $securityPatchRealtime ? '已开启' : '已关闭' ?></b><br>
        补丁版本：<b><?= e($securityPatchVersion) ?></b><?= $securityPatchLast === $securityPatchVersion ? '（已应用）' : '（待更新）' ?><br>
        最近应用：<b><?= e($securityPatchAt !== '' ? $securityPatchAt : '尚未应用') ?></b><br>
        已绑定并验证邮箱的正常用户：<b><?= $verifiedEmailUsers ?></b> / <?= $totalUsers ?><br>
        SMTP 发信：<b><?= $smtpReady ? '已配置' : '未配置' ?></b>
      </p>
    </div>
    <div class="auth-links" style="justify-content:flex-start;margin-top:0">
      <a class="link-btn" href="<?= e(admin_url('settings_mail')) ?>">前往邮件设置 →</a>
    </div>
    <button class="btn-primary" type="submit">保存账号安全设置</button>
  </form>
  <form method="post" style="margin-top:10px">
    <?= csrf_field() ?>
    <input type="hidden" name="act" value="apply_security_patch">
    <button class="btn-ghost" type="submit">立即检查并应用安全补丁</button>
  </form>
  <p class="muted" style="margin-top:10px">安全补丁默认开启并自动更新；执行后会轮换所有持久登录令牌，已登录的浏览器会话不受影响，但下次仅凭旧 Cookie 恢复登录时需要重新验证。</p>
</section>
