SOURCE DOWNLOAD

木漏茶室源码下载中心

整站 PHP 源码:可浏览文件、复制路径、下载单文件或打包 ZIP。

发布版本 v6.25.232 升级后自动生成独立源码包,下载中心只发送这份冻结包 已排除 config.php / 用户数据 / 上传文件 / 升级备份
komorebi-forum 183 个节点 · PHP 8.3.37 · 完整源码 ZIP 1.31 MB
下载完整源码 ZIP 源码包大小:1.31 MB 安装教程 作者主页 免费开源 免费下载 ↓
COMMUNITY DEPLOYMENTS

已经跑起来的木漏茶室

从源码下载中心下载、完成安装并回传验证的站外站点。每个站点只计 1 次部署下载量;已记录站点会实时读取名称、版本、Logo 与在线状态,本机、内网和证书异常站点无法完成回传。

实时检测
2 个站点已部署

已展示全部 2 个站点。

admin/users.php 97.5 KB · 发布包 v6.25.232
下载
<?php
/**
 * 后台 · 用户管理
 */
$admin = current_user();
$creatableRoles = is_superadmin($admin) ? ['admin', 'user', 'moderator', 'vip'] : ['user', 'moderator', 'vip'];

// 代登录退出走 GET(页头链接)
if (input('act') === 'stop_impersonate') {
    unset($_SESSION['imp_uid']);
    flash('已退出代登录');
    redirect(page_url('home'));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    check_csrf();
    $act = input('act');
    $uid = (int) input('uid');
    $target = user_by_id($uid);

    if ($target && ($target['role'] ?? '') === 'superadmin' && ($admin['role'] ?? '') !== 'superadmin') {
        flash($act === 'delete' ? '管理员不能删除超级管理员账号' : '管理员不能修改超级管理员的资料或权限', 'err');
        redirect(admin_url('users'));
    }

    if ($act === 'stop_impersonate') {
        unset($_SESSION['imp_uid']);
        flash('已退出代登录');
        redirect(admin_url('users'));
    }

    // ---------- 超级管理员保护锁 ----------
    if (in_array($act, ['sa_lock_enable', 'sa_lock_disable', 'sa_lock_send_email', 'sa_lock_email_unlock'], true)) {
        if (!is_superadmin($admin)) {
            flash('只有超级管理员可以操作超级管理员保护锁', 'err');
        } elseif ($act === 'sa_lock_enable') {
            if (superadmin_lock_is_on()) {
                flash('超级管理员保护锁已经开启', 'err');
            } else {
                $code = trim((string) ($_POST['code'] ?? ''));
                $code2 = trim((string) ($_POST['code2'] ?? ''));
                if (!superadmin_lock_code_format_ok($code)) {
                    flash('安全码必须为 6 位数字', 'err');
                } elseif ($code !== $code2) {
                    flash('两次输入的安全码不一致', 'err');
                } else {
                    superadmin_lock_enable($code);
                    unset($_SESSION['sa_lock_email_sent'], $_SESSION['sa_lock_email_attempts']);
                    flash('超级管理员保护锁已开启,修改用户名和密码需要通过安全码关闭保护锁');
                }
            }
        } elseif ($act === 'sa_lock_disable') {
            if (!superadmin_lock_is_on()) {
                flash('超级管理员保护锁当前未开启', 'err');
            } elseif (superadmin_lock_rate_limited()) {
                flash('安全码错误次数过多,请 10 分钟后再试,或使用邮箱验证解锁', 'err');
            } elseif (!superadmin_lock_verify_code(trim((string) ($_POST['code'] ?? '')))) {
                flash('安全码不正确,请输入开启保护锁时设置的 6 位安全码', 'err');
            } else {
                superadmin_lock_disable();
                unset($_SESSION['sa_lock_email_sent'], $_SESSION['sa_lock_email_attempts']);
                flash('安全码验证通过,超级管理员保护锁已关闭');
            }
        } elseif ($act === 'sa_lock_send_email') {
            if (!superadmin_lock_is_on()) {
                if (input('ajax') === '1') {
                    json_out(['ok' => false, 'msg' => '超级管理员保护锁当前未开启']);
                }
                flash('超级管理员保护锁当前未开启', 'err');
            } else {
                list($ok, $msg) = superadmin_lock_send_email_code();
                if (input('ajax') === '1') {
                    json_out(['ok' => (bool) $ok, 'msg' => $msg, 'retry_after' => $ok ? 60 : 0]);
                }
                flash($msg, $ok ? 'ok' : 'err');
            }
        } elseif ($act === 'sa_lock_email_unlock') {
            if (!superadmin_lock_is_on()) {
                if (input('ajax') === '1') {
                    json_out(['ok' => false, 'msg' => '超级管理员保护锁当前未开启']);
                }
                flash('超级管理员保护锁当前未开启', 'err');
            } else {
                list($ok, $msg) = superadmin_lock_consume_email_code(trim((string) ($_POST['email_code'] ?? '')));
                if ($ok) {
                    unset($_SESSION['sa_lock_email_sent'], $_SESSION['sa_lock_email_attempts']);
                }
                if (input('ajax') === '1') {
                    json_out(['ok' => (bool) $ok, 'msg' => $msg, 'lock_on' => superadmin_lock_is_on()]);
                }
                flash($msg, $ok ? 'ok' : 'err');
            }
        }
        redirect(admin_url('users'));
    }

    if ($act === 'create') {
        $username = trim((string) ($_POST['username'] ?? ''));
        $password = (string) ($_POST['password'] ?? '');
        $password2 = (string) ($_POST['password2'] ?? '');
        $nickname = trim((string) ($_POST['nickname'] ?? ''));
        $gender = (string) ($_POST['gender'] ?? 'secret');
        $email = trim((string) ($_POST['email'] ?? ''));
        $role = (string) ($_POST['role'] ?? 'user');
        if (!in_array($role, $creatableRoles, true)) {
            flash('你没有权限添加该角色的用户', 'err');
            redirect(admin_url('users'));
        }
        $errors = validate_register($username, $password, $password2, $nickname, $email);
        if ($errors) {
            foreach ($errors as $er) { flash($er, 'err'); }
        } else {
            try {
                $newUid = create_user($username, $password, $nickname, $gender, $email, $role);
                DB::run('UPDATE ' . DB::table('users') . ' SET email_verified = 1 WHERE id = ?', [(int) $newUid]);
                user_initial_profile_capture((int) $newUid);
                audit_log('admin_add_user', 'UID ' . $newUid . ' 角色 ' . $role . ' 操作者 ' . $admin['username']);
                flash('已添加用户 ' . $username . ',角色:' . role_label($role));
            } catch (Exception $e) {
                flash('添加失败:' . $e->getMessage(), 'err');
            }
        }
        redirect(admin_url('users'));
    }

    if ($act === 'random_guest') {
        $alphabet = 'abcdefghjkmnpqrstuvwxyz23456789';
        $username = '';
        for ($i = 0; $i < 20; $i++) {
            $candidate = 'guest' . random_int(100000, 999999);
            if (!user_by_username($candidate)) {
                $username = $candidate;
                break;
            }
        }
        if ($username === '') {
            flash('随机账号生成失败,请稍后再试', 'err');
            redirect(admin_url('users'));
        }
        $password = '';
        for ($i = 0; $i < 10; $i++) {
            $password .= $alphabet[random_int(0, strlen($alphabet) - 1)];
        }
        $nickname = '访客' . random_int(1000, 9999);
        try {
            $newUid = create_user($username, $password, $nickname, 'secret', '', 'user');
            DB::run('UPDATE ' . DB::table('users') . ' SET email_verified = 1 WHERE id = ?', [(int) $newUid]);
            audit_log('admin_random_guest', 'UID ' . $newUid . ' 随机访客 ' . $username . ' 操作者 ' . $admin['username']);
            flash('已创建随机访客:用户名 ' . $username . ' · 密码 ' . $password . ' · 昵称 ' . $nickname . '(请复制保存,密码只显示这一次)');
        } catch (Exception $e) {
            flash('随机访客创建失败:' . $e->getMessage(), 'err');
        }
        redirect(admin_url('users'));
    }

    if ($act === 'restore_archive' || $act === 'restore_archives') {
        if (!is_superadmin($admin)) {
            flash('只有超级管理员可以恢复被删除账号', 'err');
            redirect(admin_url('users'));
        }
        $ids = [];
        if ($act === 'restore_archives') {
            foreach ((array) ($_POST['archive_ids'] ?? []) as $v) {
                $id = (int) $v;
                if ($id > 0) { $ids[] = $id; }
            }
        } else {
            $ids[] = (int) input('archive_id');
        }
        $ids = array_values(array_unique($ids));
        if (!$ids) {
            flash('请先勾选要恢复的账号', 'err');
            redirect(admin_url('users') . '#deletedAccounts');
        }
        $okCount = 0;
        $errors = [];
        $lastUid = 0;
        foreach ($ids as $archiveId) {
            list($ok, $msg, $newUid) = account_restore_archive($archiveId, (int) $admin['id']);
            if ($ok) {
                $okCount++;
                $lastUid = (int) $newUid;
            } else {
                $errors[] = '存档 #' . $archiveId . ':' . $msg;
            }
        }
        if ($okCount > 0) {
            flash('已恢复 ' . $okCount . ' 个账号及其全部已存档数据');
        }
        if ($errors) {
            flash(implode(';', $errors), 'err');
        }
        redirect(admin_url('users', $okCount === 1 && $lastUid > 0 ? ['uid' => $lastUid] : []) . ($okCount === 0 ? '#deletedAccounts' : ''));
    }

    if (!$target) {
        flash('用户不存在', 'err');
        redirect(admin_url('users'));
    }

    // 官方固定账号:不可删除、不可代登录、不可开启用户名修改
    // 部署页设置的管理员:锁死超级管理员身份,不得移交、降级、注销或封禁。
    if (is_installer_admin($target)) {
        if ($act === 'delete' || $act === 'role' || $act === 'impersonate') {
            flash($act === 'delete' ? '部署页设置的管理员账号已锁死,不能注销' : ($act === 'role' ? '部署页设置的管理员账号已锁死,不能移交或降级' : '部署页设置的管理员账号不能代登录'), 'err');
            redirect(admin_url('users'));
        }
        if (in_array($act, ['ban', 'mute', 'site_mute', 'toggle_protect'], true)) {
            flash('部署页设置的管理员账号已锁死,不能封禁、禁言或修改账号保护状态', 'err');
            redirect(admin_url('users'));
        }
    }

    if (is_official_account($target)) {
        if ($act === 'delete') {
            flash('官方固定账号不能删除', 'err');
            redirect(admin_url('users'));
        }
        if ($act === 'impersonate') {
            flash('官方固定账号不能代登录', 'err');
            redirect(admin_url('users'));
        }
        if ($act === 'toggle_username') {
            flash('官方固定账号的用户名 101 不可修改', 'err');
            redirect(admin_url('users'));
        }
        if (in_array($act, ['ban', 'mute', 'site_mute', 'toggle_protect'], true)) {
            flash('官方固定账号不能封禁、禁言或设置账号保护', 'err');
            redirect(admin_url('users'));
        }
    }

    if ($act === 'verify_save') {
        $verifyEnabled = input('verified') === '1' ? 1 : 0;
        $verifyType = input('verify_type', 'official') === 'professional' ? 'professional' : 'official';
        $verifyStyle = (string) input('verify_style', 'blue');
        $styles = verify_styles();
        if (!array_key_exists($verifyStyle, $styles)) {
            $verifyStyle = verify_style_of($target);
        }
        $verifyTitle = mb_substr(trim((string) ($_POST['verify_title'] ?? '')), 0, 60);
        $verifyInfo = mb_substr(trim((string) ($_POST['verify_info'] ?? '')), 0, 255);
        if ($verifyEnabled && $verifyInfo === '') {
            $verifyInfo = $verifyTitle !== '' ? $verifyTitle : '认证账号';
        }
        DB::run('UPDATE ' . DB::table('users') . ' SET verified = ?, verify_status = ?, verify_type = ?, verify_style = ?, verify_title = ?, verify_info = ?, verify_reason = ?, verify_paid = 0, verify_pending_type = ?, verify_pending_style = ?, verify_pending_title = ?, verify_pending_info = ? WHERE id = ?',
            [$verifyEnabled, $verifyEnabled ? 2 : 0, $verifyType, $verifyStyle, $verifyTitle, $verifyInfo, '', '', '', '', '', $uid]);
        audit_log('user_verify', 'UID ' . $uid . ' ' . ($verifyEnabled ? '开启认证 ' . $styles[$verifyStyle][0] : '关闭认证'));
        flash($verifyEnabled ? '认证信息已保存,前台立即展示 ' . $styles[$verifyStyle][0] : '已关闭该用户的认证 V 标识');
        redirect(admin_url('users', ['uid' => $uid, 'verify' => 1]));
    }

    $targetSuperLocked = is_superadmin($target) && superadmin_lock_is_on();
    $targetProtectedAdminPeer = account_is_protected($target)
        && ($target['role'] ?? '') === 'admin'
        && !is_superadmin($admin);

    if ($act === 'ban') {
        if ($uid === (int) $admin['id']) {
            flash('不能封禁自己', 'err');
        } else {
            $seconds = max(0, (int) input('duration', 0));
            $until = $seconds > 0 ? date('Y-m-d H:i:s', time() + $seconds) : '9999-12-31 23:59:59';
            $reason = mb_substr(trim((string) input('reason', '')), 0, 255);
            if ($seconds <= 0) {
                list($codeOk, $codeMsg) = account_delete_code_check($admin, input('ban_email_code'), 'admin_ban_account');
                if (!$codeOk) {
                    flash('永久封禁需要验证当前管理员绑定邮箱:' . $codeMsg, 'err');
                    redirect(admin_url('users', ['uid' => $uid]));
                }
            }
            DB::run('UPDATE ' . DB::table('users') . ' SET status = 0, ban_until = ?, mute_until = ? WHERE id = ?', [$until, '', $uid]);
            punishment_record($uid, 'ban', $reason, now(), $until, (int) $admin['id']);
            audit_log('user_ban', 'UID ' . $uid . ' 至 ' . $until . ' ' . $reason);
            if ($seconds <= 0) {
                // 永久封禁账号时,把该账号最近使用的 IP 与设备指纹一并送入木卫守护永久封禁。
                $banParts = account_ban_link_guard($uid, $reason, (int) $admin['id'], $target);
                flash($banParts ? '已永久封禁该账号,并同步封禁:' . implode('、', $banParts) : '已永久封禁该账号;暂无可联动的 IP / 设备记录');
            } else {
                flash('已封禁该账号至 ' . $until);
            }
        }
    }

    if ($act === 'unban') {
        DB::run('UPDATE ' . DB::table('users') . ' SET status = 1, ban_until = ? WHERE id = ?', ['', $uid]);
        punishment_mark_released($uid, 'ban');
        $guardReleased = guard_ban_release_account($uid);
        audit_log('user_unban', 'UID ' . $uid . ' 自动解除 IP/设备封禁 ' . (int) $guardReleased['total'] . ' 项');
        flash('已解封该账号' . ((int) $guardReleased['total'] > 0 ? ',并自动解除关联 IP/设备封禁 ' . (int) $guardReleased['total'] . ' 项' : ''));
    }

    if ($act === 'toggle_username') {
        if (is_admin($target)) {
            flash('管理员和超级管理员默认拥有修改用户名权限,无需使用此开关', 'err');
        } else {
            $allow = (int) ($target['can_rename_username'] ?? 0) === 1 ? 0 : 1;
            DB::run('UPDATE ' . DB::table('users') . ' SET can_rename_username = ? WHERE id = ?', [$allow, $uid]);
            flash($allow ? '已允许该用户自行修改登录用户名' : '已禁止该用户自行修改登录用户名');
        }
    }

    if ($act === 'toggle_protect') {
        if (!is_superadmin($admin)) {
            flash('只有超级管理员可以使用账号保护功能', 'err');
        } elseif ($uid === (int) $admin['id']) {
            flash('超级管理员不能对自己使用账号保护功能', 'err');
        } elseif (is_superadmin($target)) {
            flash('不能保护超级管理员账号', 'err');
        } else {
            $protect = input('protected') === '1' ? 1 : 0;
            $isTargetAdmin = ($target['role'] ?? '') === 'admin';
            DB::run('UPDATE ' . DB::table('users') . ' SET account_protected = ? WHERE id = ?', [$protect, $uid]);
            flash($protect
                ? '已开启' . ($isTargetAdmin ? '管理员保护' : '账号保护') . ':该用户不能自行修改密码和用户名,也不能通过邮箱找回密码;' . ($isTargetAdmin ? '该管理员无法自行解除,只能由超级管理员关闭。' : '')
                : '已解除' . ($isTargetAdmin ? '管理员保护' : '账号保护') . ',该用户可以自行修改密码和用户名,也可使用邮箱找回密码');
        }
    }

    if ($act === 'site_mute' || $act === 'site_unmute') {
        if ($uid === (int) $admin['id']) {
            flash('不能禁言自己', 'err');
        } elseif ($act === 'site_unmute') {
            DB::run('UPDATE ' . DB::table('users') . ' SET site_mute_until = ?, site_mute_reason = ? WHERE id = ?', ['', '', $uid]);
            punishment_mark_released($uid, 'site_mute');
            audit_log('site_unmute', 'UID ' . $uid);
            flash('已解除全站禁言');
        } else {
            $minutes = max(0, (int) input('minutes', 0));
            $until = $minutes > 0 ? date('Y-m-d H:i:s', time() + $minutes * 60) : '9999-12-31 23:59:59';
            $reason = mb_substr(trim((string) input('reason', '')), 0, 255);
            DB::run('UPDATE ' . DB::table('users') . ' SET site_mute_until = ?, site_mute_reason = ? WHERE id = ?', [$until, $reason, $uid]);
            punishment_record($uid, 'site_mute', $reason, now(), $until, (int) $admin['id']);
            audit_log('site_mute', 'UID ' . $uid . ' 至 ' . $until . ' ' . $reason);
            flash($minutes > 0 ? '已全站禁言至 ' . $until : '已永久全站禁言该用户');
        }
    }

    if ($act === 'mute' || $act === 'unmute') {
        if ($uid === (int) $admin['id']) {
            flash('不能禁言自己', 'err');
        } elseif ($act === 'unmute') {
            DB::run('UPDATE ' . DB::table('users') . ' SET mute_until = ? WHERE id = ?', ['', $uid]);
            punishment_mark_released($uid, 'mute');
            flash('已解除禁言');
        } else {
            $seconds = max(0, (int) input('duration', 0));
            $until = $seconds > 0 ? date('Y-m-d H:i:s', time() + $seconds) : '9999-12-31 23:59:59';
            $reason = mb_substr(trim((string) input('reason', '')), 0, 255);
            DB::run('UPDATE ' . DB::table('users') . ' SET mute_until = ? WHERE id = ?', [$until, $uid]);
            punishment_record($uid, 'mute', $reason, now(), $until, (int) $admin['id']);
            flash($seconds > 0 ? '已禁言该用户至 ' . $until : '已永久禁言该用户');
        }
    }

    if ($act === 'role') {
        if (!is_superadmin($admin)) {
            flash('只有超级管理员可以修改用户角色,管理员不能把普通用户设为管理员', 'err');
            redirect(admin_url('users', ['uid' => $uid]));
        }
        $role = input('role', 'user');
        $labels = role_options();
        if (!isset($labels[$role])) {
            flash('角色不合法', 'err');
        } elseif ($role === 'superadmin') {
            flash('超级管理员只能保留部署站长一个账号,不能新增或移交超级管理员', 'err');
        } elseif (is_installer_admin($target) && $role !== 'superadmin') {
            flash('部署页设置的管理员账号已锁死,不能移交或降级', 'err');
        } elseif (is_superadmin($target) && $role !== 'superadmin') {
            flash('超级管理员账号受保护,不能注销、降级或移交', 'err');
        } else {
            DB::run('UPDATE ' . DB::table('users') . ' SET role = ? WHERE id = ?', [$role, $uid]);
            flash('用户角色已更新为 ' . $labels[$role]);
        }
    }

    if ($act === 'save') {
        $nickname = mb_substr(trim((string) ($_POST['nickname'] ?? '')), 0, 30);
        $username = trim((string) ($_POST['username'] ?? ''));
        $gender = input('gender', is_official_account($target) ? (string) ($target['gender'] ?? 'secret') : 'secret');
        $email = trim((string) ($_POST['email'] ?? (is_official_account($target) ? (string) ($target['email'] ?? '') : '')));
        $bio = mb_substr(trim((string) ($_POST['bio'] ?? '')), 0, 200);
        $pointsSet = isset($_POST['points']);
        $newPoints = $pointsSet ? max(0, (int) $_POST['points']) : (int) ($target['points'] ?? 0);
        $oldPoints = (int) ($target['points'] ?? 0);
        $avatarUrl = trim((string) ($_POST['avatar_url'] ?? ''));
        if (is_official_account($target) && $username !== (string) $target['username']) {
            $username = (string) $target['username'];
            flash('官方固定账号的登录用户名固定为 101,不能修改', 'err');
        } elseif ($targetSuperLocked && $username !== (string) $target['username']) {
            $username = (string) $target['username'];
            flash('超级管理员保护锁已开启,无法修改用户名,请先关闭保护锁', 'err');
        } elseif ($targetProtectedAdminPeer && $username !== (string) $target['username']) {
            $username = (string) $target['username'];
            flash('该管理员受超级管理员保护,只有超级管理员可以修改其用户名', 'err');
        }
        $emailBlocked = '';
        if ($targetSuperLocked) {
            $emailBlocked = '超级管理员保护锁已开启,无法修改绑定邮箱,请先关闭保护锁';
        } elseif (($target['role'] ?? '') === 'admin' && !is_superadmin($admin) && $uid !== (int) $admin['id']) {
            $emailBlocked = '管理员不能修改其他管理员的绑定邮箱,只有超级管理员可以操作';
        }
        if ($emailBlocked !== '') {
            $email = (string) ($target['email'] ?? '');
            flash($emailBlocked, 'err');
        }
        if ($nickname === '') {
            flash('昵称不能为空', 'err');
        } elseif (!preg_match('/^[A-Za-z0-9_\x{4e00}-\x{9fa5}]{2,20}$/u', $username)) {
            flash('用户名需为 2-20 位中文、字母、数字或下划线', 'err');
        } elseif ($username !== (string) $target['username'] && DB::val('SELECT COUNT(*) FROM ' . DB::table('users') . ' WHERE username = ? AND id <> ?', [$username, $uid])) {
            flash('该用户名已被占用', 'err');
        } elseif (!nickname_check($nickname, $target)[0]) {
            flash(nickname_check($nickname, $target)[1], 'err');
        } elseif ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            flash('邮箱格式不正确', 'err');
        } else {
            $data = [
                'nickname' => $nickname,
                'username' => $username,
                'gender'   => in_array($gender, ['male', 'female', 'secret'], true) ? $gender : 'secret',
                'email'    => $email,
                'bio'      => $bio,
                'can_rename_username' => is_admin($target) ? 1 : (input('can_rename_username') === '1' ? 1 : 0),
                'avatar_free_limit' => max(0, min(9999, (int) ($_POST['avatar_free_limit'] ?? 3))),
                'avatar_unlimited' => input('avatar_unlimited') === '1' ? 1 : 0,
                'avatar_change_cost' => max(0, min(999999, (int) ($_POST['avatar_change_cost'] ?? 20))),
                'username_free_limit' => max(0, min(9999, (int) ($_POST['username_free_limit'] ?? 0))),
                'username_unlimited' => input('username_unlimited') === '1' ? 1 : 0,
                'username_change_cost' => max(0, min(999999, (int) ($_POST['username_change_cost'] ?? 50))),
            ];
            if (is_official_account($target)) {
                $data['username'] = '101';
                $data['can_rename_username'] = 0;
                $data['username_free_limit'] = 0;
                $data['username_unlimited'] = 0;
                $data['avatar_free_limit'] = (int) ($target['avatar_free_limit'] ?? 3);
                $data['avatar_unlimited'] = (int) ($target['avatar_unlimited'] ?? 0);
                $data['avatar_change_cost'] = (int) ($target['avatar_change_cost'] ?? 20);
                $data['username_change_cost'] = (int) ($target['username_change_cost'] ?? 50);
            }
            if ($pointsSet) {
                $data['points'] = $newPoints;
            }
            $targetRole = (string) ($target['role'] ?? '');
            if ($targetRole === 'admin' && is_superadmin($admin) && isset($_POST['plugin_access'])) {
                $pluginAccess = (string) input('plugin_access', 'all');
                if (in_array($pluginAccess, ['all', 'view', 'hidden'], true)) {
                    $data['plugin_access'] = $pluginAccess;
                }
            }
            $canSetFeaturePerms = $targetRole !== 'superadmin'
                && ($targetRole !== 'admin' || is_superadmin($admin));
            if ($canSetFeaturePerms) {
                $postedFeatures = isset($_POST['features']) && is_array($_POST['features']) ? array_map('strval', $_POST['features']) : [];
                if (is_official_account($target)) {
                    $postedFeatures = array_values(array_intersect($postedFeatures, ['friends', 'verify']));
                }
                $featureMap = [];
                $allEnabled = true;
                foreach (site_feature_registry() as $featureKey => $featureName) {
                    $enabled = in_array($featureKey, $postedFeatures, true) ? 1 : 0;
                    $featureMap[$featureKey] = $enabled;
                    if ($enabled !== 1) $allEnabled = false;
                }
                $data['feature_perms'] = $allEnabled ? '' : json_encode($featureMap, JSON_UNESCAPED_UNICODE);
            }
            try {
                if (!empty($_FILES['avatar']['name'])) {
                    $stored = avatar_store_upload('avatar');
                    if (strpos((string) $target['avatar'], 'uploads/') === 0) {
                        delete_upload($target['avatar']);
                    }
                    $data['avatar'] = $stored['path'];
                } elseif ($avatarUrl !== '') {
                    if (!preg_match('#^https?://#i', $avatarUrl)) {
                        throw new Exception('网络头像需以 http:// 或 https:// 开头');
                    }
                    if (strpos((string) $target['avatar'], 'uploads/') === 0) {
                        delete_upload($target['avatar']);
                    }
                    $data['avatar'] = $avatarUrl;
                }
                DB::update('users', $data, 'id = ?', [$uid]);
                $pointDelta = $newPoints - $oldPoints;
                if ($pointsSet && $pointDelta > 0) {
                    DB::run('UPDATE ' . DB::table('users') . ' SET exp = exp + ? WHERE id = ?', [$pointDelta, $uid]);
                }
                if ($pointsSet && $pointDelta !== 0) {
                    DB::insert('point_logs', [
                        'user_id' => (int) $uid,
                        'action' => 'admin_edit',
                        'delta' => $pointDelta,
                        'note' => '管理员在用户资料中调整积分',
                        'created_at' => now(),
                    ]);
                    flash('用户资料已保存,积分已改为 ' . $newPoints);
                } else {
                    flash('用户资料已保存');
                }
            } catch (Exception $e) {
                flash('保存失败:' . $e->getMessage(), 'err');
            }
        }
    }

    if ($act === 'official_frame') {
        if (!$target || !is_official_account($target)) {
            flash('只有官方固定账号可以设置个人卡外观', 'err');
            redirect(admin_url('users'));
        }
        $frame = trim((string) input('frame', ''));
        if (!array_key_exists($frame, profile_frame_options())) {
            flash('请选择有效的卡片边框', 'err');
        } else {
            DB::update('users', ['profile_frame' => $frame], 'id = ?', [$uid]);
            audit_log('official_card_frame', 'UID ' . $uid . ' 官方通知号个人卡边框更新');
            flash('个人卡边框已更新');
        }
        redirect(admin_url('users', ['uid' => $uid, 'appearance' => 1]));
    }

    if ($act === 'official_bg') {
        if (!$target || !is_official_account($target)) {
            flash('只有官方固定账号可以设置个人卡外观', 'err');
            redirect(admin_url('users'));
        }
        $bgAction = (string) input('bg_action', 'save');
        $blur = max(0, min(20, (int) input('bg_blur', 0)));
        $oldBg = (string) ($target['profile_bg'] ?? '');
        $oldVideo = (string) ($target['profile_bg_video'] ?? '');
        if ($bgAction === 'clear') {
            DB::update('users', ['profile_bg' => '', 'profile_bg_video' => '', 'profile_bg_blur' => 0], 'id = ?', [$uid]);
            profile_bg_delete_media_file($oldBg);
            profile_bg_delete_media_file($oldVideo);
            audit_log('official_card_bg', 'UID ' . $uid . ' 官方通知号个人卡背景清除');
            flash('个人卡背景已恢复默认');
            redirect(admin_url('users', ['uid' => $uid, 'appearance' => 1]));
        }
        $bgKind = (string) input('bg_kind', 'image');
        $newBg = '';
        $newVideo = '';
        try {
            if ($bgKind === 'video') {
                if (!empty($_FILES['bg_video_file']['name'])) {
                    $newVideo = profile_bg_store_admin_video('bg_video_file');
                }
            } else {
                $bgData = (string) ($_POST['bg_data'] ?? '');
                if ($bgData !== '') {
                    $newBg = profile_bg_store_data_image($bgData, $uid);
                }
            }
            $data = ['profile_bg_blur' => $blur];
            if ($newBg !== '' || $newVideo !== '') {
                $data['profile_bg'] = $newBg;
                $data['profile_bg_video'] = $newVideo;
            }
            DB::update('users', $data, 'id = ?', [$uid]);
            if ($newBg !== '' || $newVideo !== '') {
                if ($oldBg !== $newBg) { profile_bg_delete_media_file($oldBg); }
                if ($oldVideo !== $newVideo) { profile_bg_delete_media_file($oldVideo); }
                audit_log('official_card_bg', 'UID ' . $uid . ' 官方通知号个人卡背景更新');
                flash('个人卡背景已更新');
            } else {
                flash('背景清晰度已调整');
            }
        } catch (Exception $e) {
            flash('保存个人卡背景失败:' . $e->getMessage(), 'err');
        }
        redirect(admin_url('users', ['uid' => $uid, 'appearance' => 1]));
    }

    if ($act === 'password') {
        $new = (string) ($_POST['new_password'] ?? '');
        if ($targetSuperLocked) {
            flash('超级管理员保护锁已开启,无法重置密码,请先关闭保护锁', 'err');
        } elseif ($targetProtectedAdminPeer) {
            flash('该管理员受超级管理员保护,只有超级管理员可以重置其密码', 'err');
        } elseif (strlen($new) < 6) {
            flash('新密码至少 6 位', 'err');
        } else {
            DB::run('UPDATE ' . DB::table('users') . ' SET password = ? WHERE id = ?', [password_hash($new, PASSWORD_DEFAULT), $uid]);
            flash('已重置该用户密码');
        }
    }

    if ($act === 'delete_send_code') {
        if (!$target || $uid === (int) $admin['id'] || is_superadmin($target)
            || (!is_superadmin($admin) && is_admin($target))) {
            flash('当前账号不能执行删除操作', 'err');
        } else {
            list($ok, $msg) = account_delete_code_send($admin, 'admin_delete_account');
            flash($ok ? '删除验证码已发送到你的绑定邮箱' : $msg, $ok ? 'ok' : 'err');
        }
        redirect(admin_url('users', ['uid' => $uid]));
    }

    if ($act === 'restore_initial') {
        if (!is_superadmin($admin) && is_admin($target)) {
            flash('普通管理员不能恢复管理员账号的注册资料,请由超级管理员操作', 'err');
        } elseif (is_installer_admin($target) || is_official_account($target)) {
            flash('该账号受保护,不能一键恢复注册资料', 'err');
        } else {
            list($ok, $msg, $changed, $skipped) = user_restore_initial_profile($uid);
            flash($msg, $ok ? 'ok' : 'err');
            if (!empty($skipped)) {
                flash('未恢复:' . implode(';', $skipped), 'err');
            }
        }
        redirect(admin_url('users', ['uid' => $uid]));
    }

    if ($act === 'delete') {
        if ($uid === (int) $admin['id']) {
            flash('不能删除自己的账号', 'err');
        } elseif (is_superadmin($target)) {
            flash('超级管理员账号受保护,不能删除', 'err');
        } elseif (!is_superadmin($admin) && is_admin($target)) {
            flash('普通管理员不能删除管理员账号,请由超级管理员操作', 'err');
        } else {
            list($codeOk, $codeMsg) = account_delete_code_check($admin, input('delete_email_code'), 'admin_delete_account');
            if (!$codeOk) {
                flash($codeMsg, 'err');
            } else {
                try {
                    user_delete_account($uid, (int) $admin['id']);
                    flash('账号及全部内容已删除,资料已进入「被删除账号恢复」存档');
                } catch (Exception $e) {
                    flash('删除失败:' . $e->getMessage(), 'err');
                }
            }
        }
        redirect(admin_url('users', ['uid' => $uid]));
    }

    if ($act === 'impersonate') {
        if (is_admin($target) && $admin['role'] !== 'superadmin') {
            flash('只有超级管理员可以代登录管理员账号', 'err');
        } else {
            $_SESSION['imp_uid'] = $uid;
            flash('已切换为 ' . display_name($target) . ' 的身份');
        }
        redirect(page_url('home'));
    }

    redirect(admin_url('users', $uid ? ['uid' => $uid] : []));
}

$q = trim((string) input('q', ''));
$where = '1';
$params = [];
if ($q !== '') {
    $where = '(username LIKE ? OR nickname LIKE ? OR email LIKE ?)';
    $params = ['%' . $q . '%', '%' . $q . '%', '%' . $q . '%'];
}
DB::run('UPDATE ' . DB::table('users') . " SET status = 1, ban_until = '' WHERE status = 0 AND ban_until <> '' AND ban_until <= ?", [now()]);
DB::run('UPDATE ' . DB::table('users') . " SET mute_until = '' WHERE mute_until <> '' AND mute_until <= ?", [now()]);
$total = (int) DB::val('SELECT COUNT(*) FROM ' . DB::table('users') . ' WHERE ' . $where, $params, 0);
$pager = paginate($total, 20);
$users = DB::all('SELECT * FROM ' . DB::table('users') . ' WHERE ' . $where . ' ORDER BY is_official DESC, id DESC LIMIT ' . $pager['limit'] . ' OFFSET ' . $pager['offset'], $params);
$editUser = (int) input('uid') > 0 ? user_by_id((int) input('uid')) : null;
$canEditFeaturePerms = $editUser
    && ($editUser['role'] ?? '') !== 'superadmin'
    && (($editUser['role'] ?? '') !== 'admin' || is_superadmin($admin));
$editOfficial = $editUser && is_official_account($editUser);
$verifyMode = $editUser && input('verify') === '1';
$appearanceMode = $editUser && $editOfficial && input('appearance') === '1';
$editSuperLocked = $editUser && is_superadmin($editUser) && superadmin_lock_is_on();
$editEmailLocked = $editUser && ($editSuperLocked
    || (($editUser['role'] ?? '') === 'admin' && !is_superadmin($admin) && (int) $editUser['id'] !== (int) $admin['id']));
if ($editUser && ($editUser['role'] ?? '') === 'superadmin' && ($admin['role'] ?? '') !== 'superadmin') {
    flash('管理员不能编辑超级管理员', 'err');
    redirect(admin_url('users'));
}
if ($appearanceMode) {
    require __DIR__ . '/user_appearance.php';
    return;
}
?>
<?php if ($verifyMode): ?>
<?php
  $vStyles = verify_styles();
  $vStyle = verify_style_of($editUser);
  $vType = trim((string) ($editUser['verify_type'] ?? '')) !== '' ? (string) $editUser['verify_type'] : 'official';
  $vEnabled = (int) ($editUser['verified'] ?? 0) === 1;
?>
<section class="panel admin-verify-page">
  <div class="admin-verify-page-head">
    <div>
      <h1>认证中心</h1>
      <p>正在设置 <b><?= e(display_name($editUser)) ?></b> 的认证信息,保存后立即在前台展示。</p>
    </div>
    <a class="link-btn" href="<?= e(admin_url('users', ['uid' => (int) $editUser['id']])) ?>">返回用户编辑</a>
  </div>

  <div class="admin-verify-current">
    <span>当前状态</span>
    <?php if ($vEnabled): ?>
      <?= verify_badge($editUser) ?><b><?= e(verify_title_of($editUser)) ?></b>
    <?php else: ?>
      <b class="muted">未显示认证 V</b>
    <?php endif; ?>
  </div>

  <form method="post" class="verify-form-card admin-verify-form">
    <?= csrf_field() ?>
    <input type="hidden" name="act" value="verify_save">
    <input type="hidden" name="uid" value="<?= (int) $editUser['id'] ?>">

    <div class="admin-verify-toggle">
      <div>
        <label>显示认证 V</label>
        <small>关闭后前台不再显示 V 标识,已填写的款式、头衔和说明会保留。</small>
      </div>
      <label class="toggle-switch">
        <input type="checkbox" name="verified" value="1" <?= $vEnabled ? 'checked' : '' ?>>
        <span class="toggle-track"><span class="toggle-thumb"></span></span>
      </label>
    </div>

    <div class="admin-verify-preview" id="verifyPreview">
      <div class="verify-preview-caption">
        <span>前台效果预览</span>
        <small id="verifyPreviewStatus"><?= $vEnabled ? '认证 V 已开启' : '认证 V 已关闭' ?></small>
      </div>
      <div class="verify-preview-row">
        <div class="verify-preview-avatar-wrap">
          <?= avatar_html($editUser, 'verify-preview-avatar') ?>
          <span class="avatar-v v-<?= e($vStyle) ?>" id="verifyPreviewAvatarV">V</span>
        </div>
        <div class="verify-preview-info">
          <div class="verify-preview-name-line">
            <strong id="verifyPreviewName"><?= e(display_name($editUser)) ?></strong>
            <span class="v-badge v-<?= e($vStyle) ?>" id="verifyPreviewBadge" title="<?= e(verify_title_of($editUser)) ?>">V<span class="v-txt"><?= e($vStyles[$vStyle][0] ?? '认证V') ?></span></span>
          </div>
          <p class="verify-preview-meta"><span id="verifyPreviewType"><?= $vType === 'professional' ? '职业认证' : '官方认证' ?></span> · <span id="verifyPreviewTitle"><?= e(verify_title_of($editUser)) ?></span></p>
        </div>
      </div>
    </div>

    <label class="vf-label admin-verify-type-label">认证类型</label>
    <div class="type-pills">
      <label class="type-pill <?= $vType === 'official' ? 'on' : '' ?>">
        <input type="radio" name="verify_type" value="official" <?= $vType === 'official' ? 'checked' : '' ?>> 官方认证
      </label>
      <label class="type-pill <?= $vType === 'professional' ? 'on' : '' ?>">
        <input type="radio" name="verify_type" value="professional" <?= $vType === 'professional' ? 'checked' : '' ?>> 职业认证
      </label>
    </div>

    <label class="vf-label">认证款式 / 颜色</label>
    <div class="style-grid">
      <?php foreach ($vStyles as $styleKey => $styleMeta): ?>
        <label class="style-pill style-<?= $styleKey ?> <?= $vStyle === $styleKey ? 'on' : '' ?>">
          <input type="radio" name="verify_style" value="<?= e($styleKey) ?>" <?= $vStyle === $styleKey ? 'checked' : '' ?>>
          <i class="v-dot">V</i><span><?= e($styleMeta[0]) ?></span>
        </label>
      <?php endforeach; ?>
    </div>

    <label class="vf-label">认证头衔(如「官方账号」)</label>
    <input type="text" name="verify_title" maxlength="60" value="<?= e($editUser['verify_title'] ?? '') ?>" placeholder="官方账号">

    <label class="vf-label">认证说明</label>
    <textarea name="verify_info" rows="3" maxlength="255" placeholder="例如:木漏茶室官方通知账号"><?= e($editUser['verify_info'] ?? '') ?></textarea>

    <button class="btn-primary block" type="submit">保存认证信息</button>
    <p class="auth-tip">认证仅用于身份标识,不代表平台对内容的担保。</p>
  </form>
  <script>
  (function () {
    var preview = document.getElementById('verifyPreview');
    if (!preview) return;
    var badge = document.getElementById('verifyPreviewBadge');
    var avatarV = document.getElementById('verifyPreviewAvatarV');
    var toggle = document.querySelector('.admin-verify-form input[name=verified]');
    var titleInput = document.querySelector('.admin-verify-form input[name=verify_title]');
    var typeText = document.getElementById('verifyPreviewType');
    var titleText = document.getElementById('verifyPreviewTitle');
    var status = document.getElementById('verifyPreviewStatus');
    function checkedStyle() {
      var el = document.querySelector('.admin-verify-form input[name=verify_style]:checked');
      return el ? el.value : <?= json_encode($vStyle) ?>;
    }
    function checkedType() {
      var el = document.querySelector('.admin-verify-form input[name=verify_type]:checked');
      return el && el.value === 'professional' ? 'professional' : 'official';
    }
    function update() {
      var style = checkedStyle();
      var type = checkedType();
      badge.className = 'v-badge v-' + style;
      avatarV.className = 'avatar-v v-' + style;
      var title = titleInput && titleInput.value.trim() ? titleInput.value.trim() : (type === 'professional' ? '职业认证' : '官方认证');
      typeText.textContent = type === 'professional' ? '职业认证' : '官方认证';
      titleText.textContent = title;
      badge.title = title;
      var on = !!(toggle && toggle.checked);
      preview.classList.toggle('is-off', !on);
      status.textContent = on ? '认证 V 已开启' : '认证 V 已关闭';
      document.querySelectorAll('.admin-verify-form .type-pill').forEach(function (pill) {
        var input = pill.querySelector('input[name=verify_type]');
        pill.classList.toggle('on', !!(input && input.checked));
      });
      document.querySelectorAll('.admin-verify-form .style-pill').forEach(function (pill) {
        var input = pill.querySelector('input[name=verify_style]');
        pill.classList.toggle('on', !!(input && input.checked));
      });
    }
    document.querySelectorAll('.admin-verify-form input[name=verify_style], .admin-verify-form input[name=verify_type]').forEach(function (el) {
      el.addEventListener('change', update);
    });
    if (toggle) toggle.addEventListener('change', update);
    if (titleInput) titleInput.addEventListener('input', update);
    update();
  })();
  </script>
</section>
<?php return; ?>
<?php endif; ?>

<div class="admin-head">
  <div><h1>用户管理</h1><p>共 <?= $total ?> 位茶客 · 可添加用户、封禁、改角色、改资料、重置密码与代登录 · 登录记录</p></div>
  <div class="admin-head-tools">
    <?php if (!$editUser): ?>
    <button class="btn-primary btn-mini" type="button" id="addUserOpen">+ 添加用户</button>
    <?php if (is_superadmin($admin)): ?>
    <button class="btn-mini" type="button" data-add-role="admin">+ 添加管理员</button>
    <?php endif; ?>
    <?php endif; ?>
    <a class="btn-mini ghost" href="<?= e(admin_url('login_logs')) ?>">登录记录</a>
    <?php if (is_superadmin($admin)): ?><a class="btn-mini ghost" href="#deletedAccounts">账号恢复</a><?php endif; ?>
    <?php if (!$editUser): ?>
    <form method="post" class="inline-form" data-confirm="创建一个随机访客账号?用户名和初始密码会显示一次。">
      <?= csrf_field() ?>
      <input type="hidden" name="act" value="random_guest">
      <button class="btn-mini ghost" type="submit">随机访客注册</button>
    </form>
    <?php endif; ?>
    <form method="get" class="admin-search">
      <input type="hidden" name="page" value="admin">
      <input type="hidden" name="s" value="users">
      <input type="search" name="q" value="<?= e($q) ?>" placeholder="搜索用户名 / 昵称 / 邮箱">
      <button class="btn-mini" type="submit">搜索</button>
    </form>
  </div>
</div>

<section class="modal" id="addUserModal" hidden>
  <div class="modal-mask"></div>
  <div class="modal-card add-user-modal">
    <div class="sa-lock-modal-head">
      <h3>添加用户</h3>
      <button type="button" class="readers-close" data-close>×</button>
    </div>
    <p class="muted">像注册页一样创建账号;角色范围由你的权限决定。</p>
    <form method="post" class="auth-form grid2">
      <?= csrf_field() ?>
      <input type="hidden" name="act" value="create">
      <div class="full"><label>用户名(2-20 位,支持中文)</label><input type="text" name="username" required autocomplete="off"></div>
      <div class="full"><label>昵称(展示用,可留空)</label><input type="text" name="nickname" maxlength="64" autocomplete="off"></div>
      <div><label>密码(至少 6 位)</label><input type="password" name="password" required autocomplete="new-password"></div>
      <div><label>确认密码</label><input type="password" name="password2" required autocomplete="new-password"></div>
      <div><label>性别</label><select name="gender"><option value="secret">保密</option><option value="female">女</option><option value="male">男</option></select></div>
      <div><label>邮箱(可留空)</label><input type="email" name="email" autocomplete="off"></div>
      <div class="full"><label>账号角色</label>
        <select name="role" id="addUserRole">
          <?php foreach ($creatableRoles as $roleKey): ?>
            <option value="<?= e($roleKey) ?>" <?= $roleKey === 'user' ? 'selected' : '' ?>><?= e(role_label($roleKey)) ?></option>
          <?php endforeach; ?>
        </select>
        <small class="field-tip"><?= is_superadmin($admin) ? '超级管理员只有一个,固定为部署站长账号;这里只能添加普通用户、版主、贵宾和管理员。' : '管理员只能添加普通用户、版主、贵宾,不能添加管理员。' ?></small>
      </div>
      <div class="full modal-actions"><button type="button" class="btn-mini ghost" data-close>取消</button><button class="btn-primary" type="submit">创建用户</button></div>
    </form>
  </div>
</section>
<script>
(function(){
  var b=document.getElementById('addUserOpen'),m=document.getElementById('addUserModal'),r=document.getElementById('addUserRole');
  function open(role){
    if(!m)return;
    if(r&&role){for(var i=0;i<r.options.length;i++){if(r.options[i].value===role){r.selectedIndex=i;break;}}}
    m.hidden=false;document.body.classList.add('crop-open');
  }
  if(b&&m){b.addEventListener('click',function(){open('user');});}
  document.querySelectorAll('[data-add-role]').forEach(function(btn){
    btn.addEventListener('click',function(){open(btn.getAttribute('data-add-role'));});
  });
})();
</script>

<?php if (is_superadmin($admin) && (!$editUser || is_superadmin($editUser))): $saLockOn = superadmin_lock_is_on(); ?>
<section class="panel sa-lock-panel">
  <div class="sa-lock-head">
    <div class="sa-lock-copy">
      <span class="sa-lock-kicker">SUPERADMIN SECURITY</span>
      <h2>超级管理员保护锁</h2>
      <p>开启后,超级管理员不能自行修改用户名和密码;关闭保护锁必须输入 6 位安全码。忘记安全码时,可验证超级管理员绑定邮箱后解锁。</p>
    </div>
    <button type="button" class="sa-lock-switch" id="saLockSwitch" data-on="<?= $saLockOn ? '1' : '0' ?>" aria-pressed="<?= $saLockOn ? 'true' : 'false' ?>">
      <span class="sa-lock-track"><span class="sa-lock-thumb"></span></span>
      <span class="sa-lock-state"><?= $saLockOn ? '已开启' : '未开启' ?></span>
    </button>
  </div>
  <div class="sa-lock-meta">
    <span class="status-pill <?= $saLockOn ? 'ok' : 'bad' ?>"><?= $saLockOn ? '保护中' : '未保护' ?></span>
    <span><?= $saLockOn ? '用户名和密码已锁定,需安全码或邮箱验证后关闭。' : '开启后可用于防止超级管理员账号被误改或被盗改。' ?></span>
  </div>
  <?php if ($saLockOn && !empty($_SESSION['sa_lock_email_sent'])): ?>
    <button type="button" class="btn-mini ghost sa-lock-email-entry" id="saLockEmailOpen">输入邮箱验证码解锁</button>
  <?php endif; ?>
</section>

<section class="modal" id="saLockEnableModal" hidden>
  <div class="modal-mask"></div>
  <div class="modal-card sa-lock-modal">
    <div class="sa-lock-modal-head">
      <h3>开启超级管理员保护锁</h3>
      <button type="button" class="readers-close" data-close>×</button>
    </div>
    <p class="muted">请设置 6 位数字安全码。开启后,修改超级管理员用户名和密码前必须先关闭保护锁。</p>
    <form method="post">
      <?= csrf_field() ?>
      <input type="hidden" name="act" value="sa_lock_enable">
      <label>6 位安全码</label>
      <input class="sa-code-input" type="password" name="code" inputmode="numeric" autocomplete="new-password" maxlength="6" pattern="[0-9]{6}" placeholder="请输入 6 位数字" required>
      <label>再次输入安全码</label>
      <input class="sa-code-input" type="password" name="code2" inputmode="numeric" autocomplete="new-password" maxlength="6" pattern="[0-9]{6}" placeholder="请再次输入" required>
      <div class="modal-actions">
        <button type="button" class="btn-mini ghost" data-close>取消</button>
        <button type="submit" class="btn-primary">开启保护锁</button>
      </div>
    </form>
  </div>
</section>

<section class="modal" id="saLockDisableModal" hidden>
  <div class="modal-mask"></div>
  <div class="modal-card sa-lock-modal">
    <div class="sa-lock-modal-head">
      <h3>关闭超级管理员保护锁</h3>
      <button type="button" class="readers-close" data-close>×</button>
    </div>
    <p class="muted">请输入开启保护锁时设置的 6 位安全码。连续输错 5 次会锁定 10 分钟。</p>
    <form method="post">
      <?= csrf_field() ?>
      <input type="hidden" name="act" value="sa_lock_disable">
      <label>6 位安全码</label>
      <input class="sa-code-input" type="password" name="code" inputmode="numeric" autocomplete="off" maxlength="6" pattern="[0-9]{6}" placeholder="请输入 6 位数字" required>
      <div class="modal-actions">
        <button type="button" class="btn-mini ghost" data-close>取消</button>
        <button type="submit" class="btn-primary">确认关闭</button>
      </div>
    </form>
    <div class="sa-lock-divider"></div>
    <p class="muted">忘记安全码?可发送验证邮件到超级管理员绑定邮箱,验证通过后自动关闭保护锁。</p>
    <div class="sa-lock-actions">
      <button type="button" class="btn-mini ghost" id="saLockEmailEntry">使用邮箱验证码解锁</button>
    </div>
  </div>
</section>

<section class="modal" id="saLockEmailModal" hidden>
  <div class="modal-mask"></div>
  <div class="modal-card sa-lock-modal">
    <div class="sa-lock-modal-head">
      <h3>忘记安全码 · 邮箱验证解锁</h3>
      <button type="button" class="readers-close" data-close>×</button>
    </div>
    <p class="muted">验证码会发送到超级管理员绑定的邮箱,10 分钟内有效。若站点未配置 SMTP,验证码也会记录在 <code>data/mail.log</code>。</p>
    <form method="post" id="saLockEmailForm">
      <?= csrf_field() ?>
      <input type="hidden" name="act" value="sa_lock_email_unlock">
      <label>邮箱验证码</label>
      <div class="sa-code-row">
        <input class="sa-code-input" type="text" name="email_code" inputmode="numeric" autocomplete="one-time-code" maxlength="6" pattern="[0-9]{6}" placeholder="请输入邮件中的 6 位验证码" required>
        <button type="submit" class="btn-primary sa-code-confirm" id="saLockEmailConfirm">确认</button>
      </div>
      <div class="sa-email-status" id="saLockEmailStatus" aria-live="polite"></div>
      <button type="button" class="btn-mini ghost sa-email-send" id="saLockSendEmail">发送验证码</button>
    </form>
    <p class="sa-email-note">验证码正确并点击「确认」后,保护锁会自动关闭。</p>
  </div>
</section>
<?php endif; ?>

<?php if ($editUser): ?>
    <div class="crop-modal admin-avatar-crop" id="adminAvatarCropModal" hidden>
      <div class="crop-dialog" role="dialog" aria-modal="true" aria-labelledby="adminAvatarCropTitle">
        <div class="crop-head">
          <strong id="adminAvatarCropTitle">裁剪头像</strong>
          <button type="button" class="crop-x" id="adminAvatarCropClose" aria-label="关闭">×</button>
        </div>
        <p class="crop-tip">拖动图片调整位置,可缩放;方框内就是头像最终展示区域。确认后会以 512×512 PNG 上传。</p>
        <div class="crop-stage reg-crop-stage" id="adminAvatarCropStage"><img id="adminAvatarCropImage" alt=""></div>
        <div class="crop-zoom"><span>缩放</span><input type="range" id="adminAvatarCropZoom" min="1" max="3" step="0.01" value="1"><b id="adminAvatarCropZoomText">1.0×</b></div>
        <div class="crop-actions">
          <button type="button" class="btn-mini ghost" id="adminAvatarCropCancel">取消</button>
          <button type="button" class="btn-primary crop-apply" id="adminAvatarCropApply">完成并上传</button>
        </div>
      </div>
    </div>

<section class="modal admin-user-edit-modal" id="userEditModal">
  <div class="modal-mask" data-user-edit-close></div>
  <div class="modal-card admin-user-edit-card" role="dialog" aria-modal="true" aria-labelledby="userEditTitle">
    <div class="sa-lock-modal-head admin-user-edit-head">
      <h3 id="userEditTitle">编辑用户 · <?= e(display_name($editUser)) ?><?php if ((int) ($editUser['verified'] ?? 0) === 1): ?> <?= verify_badge($editUser) ?><?php endif; ?></h3>
      <a class="readers-close" href="<?= e(admin_url('users')) ?>" data-user-edit-close aria-label="关闭">×</a>
    </div>
    <div class="admin-user-edit-body edit-panel">
  <?php if ($editOfficial): ?>
  <?php
    $editFrame = profile_frame_of($editUser);
    $editFrameLabel = profile_frame_options()[$editFrame] ?? '默认无边框';
    $editBg = trim((string) ($editUser['profile_bg'] ?? ''));
    $editVideo = trim((string) ($editUser['profile_bg_video'] ?? ''));
    $editBlur = max(0, min(20, (int) ($editUser['profile_bg_blur'] ?? 0)));
    $editBgUrl = $editBg !== '' ? upload_url($editBg) : '';
    $editVideoUrl = $editVideo !== '' ? upload_url($editVideo) : '';
  ?>
  <?php endif; ?>
  <form method="post" enctype="multipart/form-data" class="form-card">
    <?= csrf_field() ?>
    <input type="hidden" name="act" value="save">
    <input type="hidden" name="uid" value="<?= (int) $editUser['id'] ?>">
    <div class="avatar-edit avatar-edit-top avatar-edit-admin">
      <div class="admin-avatar-preview<?= $editOfficial ? ' admin-avatar-preview-clickable' : '' ?>" id="adminAvatarPreview"<?= $editOfficial ? ' data-avatar-clickable="1" role="button" tabindex="0" title="点击修改头像" aria-label="点击修改头像"' : '' ?>><?php if ($editOfficial): ?><span class="avatar-v-wrap admin-avatar-vwrap"><?= avatar_html($editUser) ?><?= verify_dot_html($editUser) ?></span><?php else: ?><?= avatar_html($editUser) ?><?php endif; ?></div>
      <div class="admin-avatar-fields">
        <label class="admin-avatar-caption">修改头像(图片 <?= avatar_max_mb('image') ?>MB / 视频 <?= avatar_max_mb('video') ?>MB)</label>
        <small class="avatar-format-hint">支持图片 / GIF / 动态 WebP / 视频 · 选择后保存生效</small>
        <input type="file" name="avatar" id="adminAvatarInput" class="avatar-file-input" accept="image/*,video/mp4,video/webm,video/quicktime,.m4v,.ogv" data-avatar-max-image="<?= avatar_max_bytes('image') ?>" data-avatar-max-video="<?= avatar_max_bytes('video') ?>">
        <button type="button" class="avatar-upload-zone" id="adminAvatarZone" aria-label="拖拉或点击上传头像">
          <span class="auz-icon" aria-hidden="true">+</span>
          <strong>拖拉头像到此处,或点击选择文件</strong>
        </button>
        <label>或网络头像链接</label><input type="url" name="avatar_url" placeholder="https://">
        <small class="muted" style="display:block;margin-top:6px">头像修改放在昵称之前;管理员与超级管理员不受换头像次数限制。</small>
      </div>
    </div>
    <script>
    (function () {
      var input = document.getElementById('adminAvatarInput');
      var zone = document.getElementById('adminAvatarZone');
      var preview = document.getElementById('adminAvatarPreview');
      var modal = document.getElementById('adminAvatarCropModal');
      var stage = document.getElementById('adminAvatarCropStage');
      var img = document.getElementById('adminAvatarCropImage');
      var zoom = document.getElementById('adminAvatarCropZoom');
      var zoomText = document.getElementById('adminAvatarCropZoomText');
      if (!input || !zone || !preview || !modal || !stage || !img) return;
      var maxImage = parseInt(input.getAttribute('data-avatar-max-image') || '209715200', 10);
      var maxVideo = parseInt(input.getAttribute('data-avatar-max-video') || '524288000', 10);
      var imageExt = /\.(jpg|jpeg|png|webp|gif|heic|heif|avif|svg|bmp)$/i;
      var videoExt = /\.(mp4|m4v|webm|ogv|mov)$/i;
      var st = { base: 1, scale: 1, x: 0, y: 0, vw: 0, vh: 0, drag: false, px: 0, py: 0, url: '' };
      var previewUrl = '';

      function isVideo(f) { return !!(f && ((f.type && f.type.indexOf('video/') === 0) || videoExt.test(f.name || ''))); }
      function isImage(f) { return !!(f && ((f.type && f.type.indexOf('image/') === 0) || imageExt.test(f.name || ''))); }
      function isGif(f) { return !!(f && ((f.type === 'image/gif') || /\.gif$/i.test(f.name || ''))); }
      function clearPreviewUrl() { if (previewUrl) { URL.revokeObjectURL(previewUrl); previewUrl = ''; } }
      function showFile(f) {
        if (!f) return;
        clearPreviewUrl();
        previewUrl = URL.createObjectURL(f);
        preview.innerHTML = isVideo(f)
          ? '<video src="' + previewUrl + '" muted loop playsinline autoplay preload="metadata" aria-label="头像预览"></video>'
          : '<img src="' + previewUrl + '" alt="头像预览">';
      }
      function setInputFile(f) {
        try {
          var dt = new DataTransfer();
          dt.items.add(f);
          input.files = dt.files;
          return true;
        } catch (e) {
          return false;
        }
      }
      function clearInput() { input.value = ''; clearPreviewUrl(); }
      function checkFile(f) {
        if (!isImage(f) && !isVideo(f)) return false;
        return f.size <= (isVideo(f) ? maxVideo : maxImage);
      }
      function fit(center) {
        st.vw = stage.clientWidth; st.vh = stage.clientHeight;
        st.base = Math.max(st.vw / img.naturalWidth, st.vh / img.naturalHeight);
        st.scale = st.base * parseFloat(zoom.value || '1');
        if (center) {
          st.x = (st.vw - img.naturalWidth * st.scale) / 2;
          st.y = (st.vh - img.naturalHeight * st.scale) / 2;
        }
        clamp();
      }
      function clamp() {
        var dw = img.naturalWidth * st.scale, dh = img.naturalHeight * st.scale;
        st.x = Math.max(Math.min(0, st.vw - dw), Math.min(0, st.x));
        st.y = Math.max(Math.min(0, st.vh - dh), Math.min(0, st.y));
        img.style.width = dw + 'px'; img.style.height = dh + 'px';
        img.style.transform = 'translate(' + st.x + 'px,' + st.y + 'px)';
      }
      function openCrop(f) {
        if (st.url) URL.revokeObjectURL(st.url);
        st.url = URL.createObjectURL(f);
        var side = Math.max(220, Math.min(420, (stage.parentElement ? stage.parentElement.clientWidth : 420) - 8));
        stage.style.width = side + 'px'; stage.style.height = side + 'px';
        modal.hidden = false; document.body.classList.add('crop-open');
        zoom.value = '1'; zoomText.textContent = '1.0×';
        img.onload = function () { fit(true); };
        img.src = st.url;
      }
      function closeCrop() {
        modal.hidden = true; document.body.classList.remove('crop-open');
        if (st.url) { URL.revokeObjectURL(st.url); st.url = ''; }
        clearInput();
      }
      function applyCrop() {
        if (!img.naturalWidth) return;
        var canvas = document.createElement('canvas'); canvas.width = 512; canvas.height = 512;
        var c = canvas.getContext('2d');
        var sx = Math.max(0, -st.x / st.scale), sy = Math.max(0, -st.y / st.scale);
        var sw = Math.min(img.naturalWidth - sx, st.vw / st.scale), sh = Math.min(img.naturalHeight - sy, st.vh / st.scale);
        c.drawImage(img, sx, sy, sw, sh, 0, 0, 512, 512);
        var finish = function (blob) {
          if (!blob) { closeCrop(); return; }
          var cropped = new File([blob], 'avatar-crop.png', { type: 'image/png' });
          var ok = setInputFile(cropped);
          modal.hidden = true; document.body.classList.remove('crop-open');
          if (st.url) { URL.revokeObjectURL(st.url); st.url = ''; }
          if (!ok) {
            input.value = '';
            alert('当前浏览器不支持裁剪上传,请换用 Chrome 或 Edge。');
            return;
          }
          showFile(cropped);
        };
        if (canvas.toBlob) canvas.toBlob(finish, 'image/png');
        else { closeCrop(); alert('当前浏览器不支持裁剪上传,请换用 Chrome 或 Edge。'); }
      }
      function handleFile(f) {
        if (!f) return;
        if (!checkFile(f)) {
          input.value = '';
          alert((isVideo(f) ? '视频头像' : '图片') + '超过大小限制,请更换文件。');
          return;
        }
        if (isImage(f) && !isGif(f)) { openCrop(f); return; }
        if (!setInputFile(f)) { input.value = ''; alert('当前浏览器不支持该上传方式,请换用 Chrome 或 Edge。'); return; }
        showFile(f);
      }

      if (preview.getAttribute('data-avatar-clickable') === '1') {
        preview.addEventListener('click', function () { input.click(); });
        preview.addEventListener('keydown', function (e) {
          if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); input.click(); }
        });
      }
      zone.addEventListener('click', function () { input.click(); });
      input.addEventListener('change', function () {
        if (input.files && input.files[0]) handleFile(input.files[0]);
      });
      ['dragenter', 'dragover'].forEach(function (ev) {
        zone.addEventListener(ev, function (e) { e.preventDefault(); e.stopPropagation(); zone.classList.add('is-drop'); });
      });
      ['dragleave', 'dragend'].forEach(function (ev) {
        zone.addEventListener(ev, function (e) { e.preventDefault(); e.stopPropagation(); zone.classList.remove('is-drop'); });
      });
      zone.addEventListener('drop', function (e) {
        e.preventDefault(); e.stopPropagation(); zone.classList.remove('is-drop');
        var f = e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files[0];
        if (f) handleFile(f);
      });
      zoom.addEventListener('input', function () {
        zoomText.textContent = parseFloat(zoom.value || '1').toFixed(1) + '×';
        st.scale = st.base * parseFloat(zoom.value || '1'); clamp();
      });
      stage.addEventListener('pointerdown', function (e) { st.drag = true; st.px = e.clientX; st.py = e.clientY; stage.setPointerCapture(e.pointerId); });
      stage.addEventListener('pointermove', function (e) { if (!st.drag) return; st.x += e.clientX - st.px; st.y += e.clientY - st.py; st.px = e.clientX; st.py = e.clientY; clamp(); });
      stage.addEventListener('pointerup', function () { st.drag = false; });
      stage.addEventListener('pointercancel', function () { st.drag = false; });
      document.getElementById('adminAvatarCropApply').addEventListener('click', applyCrop);
      document.getElementById('adminAvatarCropCancel').addEventListener('click', closeCrop);
      document.getElementById('adminAvatarCropClose').addEventListener('click', closeCrop);
    })();
    </script>
    <div class="field-row">
      <div class="field"><label>昵称</label><input type="text" name="nickname" value="<?= e($editUser['nickname']) ?>" required></div>
      <div class="field"><label>用户名(登录账号<?= $editOfficial ? ' · 官方账号固定不可改' : '' ?>)</label><input type="text" name="username" maxlength="20" value="<?= e($editUser['username']) ?>" required <?= ($editSuperLocked || $editOfficial) ? 'readonly class="readonly-input"' : '' ?>>
          <?php if ($editOfficial): ?>
          <small class="muted" style="display:block;margin-top:6px">官方固定账号用户名固定为 101,登录账号不可修改。</small>
          <?php elseif (!is_admin($editUser)): ?>
          <label class="toggle-switch" style="margin-top:8px"><input type="checkbox" name="can_rename_username" value="1" <?= (int) ($editUser['can_rename_username'] ?? 0) === 1 ? 'checked' : '' ?>><span class="toggle-track"><span class="toggle-thumb"></span></span><span class="toggle-text">允许修改用户名(使用下方额度)</span></label>
          <?php else: ?>
          <small class="muted" style="display:block;margin-top:6px">管理员和超级管理员默认拥有修改用户名权限,无需开关。</small>
          <?php endif; ?>
        </div>
      <?php if (!$editOfficial): ?>
      <div class="field"><label>性别</label>
        <select name="gender">
          <option value="secret" <?= $editUser['gender'] === 'secret' ? 'selected' : '' ?>>保密</option>
          <option value="female" <?= $editUser['gender'] === 'female' ? 'selected' : '' ?>>女</option>
          <option value="male" <?= $editUser['gender'] === 'male' ? 'selected' : '' ?>>男</option>
        </select>
      </div>
      <div class="field"><label>积分</label><?php if (is_superadmin($editUser)): ?><input type="text" value="无限" disabled><?php else: ?><input type="number" name="points" min="0" max="99999999" value="<?= (int) $editUser['points'] ?>"><?php endif; ?></div>
      <?php endif; ?>
    </div>
    <?php if ($editOfficial): ?>
      <input type="hidden" name="gender" value="<?= e($editUser['gender']) ?>">
      <input type="hidden" name="email" value="<?= e($editUser['email']) ?>">
    <?php else: ?>
    <div class="field"><label>邮箱</label><input type="email" name="email" value="<?= e($editUser['email']) ?>" <?= $editEmailLocked ? 'readonly class="readonly-input"' : '' ?>><?php if ($editEmailLocked): ?><small class="muted"><?= $editSuperLocked ? '超级管理员保护锁已开启,需先关闭保护锁' : '管理员不能修改其他管理员的邮箱,只有超级管理员可以操作' ?></small><?php endif; ?></div>
    <?php endif; ?>
    <div class="field"><label>自我介绍</label><textarea name="bio" rows="2" maxlength="200"><?= e($editUser['bio']) ?></textarea></div>
    <?php if (!$editOfficial): ?>
    <div class="admin-verify-entry">
      <div class="admin-verify-entry-copy">
        <label>认证中心</label>
        <small>认证类型、V 款式 / 颜色、认证头衔和说明,点击进入设置。</small>
      </div>
      <div class="admin-verify-entry-status">
        <?php if ((int) ($editUser['verified'] ?? 0) === 1): ?>
          <?= verify_badge($editUser) ?><span><?= e(verify_title_of($editUser)) ?></span>
        <?php else: ?>
          <span class="muted">当前未显示认证 V</span>
        <?php endif; ?>
      </div>
      <a class="btn-ghost block" href="<?= e(admin_url('users', ['uid' => (int) $editUser['id'], 'verify' => 1])) ?>">认证中心</a>
    </div>
    <?php endif; ?>
    <div class="code" style="margin:2px 0 12px">最后访问 IP:<b><?= e(($editUser['last_ip'] ?? '') !== '' ? $editUser['last_ip'] : '未记录') ?></b><?php if (!empty($editUser['last_ip_at'])): ?> · <?= e($editUser['last_ip_at']) ?><?php endif; ?></div>
    <?php if (!is_admin($editUser) && !$editOfficial): ?>
    <div class="field-row" style="margin-top:6px">
      <div class="field" style="flex:1 1 100%">
        <label>头像 / 用户名修改额度</label>
        <p class="muted" style="margin:0">已累计使用:头像 <b><?= profile_change_used_count((int) $editUser['id'], 'avatar') ?></b> 次,用户名 <b><?= profile_change_used_count((int) $editUser['id'], 'username') ?></b> 次。免费额度用完后按下方积分收费;管理员和超级管理员不受限。</p>
      </div>
    </div>
    <div class="field-row">
      <div class="field">
        <label>免费换头像次数</label>
        <input type="number" name="avatar_free_limit" min="0" max="9999" value="<?= (int) ($editUser['avatar_free_limit'] ?? 3) ?>">
        <label class="check-line"><input type="checkbox" name="avatar_unlimited" value="1" <?= (int) ($editUser['avatar_unlimited'] ?? 0) === 1 ? 'checked' : '' ?>> 头像修改不限次数</label>
      </div>
      <div class="field">
        <label>头像超出后每次扣积分</label>
        <input type="number" name="avatar_change_cost" min="0" max="999999" value="<?= (int) ($editUser['avatar_change_cost'] ?? 20) ?>">
        <small class="muted">0 表示超出后也不扣积分。</small>
      </div>
    </div>
    <div class="field-row">
      <div class="field">
        <label>免费改用户名次数</label>
        <input type="number" name="username_free_limit" min="0" max="9999" value="<?= (int) ($editUser['username_free_limit'] ?? 0) ?>">
        <label class="check-line"><input type="checkbox" name="username_unlimited" value="1" <?= (int) ($editUser['username_unlimited'] ?? 0) === 1 ? 'checked' : '' ?>> 用户名修改不限次数</label>
      </div>
      <div class="field">
        <label>用户名超出后每次扣积分</label>
        <input type="number" name="username_change_cost" min="0" max="999999" value="<?= (int) ($editUser['username_change_cost'] ?? 50) ?>">
        <small class="muted">可配合上方“允许修改用户名”使用;填写免费次数或勾选不限次数会自动允许。</small>
      </div>
    </div>
    <?php elseif (!$editOfficial): ?>
    <div class="field-row">
      <div class="field" style="flex:1 1 100%">
        <p class="muted" style="margin:0">管理员与超级管理员不受免费头像、昵称更换次数限制,因此无需设置额度与扣分。</p>
      </div>
    </div>
    <?php endif; ?>
    <?php if ($canEditFeaturePerms): ?>
    <div class="feature-perms">
      <label class="feature-perms-title">本站功能开关</label>
      <p class="muted">勾选表示开放;取消勾选后该用户无法使用对应前台功能。超级管理员始终不受限制。</p>
      <div class="feature-perm-grid">
        <?php
          $featureRegistry = site_feature_registry();
          if ($editOfficial) {
              $featureRegistry = array_intersect_key($featureRegistry, ['friends' => 1, 'verify' => 1]);
          }
        ?>
        <?php foreach ($featureRegistry as $featureKey => $featureName): ?>
          <label class="feature-perm-item"><input type="checkbox" name="features[]" value="<?= e($featureKey) ?>" <?= user_feature_enabled($editUser, $featureKey) ? 'checked' : '' ?>><span><?= e($featureName) ?></span></label>
        <?php endforeach; ?>
      </div>
    </div>
    <?php elseif (($editUser['role'] ?? '') === 'admin' && !is_superadmin($admin)): ?>
    <div class="feature-perms"><p class="muted">管理员不能设置管理员的功能权限;如需调整,请由超级管理员操作。</p></div>
    <?php endif; ?>
    <?php if (($editUser['role'] ?? '') === 'admin' && is_superadmin($admin)): ?>
    <div class="feature-perms plugin-access-perms">
      <label class="feature-perms-title">插件中心权限(仅普通管理员)</label>
      <p class="muted">控制该管理员在扩展中心看到的「插件中心」入口,以及插件商城里的上传接口。超级管理员始终可见并可上传。</p>
      <select name="plugin_access" class="plugin-access-select">
        <?php $pluginAccessNow = plugin_access_mode($editUser); ?>
        <option value="all" <?= $pluginAccessNow === 'all' ? 'selected' : '' ?>>可见可上传</option>
        <option value="view" <?= $pluginAccessNow === 'view' ? 'selected' : '' ?>>可见不能上传</option>
        <option value="hidden" <?= $pluginAccessNow === 'hidden' ? 'selected' : '' ?>>不可见</option>
      </select>
    </div>
    <?php endif; ?>
    <button class="btn-primary" type="submit">保存资料</button>
  </form>

  <?php if ($editOfficial): ?>
  <div class="admin-verify-card official-pc-appearance">
    <div class="admin-verify-head">
      <div>
        <label class="admin-verify-title">个人卡外观(仅官方固定账号)</label>
        <p class="muted">和「我的」个人卡外观设置一致:选择边框、背景图片或视频,支持预览、拖动、缩放和清晰度调整。</p>
      </div>
    </div>
    <div class="official-pc-current">
      <?= profile_bg_media_html($editBg, $editVideo) ?>
      <div class="official-pc-current-meta">
        <p>当前边框:<b><?= e($editFrameLabel) ?></b></p>
        <p>当前背景:<b><?= $editBg !== '' ? '图片' : ($editVideo !== '' ? '视频' : '未设置') ?></b><?= ($editBg !== '' || $editVideo !== '') ? ' · 清晰度 ' . (int) $editBlur . ' px' : '' ?></p>
        <p class="muted">背景图片与视频只能二选一;图片最长边会自动压到 1440px。</p>
      </div>
    </div>
    <div class="official-pc-actions">
      <a class="btn-primary block" href="<?= e(admin_url('users', ['uid' => (int) $editUser['id'], 'appearance' => 1])) ?>">个人卡外观设置</a>
      <span class="muted">点击进入独立设置页,可选择边框、上传背景并调整裁剪位置与清晰度。</span>
    </div>
  </div>
  <?php endif; ?>

  <?php if (!$editOfficial): ?>
  <div class="edit-row-forms">
    <form method="post" class="form-card">
      <?= csrf_field() ?>
      <input type="hidden" name="act" value="password">
      <input type="hidden" name="uid" value="<?= (int) $editUser['id'] ?>">
      <label>重置密码</label>
      <input type="password" name="new_password" placeholder="至少 6 位" required>
      <button class="btn-mini" type="submit">重置</button>
    </form>
    <?php if (is_superadmin($admin)): ?>
    <div class="form-card">
      <label><?= ($editUser['role'] ?? '') === 'admin' ? '管理员保护' : '账号保护' ?></label>
      <?php if ((int) $editUser['id'] === (int) $admin['id']): ?>
        <p class="muted">超级管理员不能对自己使用账号保护功能;请使用上方的「超级管理员保护锁」。</p>
      <?php elseif (is_superadmin($editUser)): ?>
        <p class="muted">不能保护超级管理员账号;请使用上方的「超级管理员保护锁」。</p>
      <?php else: ?>
        <p class="muted">开启后,该用户无法自行修改密码和用户名,也不能通过邮箱找回密码。<?= ($editUser['role'] ?? '') === 'admin' ? '受保护的管理员不能自行解除,只能由超级管理员关闭。' : '' ?></p>
        <form method="post">
          <?= csrf_field() ?>
          <input type="hidden" name="act" value="toggle_protect">
          <input type="hidden" name="uid" value="<?= (int) $editUser['id'] ?>">
          <label class="toggle-switch">
            <input type="checkbox" name="protected" value="1" <?= account_is_protected($editUser) ? 'checked' : '' ?> onchange="this.form.submit()">
            <span class="toggle-track"><span class="toggle-thumb"></span></span>
            <span class="toggle-text"><?= ($editUser['role'] ?? '') === 'admin' ? '管理员保护' : '账号保护' ?></span>
          </label>
        </form>
      <?php endif; ?>
    </div>
    <?php if (is_superadmin($editUser)): ?>
    <div class="form-card">
      <label>角色</label>
      <p class="muted">超级管理员只有一个,固定为部署站长账号;不能新增第二个超级管理员,也不能降级或移交。</p>
    </div>
    <?php else: ?>
    <form method="post" class="form-card">
      <?= csrf_field() ?>
      <input type="hidden" name="act" value="role">
      <input type="hidden" name="uid" value="<?= (int) $editUser['id'] ?>">
      <label>角色</label>
      <select name="role">
        <?php $assignableRoles = role_options(); unset($assignableRoles['superadmin']); ?>
        <?php foreach ($assignableRoles as $roleKey => $roleName): ?>
          <option value="<?= e($roleKey) ?>" <?= $editUser['role'] === $roleKey ? 'selected' : '' ?>><?= e($roleName) ?></option>
        <?php endforeach; ?>
      </select>
      <small class="field-tip">超级管理员只有一个,固定为部署站长账号;其他账号最高只能设为管理员。</small>
      <button class="btn-mini" type="submit">更新角色</button>
    </form>
    <?php endif; ?>
    <?php else: ?>
    <div class="form-card">
      <label>角色</label>
      <p class="muted">当前角色:<?= e($editUser['role'] === 'admin' ? '管理员' : ($editUser['role'] === 'superadmin' ? '超级管理员' : '普通用户')) ?>。角色只能由超级管理员调整。</p>
    </div>
    <?php endif; ?>
    <?php
      $realLogin = real_user() ?: $admin;
      $alreadyThisAccount = (int) ($realLogin['id'] ?? 0) === (int) $editUser['id'];
      $alreadyImpersonatingThis = impersonating() && (int) ($admin['id'] ?? 0) === (int) $editUser['id'];
    ?>
    <?php if (!$alreadyThisAccount && !$alreadyImpersonatingThis && !$editOfficial): ?>
    <form method="post" class="form-card">
      <?= csrf_field() ?>
      <input type="hidden" name="act" value="impersonate">
      <input type="hidden" name="uid" value="<?= (int) $editUser['id'] ?>">
      <label>代登录</label>
      <p class="muted">以该用户身份浏览前台,可在顶部退出。</p>
      <button class="btn-mini" type="submit">以 TA 的身份浏览</button>
    </form>
    <?php endif; ?>
    <?php if (!$editOfficial && !is_installer_admin($editUser) && (is_superadmin($admin) || !is_admin($editUser))): ?>
    <form method="post" class="form-card" data-confirm="把该账号的用户名、邮箱、昵称、性别、简介、所在地、展示范围和头像恢复到注册时填写的内容?密码、角色、积分和已发布内容不会改变。">
      <?= csrf_field() ?>
      <input type="hidden" name="act" value="restore_initial">
      <input type="hidden" name="uid" value="<?= (int) $editUser['id'] ?>">
      <label>注册资料恢复(仅此账号)</label>
      <p class="muted">只恢复当前这一位账号注册时保存的资料快照,不会影响其他用户;用户名或邮箱被占用时会跳过并提示。</p>
      <button class="btn-mini ghost" type="submit">恢复此账号的注册资料</button>
    </form>
    <?php endif; ?>
    <?php if (!$editOfficial && (int) $editUser['id'] !== (int) $admin['id'] && !is_superadmin($editUser) && (is_superadmin($admin) || !is_admin($editUser))): ?>
    <div class="form-card">
      <label>危险操作</label>
      <button class="btn-mini danger" type="button" data-delete-open data-uid="<?= (int) $editUser['id'] ?>" data-name="<?= e(display_name($editUser)) ?>">删除账号</button>
    </div>
    <?php endif; ?>
  </div>
  <?php endif; ?>
    </div>
  </div>
</section>
<?php endif; ?>

<section class="panel">
  <div class="admin-user-list">
    <?php foreach ($users as $u): $st = user_status_meta($u); ?>
      <article class="au-card">
        <div class="au-person">
          <a class="au-avatar-wrap" href="<?= e(page_url('user', ['id' => $u['id']])) ?>">
            <?= avatar_html($u, 'au-avatar') ?>
            <?php if ((int) $u['verified'] === 1): ?><span class="avatar-v v-<?= verify_style_of($u) ?>">V</span><?php endif; ?>
          </a>
          <div class="au-name">
            <a href="<?= e(page_url('user', ['id' => $u['id']])) ?>"><?= e(display_name($u)) ?></a>
            <?= verify_badge($u) ?>
            <?php if (is_official_account($u)): ?><span class="official-account-tag">官方固定账号</span><?php endif; ?>
            <span class="point-uid">ID <?= (int) $u['id'] ?></span>
          </div>
        </div>
        <div class="au-meta">
          <span>注册时间</span>
          <b><?= e(date('Y-m-d H:i', strtotime($u['created_at']))) ?></b>
        </div>
        <div class="au-status">
          <span class="role-pill role-<?= e($u['role']) ?>"><?= e(role_label($u['role'])) ?></span>
          <span class="status-pill <?= e($st['cls']) ?>"><?= e($st['label']) ?></span>
          <span class="au-points">积分 <b><?= e(points_text($u)) ?></b></span>
          <?php if (is_installer_admin($u)): ?><span class="status-pill ok">部署管理员</span><?php endif; ?>
          <?php if (account_is_protected($u)): ?><span class="status-pill bad">受保护</span><?php endif; ?>
          <?php if ($st['extra'] !== ''): ?><small><?= e($st['extra']) ?></small><?php endif; ?>
        </div>
        <div class="au-ops">
          <?php if (($admin['role'] ?? '') !== 'superadmin' && ($u['role'] ?? '') === 'superadmin'): ?>
            <span class="muted">仅超级管理员可操作</span>
          <?php else: ?>
          <a class="btn-mini ghost" href="<?= e(admin_url('users', ['uid' => $u['id']])) ?>">编辑</a>
          <a class="btn-mini ghost" href="<?= e(page_url('ip_history', ['uid' => (int) $u['id']])) ?>">登录记录</a>
          <?php if (!is_admin($u) && !is_official_account($u)): ?>
          <form method="post" class="inline-form">
            <?= csrf_field() ?><input type="hidden" name="act" value="toggle_username"><input type="hidden" name="uid" value="<?= (int) $u['id'] ?>">
            <label class="toggle-switch"><input type="checkbox" <?= (int) ($u['can_rename_username'] ?? 0) === 1 ? 'checked' : '' ?> onchange="this.form.submit()"><span class="toggle-track"><span class="toggle-thumb"></span></span><span class="toggle-text">允许修改用户名(使用下方额度)</span></label>
          </form>
          <?php endif; ?>
          <?php if (is_superadmin($admin) && (int) $u['id'] !== (int) $admin['id'] && !is_superadmin($u) && !is_official_account($u)): ?>
          <form method="post" class="inline-form">
            <?= csrf_field() ?><input type="hidden" name="act" value="toggle_protect"><input type="hidden" name="uid" value="<?= (int) $u['id'] ?>">
            <label class="toggle-switch"><input type="checkbox" name="protected" value="1" <?= account_is_protected($u) ? 'checked' : '' ?> onchange="this.form.submit()"><span class="toggle-track"><span class="toggle-thumb"></span></span><span class="toggle-text">保护账号</span></label>
          </form>
          <?php endif; ?>
          <?php if ((int) $u['id'] === (int) $admin['id']): ?>
            <span class="muted">当前账号</span>
          <?php elseif (!is_official_account($u)): ?>
            <?php if (user_is_muted($u)): ?>
              <form method="post" class="inline-form">
                <?= csrf_field() ?><input type="hidden" name="act" value="unmute"><input type="hidden" name="uid" value="<?= (int) $u['id'] ?>">
                <button class="btn-mini ghost" type="submit">解除禁言</button>
              </form>
            <?php else: ?>
              <button class="btn-mini ghost op-danger" type="button" data-user-action="mute" data-uid="<?= (int) $u['id'] ?>" data-name="<?= e(display_name($u)) ?>">禁言</button>
            <?php endif; ?>
            <?php if ((int) $u['status'] === 1): ?>
              <button class="btn-mini ghost op-danger" type="button" data-user-action="ban" data-uid="<?= (int) $u['id'] ?>" data-name="<?= e(display_name($u)) ?>">封禁</button>
            <?php else: ?>
              <form method="post" class="inline-form">
                <?= csrf_field() ?><input type="hidden" name="act" value="unban"><input type="hidden" name="uid" value="<?= (int) $u['id'] ?>">
                <button class="btn-mini ghost" type="submit">解封</button>
              </form>
            <?php endif; ?>
            <?php if (!is_official_account($u) && !is_superadmin($u) && !is_installer_admin($u) && (is_superadmin($admin) || !is_admin($u))): ?>
              <button class="btn-mini ghost op-danger" type="button" data-delete-open data-uid="<?= (int) $u['id'] ?>" data-name="<?= e(display_name($u)) ?>">删除账号</button>
            <?php endif; ?>
          <?php endif; ?>
          <?php endif; ?>
        </div>
      </article>
    <?php endforeach; ?>
    <?php if (!$users): ?><?php empty_state('没有找到用户'); ?><?php endif; ?>
  </div>
  <?= pager_html($pager, 'admin', array_filter(['s' => 'users', 'q' => $q !== '' ? $q : null])) ?>
</section>

<?php if (is_superadmin($admin)): ?>
<?php
$deletedArchives = DB::all('SELECT * FROM ' . DB::table('deleted_accounts') . " WHERE restored_at = '' AND restored_uid = 0 ORDER BY id DESC LIMIT 100");
?>
<section class="panel deleted-account-panel" id="deletedAccounts">
  <div class="panel-head">
    <div>
      <h2 class="section-title">被删除账号恢复</h2>
      <p class="muted">删除账号前会把账号资料、帖子、评论、世界圈、网盘、图床、附件、私信、草稿和社交关系完整归档。勾选一个或多个存档后恢复,账号会按原 UID、原用户名和邮箱重建,并恢复所有已存档数据与文件。</p>
    </div>
    <span class="muted"><?= count($deletedArchives) ?> 条待恢复</span>
  </div>
  <?php if (!$deletedArchives): ?>
    <p class="muted">暂无待恢复的删除存档。</p>
  <?php else: ?>
  <form method="post" id="restoreArchivesForm" data-confirm="恢复勾选的账号?将重建账号并恢复已归档的全部内容与文件。">
    <?= csrf_field() ?>
    <input type="hidden" name="act" value="restore_archives">
    <div class="deleted-account-toolbar">
      <label class="check-line"><input type="checkbox" id="restoreSelectAll"> 全选</label>
      <button class="btn-primary btn-mini" type="submit">恢复勾选账号</button>
    </div>
    <div class="deleted-account-list">
      <?php foreach ($deletedArchives as $a): ?>
        <label class="deleted-account-card">
          <input type="checkbox" name="archive_ids[]" value="<?= (int) $a['id'] ?>" class="restore-archive-check">
          <div class="deleted-account-main">
            <div class="deleted-account-title">
              <b><?= e((string) ($a['nickname'] !== '' ? $a['nickname'] : $a['username'])) ?></b>
              <span class="muted">@<?= e((string) $a['username']) ?></span>
              <em><?= e(role_label((string) $a['role'])) ?></em>
            </div>
            <p class="muted">原 UID <?= (int) $a['original_uid'] ?> · <?= e((string) ($a['email'] !== '' ? email_mask((string) $a['email']) : '无绑定邮箱')) ?> · 删除于 <?= e((string) $a['created_at']) ?></p>
            <p class="deleted-account-summary"><?= e((string) ($a['summary'] ?? '')) ?></p>
          </div>
        </label>
      <?php endforeach; ?>
    </div>
  </form>
  <script>
  (function(){
    var all = document.getElementById('restoreSelectAll');
    var list = document.querySelectorAll('.restore-archive-check');
    if (all) all.addEventListener('change', function(){
      list.forEach(function(x){ x.checked = all.checked; });
    });
  })();
  </script>
  <?php endif; ?>
</section>
<?php endif; ?>

<section class="modal delete-account-modal" id="deleteAccountModal" hidden>
  <div class="modal-mask" data-delete-close></div>
  <div class="modal-card">
    <div class="sa-lock-modal-head">
      <h3 id="deleteAccountTitle">删除账号</h3>
      <button type="button" class="readers-close" data-delete-close>×</button>
    </div>
    <p class="muted">删除会清空该账号的帖子、评论、网盘与图床内容,删除前会完整归档以便恢复。所有管理员和超级管理员都必须先验证本人绑定邮箱,再输入发送到该邮箱的 6 位验证码。</p>
    <p class="muted" id="deleteAccountEmailHint">验证码将发送到:<?= e(trim((string) ($admin['email'] ?? '')) !== '' ? email_mask((string) $admin['email']) : '当前管理员尚未绑定邮箱,无法删除') ?></p>
    <button type="button" class="btn-mini ghost" id="deleteAccountSendCode">发送邮箱验证码</button>
    <form method="post" class="auth-form" id="deleteAccountForm" data-confirm="确认删除该账号?账号资料会进入恢复存档,已清理的内容不会恢复。">
      <?= csrf_field() ?>
      <input type="hidden" name="act" value="delete">
      <input type="hidden" name="uid" id="deleteAccountUid" value="0">
      <label for="deleteAccountCode">邮箱验证码</label>
      <input type="text" name="delete_email_code" id="deleteAccountCode" inputmode="numeric" maxlength="6" pattern="\d{6}" autocomplete="one-time-code" placeholder="6 位验证码" required>
      <div class="modal-actions">
        <button type="button" class="btn-mini ghost" data-delete-close>取消</button>
        <button type="submit" class="btn-mini danger">确认删除</button>
      </div>
    </form>
  </div>
</section>

<section class="user-action-modal" id="userActionModal" hidden>
  <div class="uam-card">
    <div class="uam-head">
      <h3 id="uamTitle">禁言用户</h3>
      <button type="button" class="readers-close" id="uamClose">×</button>
    </div>
    <form method="post" id="uamForm">
      <?= csrf_field() ?>
      <input type="hidden" name="act" id="uamAct" value="mute">
      <input type="hidden" name="uid" id="uamUid" value="0">
      <p class="muted" id="uamDesc">请选择时长,到期后自动解除。</p>
      <label>时长</label>
      <select name="duration" id="uamDuration">
        <option value="600">10 分钟</option>
        <option value="3600">1 小时</option>
        <option value="86400" selected>1 天</option>
        <option value="604800">7 天</option>
        <option value="2592000">30 天</option>
        <option value="31536000">1 年</option>
        <option value="0">永久</option>
      </select>
      <label for="uamReason">处罚理由</label>
      <input type="text" name="reason" id="uamReason" maxlength="255" placeholder="例如:发布广告、恶意刷屏(会展示在小黑屋)">
      <div class="uam-ban-code" id="uamBanCodeWrap" hidden>
        <p class="muted" id="uamBanCodeHint"><?php
          $adminEmail = trim((string) ($admin['email'] ?? ''));
          if ($adminEmail === '' || !filter_var($adminEmail, FILTER_VALIDATE_EMAIL)) {
              echo '当前管理员尚未绑定有效邮箱,无法永久封禁';
          } elseif ((int) ($admin['email_verified'] ?? 0) !== 1) {
              echo '当前管理员邮箱尚未验证,请先到认证中心完成验证';
          } else {
              echo '验证码将发送到 ' . e(email_mask($adminEmail)) . ',10 分钟内有效';
          }
        ?></p>
        <button type="button" class="btn-mini ghost" id="uamBanSendCode"<?= (trim((string) ($admin['email'] ?? '')) === '' || !filter_var((string) ($admin['email'] ?? ''), FILTER_VALIDATE_EMAIL) || (int) ($admin['email_verified'] ?? 0) !== 1) ? ' disabled' : '' ?>>发送邮箱验证码</button>
        <label for="uamBanEmailCode">邮箱验证码</label>
        <input type="text" name="ban_email_code" id="uamBanEmailCode" inputmode="numeric" maxlength="6" pattern="\d{6}" autocomplete="one-time-code" placeholder="永久封禁需填 6 位验证码">
      </div>
      <button class="btn-primary" type="submit" id="uamSubmit">确认禁言</button>
    </form>
  </div>
</section>
<script>
(function () {
  function openSaModal(modal) {
    if (!modal) return;
    modal.hidden = false;
    var first = modal.querySelector('input[name="code"], input[name="email_code"]');
    if (first) setTimeout(function () { first.focus(); }, 30);
  }
  var switchBtn = document.getElementById('saLockSwitch');
  if (switchBtn) {
    switchBtn.addEventListener('click', function () {
      var on = switchBtn.getAttribute('data-on') === '1';
      openSaModal(document.getElementById(on ? 'saLockDisableModal' : 'saLockEnableModal'));
    });
  }
  ['saLockEmailOpen', 'saLockEmailEntry'].forEach(function (id) {
    var btn = document.getElementById(id);
    if (btn) btn.addEventListener('click', function () {
      openSaModal(document.getElementById('saLockEmailModal'));
    });
  });

  var emailForm = document.getElementById('saLockEmailForm');
  var sendBtn = document.getElementById('saLockSendEmail');
  var confirmBtn = document.getElementById('saLockEmailConfirm');
  var emailStatus = document.getElementById('saLockEmailStatus');
  var emailInput = emailForm ? emailForm.querySelector('input[name="email_code"]') : null;
  var cooldownTimer = null;
  var cooldownLeft = 0;

  function setEmailStatus(text, type) {
    if (!emailStatus) return;
    emailStatus.textContent = text || '';
    emailStatus.className = 'sa-email-status' + (text ? ' on' : '') + (type ? ' ' + type : '');
  }
  function setIdleSendText() {
    if (sendBtn) sendBtn.textContent = '发送验证码';
  }
  function startCooldown(seconds) {
    if (!sendBtn) return;
    cooldownLeft = Math.max(0, parseInt(seconds, 10) || 60);
    if (cooldownTimer) clearInterval(cooldownTimer);
    sendBtn.disabled = true;
    sendBtn.textContent = '重新发送验证码(' + cooldownLeft + 's)';
    cooldownTimer = setInterval(function () {
      cooldownLeft--;
      if (cooldownLeft <= 0) {
        clearInterval(cooldownTimer);
        cooldownTimer = null;
        sendBtn.disabled = false;
        sendBtn.textContent = '重新发送验证码';
        return;
      }
      sendBtn.textContent = '重新发送验证码(' + cooldownLeft + 's)';
    }, 1000);
  }
  function postEmailAction(extra) {
    var data = new FormData(emailForm);
    data.set('ajax', '1');
    Object.keys(extra || {}).forEach(function (k) { data.set(k, extra[k]); });
    return fetch(emailForm.getAttribute('action') || window.location.href, {
      method: 'POST',
      headers: { 'X-Requested-With': 'XMLHttpRequest' },
      body: data,
      credentials: 'same-origin'
    }).then(function (res) {
      return res.json();
    });
  }

  if (sendBtn) {
    sendBtn.addEventListener('click', function () {
      if (sendBtn.disabled) return;
      sendBtn.disabled = true;
      sendBtn.textContent = '发送中…';
      setEmailStatus('正在发送验证码,请稍候…', '');
      postEmailAction({ act: 'sa_lock_send_email' }).then(function (res) {
        if (res && res.ok) {
          setEmailStatus('发送成功,验证码已发送到超级管理员绑定邮箱,请查收。', 'ok');
          startCooldown(res.retry_after || 60);
        } else {
          setEmailStatus((res && res.msg) ? res.msg : '发送失败,请稍后重试', 'err');
          sendBtn.disabled = false;
          setIdleSendText();
        }
      }).catch(function () {
        setEmailStatus('网络异常,验证码发送失败,请稍后重试', 'err');
        sendBtn.disabled = false;
        setIdleSendText();
      });
    });
  }

  if (emailForm) {
    emailForm.addEventListener('submit', function (e) {
      e.preventDefault();
      var code = emailInput ? emailInput.value.replace(/\D/g, '').slice(0, 6) : '';
      if (!/^\d{6}$/.test(code)) {
        setEmailStatus('请输入 6 位数字邮箱验证码', 'err');
        if (emailInput) emailInput.focus();
        return;
      }
      if (emailInput) emailInput.value = code;
      confirmBtn.disabled = true;
      confirmBtn.textContent = '验证中…';
      setEmailStatus('正在验证邮箱验证码…', '');
      postEmailAction({ act: 'sa_lock_email_unlock', email_code: code }).then(function (res) {
        if (res && res.ok) {
          setEmailStatus('验证成功,超级管理员保护锁已自动关闭。', 'ok');
          confirmBtn.textContent = '已关闭';
          setTimeout(function () { window.location.reload(); }, 900);
        } else {
          setEmailStatus((res && res.msg) ? res.msg : '验证码错误或已过期', 'err');
          confirmBtn.disabled = false;
          confirmBtn.textContent = '确认';
          if (emailInput) {
            emailInput.focus();
            emailInput.select();
          }
        }
      }).catch(function () {
        setEmailStatus('网络异常,验证失败,请稍后重试', 'err');
        confirmBtn.disabled = false;
        confirmBtn.textContent = '确认';
      });
    });
  }
})();
</script>
<script>
(function () {
  var modal = document.getElementById('userEditModal');
  if (!modal) return;
  function closeEdit(e) {
    if (e) e.preventDefault();
    modal.hidden = true;
    var u = new URL(window.location.href);
    u.searchParams.delete('uid');
    u.searchParams.delete('verify');
    u.searchParams.delete('appearance');
    try { history.replaceState(null, '', u.pathname + u.search + u.hash); } catch (err) {}
  }
  document.querySelectorAll('[data-user-edit-close]').forEach(function (el) {
    el.addEventListener('click', closeEdit);
  });
  document.addEventListener('keydown', function (e) {
    if (e.key === 'Escape' && !modal.hidden) closeEdit(e);
  });
})();
</script>
<script>
(function () {
  var modal = document.getElementById('deleteAccountModal');
  if (!modal) return;
  var uidInput = document.getElementById('deleteAccountUid');
  var title = document.getElementById('deleteAccountTitle');
  var hint = document.getElementById('deleteAccountEmailHint');
  var sendBtn = document.getElementById('deleteAccountSendCode');
  var codeInput = document.getElementById('deleteAccountCode');
  var currentUid = 0;

  function close() {
    modal.hidden = true;
    document.body.classList.remove('crop-open');
  }
  document.querySelectorAll('[data-delete-close]').forEach(function (el) {
    el.addEventListener('click', close);
  });
  document.addEventListener('keydown', function (e) {
    if (e.key === 'Escape' && !modal.hidden) close();
  });
  document.addEventListener('click', function (e) {
    var btn = e.target.closest('[data-delete-open]');
    if (!btn) return;
    currentUid = parseInt(btn.getAttribute('data-uid') || '0', 10);
    var name = btn.getAttribute('data-name') || '该用户';
    uidInput.value = currentUid;
    title.textContent = '删除账号 · ' + name;
    hint.textContent = '验证码将发送到你的绑定邮箱。';
    codeInput.value = '';
    sendBtn.disabled = false;
    sendBtn.textContent = '发送邮箱验证码';
    modal.hidden = false;
    document.body.classList.add('crop-open');
    codeInput.focus();
  });

  sendBtn.addEventListener('click', function () {
    sendBtn.disabled = true;
    sendBtn.textContent = '发送中…';
    hint.textContent = '正在发送验证码…';
    if (!window.KM || !KM.api) {
      hint.textContent = '页面脚本未加载,请刷新后重试';
      sendBtn.disabled = false;
      sendBtn.textContent = '发送邮箱验证码';
      return;
    }
    KM.api('admin_delete_send_code', { uid: currentUid }).then(function (res) {
      if (res && res.ok) {
        hint.textContent = '验证码已发送到 ' + (res.email_mask || '你的绑定邮箱') + ',10 分钟内有效';
        sendBtn.textContent = '重新发送验证码';
      } else {
        hint.textContent = (res && res.msg) ? res.msg : '发送失败,请稍后重试';
        sendBtn.textContent = '重新发送验证码';
      }
      sendBtn.disabled = false;
    }).catch(function () {
      hint.textContent = '网络异常,请稍后重试';
      sendBtn.disabled = false;
      sendBtn.textContent = '重新发送验证码';
    });
  });
})();
</script>
主题