<?php
// 功能：网站登录文件
// 作者：启肯科技
// Q Q：328493711
// 微信：13738373177（同手机）
// 官网：http://www.qiken.com
// 说明：QKCMS-轻量级AI智能内容管理建站系统
// 版权：© 2025 温州启肯网络有限公司 保留所有权利，盗版必究。

// 确保会话已启动，避免重复调用
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// 启用输出缓冲，用于解析插件标签
ob_start();

// 检查是否是直接访问templates/login.php文件
if (!defined('COMMON_LOADED')) {
    // 如果是POST请求（如注册或登录），则不重定向
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        // 直接加载common.php，不进行重定向
        require_once '../common.php';
        define('COMMON_LOADED', true);
    } else {
        // 检查请求是否来自index.php路由
        $isDirectAccess = true;
        if (isset($_SERVER['HTTP_REFERER'])) {
            $referer = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_PATH);
            if (strpos($referer, '/index.php') !== false || strpos($referer, '/login') !== false) {
                $isDirectAccess = false;
            }
        }

        // 如果是直接访问，重定向到简短URL格式（除非是模态框模式）
        if ($isDirectAccess && !isset($_GET['is_modal'])) {
            // 构建简短URL
            $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
            $host = $_SERVER['HTTP_HOST'];
            $shortUrl = $protocol . $host . '/login';

            // 执行301永久重定向
            header('HTTP/1.1 301 Moved Permanently');
            header('Location: ' . $shortUrl);
            exit;
        }

        // 如果不是直接访问但没有通过index.php加载，则自己加载
        require_once '../common.php';
        define('COMMON_LOADED', true);
    }
}

if (isset($_GET['email_tool'])) {
    $email_mode = isset($_GET['mode']) ? trim((string)$_GET['mode']) : '';
    if ($email_mode === 'bind' || $email_mode === 'recover') {
        $_GET['mode'] = $email_mode;
        require_once __DIR__ . '/Plugin/52_emaillink.php';
        exit;
    }
}

// 获取网站设置
$settings = getSettings($GLOBALS['conn']);
$favicon_color = isset($settings['primary_color']) ? trim($settings['primary_color']) : '#10b981';
if (!preg_match('/^#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/', $favicon_color)) {
    $favicon_color = '#10b981';
}
$favicon_svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="12" fill="' . $favicon_color . '"/><text x="32" y="45" text-anchor="middle" fill="#fff" font-size="46" font-family="Arial,Helvetica,sans-serif" font-weight="900">Q</text></svg>';
$favicon_data_uri = 'data:image/svg+xml,' . rawurlencode($favicon_svg);

// 页面标题
$page_title = '登录/注册 - ' . escape($settings['site_title']);

if (!function_exists('qk_validate_bind_email_token')) {
    function qk_validate_bind_email_token($token, $email)
    {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        $tokenPool = array();
        if (isset($_SESSION['qk52_email_bind_tokens']) && is_array($_SESSION['qk52_email_bind_tokens'])) {
            $tokenPool = &$_SESSION['qk52_email_bind_tokens'];
        } elseif (isset($_SESSION['qk_email_bind_tokens']) && is_array($_SESSION['qk_email_bind_tokens'])) {
            $tokenPool = &$_SESSION['qk_email_bind_tokens'];
        } else {
            return false;
        }
        if (!$token || !$email || !isset($tokenPool[$token])) {
            return false;
        }
        $row = $tokenPool[$token];
        if (!isset($row['email'], $row['expires_at'])) {
            return false;
        }
        if ((int)$row['expires_at'] < time()) {
            unset($tokenPool[$token]);
            return false;
        }
        if (strtolower(trim((string)$row['email'])) !== strtolower(trim((string)$email))) {
            return false;
        }
        return true;
    }
}



if (isset($_GET['action']) && $_GET['action'] == 'logout') {
    // 设置最严格的防缓存头
    header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0, private");
    header("Pragma: no-cache");
    header("Expires: -1");
    header("X-Content-Type-Options: nosniff");
    header("X-Frame-Options: SAMEORIGIN");

    // 强制清除会话数据（额外的保障层）
    if (session_status() !== PHP_SESSION_NONE) {
        $_SESSION = array();
        @session_destroy();
        @session_write_close();
    }

    // 调用logoutUser函数进行标准退出处理
    logoutUser();

    // 立即重定向到登录页面，添加logout_success参数
    // 使用302重定向确保每次请求都是新的
    header('HTTP/1.1 302 Found');
    header('Location: /admin/login.php?logout_success=true&t=' . time());
    exit;
}

// 特别处理登出后的情况，确保显示登录页面
if (isset($_GET['logout_success']) || isset($_GET['action']) && $_GET['action'] == 'logout') {
    // 强制清除任何可能的会话数据
    if (session_status() !== PHP_SESSION_NONE) {
        $_SESSION = array();
        session_destroy();
        session_write_close();
    }

    // 设置严格的无缓存头
    header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
    header("Pragma: no-cache");
    header("Expires: 0");

    // 确保没有登录状态 - 即使会话已经被销毁也要执行
    if (isset($_SESSION)) {
        unset($_SESSION['user_id']);
        unset($_SESSION['username']);
        unset($_SESSION['role']);
    }

    // 强制显示登录页面，不执行下面的登录检查重定向
} else {
    // 正常的登录状态检查
    if (isLoggedIn()) {
        $redirectUrl = '/';
        $user_levels_id = $_SESSION['levels_id'] ?? 0;
        $is_admin = ($user_levels_id == 3);
        if ($is_admin) {
            $redirectUrl = '/admin/admin.php';
        } else if (isset($_GET['redirect']) && !empty($_GET['redirect'])) {
            $redirectUrl = $_GET['redirect'];
        }

        if (isset($_GET['is_modal'])) {
            header('Content-Type: text/html; charset=utf-8');
            $safeRedirect = htmlspecialchars($redirectUrl, ENT_QUOTES, 'UTF-8');
            echo '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"></head><body><script>(function(){try{if(window.parent){window.parent.postMessage({type:"close_modal",modal_id:"login",source:"admin_login"}, "*");}}catch(e){}try{var u="' . $safeRedirect . '";if(u){if(window.top&&window.top!==window){window.top.location.href=u;}else{window.location.href=u;}}}catch(e){}})();</script></body></html>';
            exit;
        }

        header('Location: ' . $redirectUrl);
        exit;
    }
}

// 处理异步登录请求
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'ajax_login') {
    // 设置响应头为JSON格式
    header('Content-Type: application/json');

    // 初始化响应数组
    $response = ['success' => false, 'message' => '登录失败'];

    try {
        $username = escape(trim($_POST['username']));
        $password = trim($_POST['password']);

        // 调用loginUser函数进行登录验证
        $result = loginUser($GLOBALS['conn'], $username, $password);

        if ($result === true) {
            // 登录成功
            $response['success'] = true;
            $response['message'] = '登录成功';
            // 获取用户信息
            $user_info = get_single_row($GLOBALS['conn'], "SELECT id, username, avatar, points, created_at, email FROM users WHERE id = ?", [$_SESSION['user_id']]);
            $response['user_info'] = [
                'id' => $user_info['id'] ?? $_SESSION['user_id'],
                'username' => $user_info['username'] ?? $_SESSION['username'] ?? $username,
                'avatar' => $user_info['avatar'] ?? '',
                'points' => $user_info['points'] ?? 0,
                'created_at' => $user_info['created_at'] ?? '',
                'email' => isset($user_info['email']) && !empty($user_info['email']) ? $user_info['email'] : '未绑定',
                'is_admin' => isset($_SESSION['levels_id']) && $_SESSION['levels_id'] == 3
            ];
        } else {
            // 登录失败，返回错误信息
            $response['message'] = $result;
        }
    } catch (Exception $e) {
        $response['message'] = '登录过程中发生错误';
    }

    // 返回JSON响应
    echo json_encode($response);
    exit;
}

// 处理检查登录状态请求
if (isset($_GET['action']) && $_GET['action'] == 'check_login') {
    // 设置响应头为JSON格式
    header('Content-Type: application/json');

    // 初始化响应数组
    $response = ['logged_in' => false, 'user_info' => null];

    try {
        if (isLoggedIn() && isset($_SESSION['user_id'])) {
            // 获取用户信息
            $user_info = get_single_row($GLOBALS['conn'], "SELECT id, username, avatar, points, created_at, email FROM users WHERE id = ?", [$_SESSION['user_id']]);
            // 获取用户等级
            $user_level = '';
            if (isset($_SESSION['levels_id'])) {
                switch ($_SESSION['levels_id']) {
                    case 3:
                        $user_level = '管理员';
                        break;
                    case 2:
                        $user_level = 'VIP会员';
                        break;
                    default:
                        $user_level = '普通会员';
                        break;
                }
            }
            $response['logged_in'] = true;
            $response['user_info'] = [
                'id' => $user_info['id'] ?? $_SESSION['user_id'],
                'username' => $user_info['username'] ?? $_SESSION['username'],
                'avatar' => $user_info['avatar'] ?? '',
                'points' => $user_info['points'] ?? 0,
                'created_at' => $user_info['created_at'] ?? '',
                'email' => isset($user_info['email']) && !empty($user_info['email']) ? $user_info['email'] : '未绑定',
                'level' => $user_level
            ];
        }
    } catch (Exception $e) {
        // 忽略错误
    }

    // 返回JSON响应
    echo json_encode($response);
    exit;
}

// 处理表单提交
$error = '';
$success = '';
$bound_reg_email = '';
$bound_reg_email_token = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // 处理登录
    if (isset($_POST['login'])) {
        $username = escape(trim($_POST['username']));
        $password = trim($_POST['password']);

        // 调用loginUser函数进行登录验证
        $result = loginUser($GLOBALS['conn'], $username, $password);

        if ($result === true) {
            // 构建重定向目标URL
            $redirectUrl = '/'; // 默认

            // 获取用户等级ID，判断是否是管理员（levels_id 为 3 是管理员）
            $user_levels_id = $_SESSION['levels_id'] ?? 0;
            $is_admin = ($user_levels_id == 3);

            if ($is_admin) {
                // 管理员登录，强制跳转到后台
                $redirectUrl = '/admin/admin.php';
            } else {
                // 普通用户登录，逻辑如下：
                // 1. 如果有 redirect 参数（通常是 QKModal 自动带上的当前页面 URL），则跳转到该 URL
                // 2. 如果没有 redirect 参数，默认回首页
                if (isset($_GET['redirect']) && !empty($_GET['redirect'])) {
                    $redirectUrl = $_GET['redirect'];
                } else {
                    $redirectUrl = '/';
                }
            }

            // 登录成功，设置localStorage状态并触发同步登录
            // 获取用户信息（优先从数据库获取最新数据）
            $user_info = get_single_row($GLOBALS['conn'], "SELECT id, username, avatar, points, created_at, levels_id, email FROM users WHERE id = ?", [$_SESSION['user_id']]);

            // 调试：如果查询失败，使用session数据
            if (!$user_info) {
                $user_info = [
                    'id' => $_SESSION['user_id'],
                    'username' => $_SESSION['username'] ?? $username,
                    'avatar' => '',
                    'points' => 0,
                    'created_at' => '',
                    'email' => '未绑定'
                ];
            }

            $user_id = $user_info['id'] ?? $_SESSION['user_id'];
            $user_name = $user_info['username'] ?? $_SESSION['username'] ?? $username;
            // 优先使用数据库中的头像，确保获取最新数据
            $user_avatar = $user_info['avatar'] ?? '';
            if (empty($user_avatar)) {
                $user_avatar = DEFAULT_AVATAR_PATH;
            }
            $user_points = $user_info['points'] ?? 0;
            $user_created_at = $user_info['created_at'] ?? '';
            $user_email = isset($user_info['email']) && !empty($user_info['email']) ? $user_info['email'] : '未绑定';
            $_SESSION['user_email'] = $user_email;
            // 获取用户等级
            $user_level = '普通会员';
            if (isset($_SESSION['levels_id'])) {
                if ($_SESSION['levels_id'] == 3) $user_level = '管理员';
                else if ($_SESSION['levels_id'] == 2) $user_level = 'VIP会员';
            }

            // 对JavaScript字符串进行转义，但不转义&符号
            $js_user_name = json_encode($user_name);
            $js_user_avatar = json_encode($user_avatar);
            $js_user_created_at = json_encode($user_created_at);
            $js_user_email = json_encode($user_email);
            $js_user_level = json_encode($user_level);
            $js_user_status = json_encode($_SESSION['user_status'] ?? '正常');

            echo '<script>
                // 立即关闭模态窗口（如果是模态方式打开）
                if (window.parent && window.parent !== window) {
                    window.parent.postMessage({type: "close_modal", modal_id: "login", source: "admin_login"}, "*");
                }
                
                try {
                    localStorage.setItem("qkcms_logged_in", "true");
                    localStorage.setItem("qkcms_user_nickname", ' . $js_user_name . ');
                    localStorage.setItem("qkcms_user_id", "' . $user_id . '");
                    localStorage.setItem("qkcms_user_avatar", ' . $js_user_avatar . ');
                    localStorage.setItem("qkcms_user_email", ' . $js_user_email . ');
                    
                    var syncData = {
                        action: "login",
                        time: Date.now(),
                        userInfo: {
                            id: "' . $user_id . '",
                            username: ' . $js_user_name . ',
                            avatar: ' . $js_user_avatar . ',
                            points: ' . (int)$user_points . ',
                            created_at: ' . $js_user_created_at . ',
                            email: ' . $js_user_email . ',
                            level: ' . $js_user_level . ',
                            status: ' . $js_user_status . '
                        }
                    };
                    localStorage.setItem("qkcms_login_sync", JSON.stringify(syncData));
                } catch(e) { console.error("Sync error:", e); }
                
                // 延迟跳转，让模态窗口关闭动画有时间执行
                setTimeout(function() {
                    (window.top || window).location.href = "' . $redirectUrl . '";
                }, 100);
            </script>';
            exit;
        } else {
            $error = $result;
        }
    }
    // 处理注册
    else if (isset($_POST['register'])) {
        $username = escape(trim($_POST['reg_username']));
        $password = trim($_POST['reg_password']);
        $reg_email = strtolower(trim((string)($_POST['reg_email'] ?? '')));
        $reg_email_token = trim((string)($_POST['reg_email_token'] ?? ''));
        $bound_reg_email = $reg_email;
        $bound_reg_email_token = $reg_email_token;
        $email_for_register = '';

        if ($reg_email !== '' || $reg_email_token !== '') {
            if (!filter_var($reg_email, FILTER_VALIDATE_EMAIL)) {
                $error = '绑定邮箱格式不正确';
                $showRegisterForm = true;
            } else if (!qk_validate_bind_email_token($reg_email_token, $reg_email)) {
                $error = '绑定邮箱验证已失效，请重新验证';
                $showRegisterForm = true;
            } else {
                $email_for_register = $reg_email;
            }
        }

        if (empty($error)) {
            $result = registerUser($GLOBALS['conn'], $username, $password, $email_for_register);

            if ($result === true) {
                $success = '注册成功，请登录';
                $showLoginForm = true;
                $showRegisterForm = false;
                $registered_username = $username;
                $registered_password = $password;
                $bound_reg_email = '';
                $bound_reg_email_token = '';
            } else {
                $error = $result;
                $showRegisterForm = true;
            }
        }
    }
}

// 如果不是POST请求，检查URL参数是否显示注册表单
if ($_SERVER['REQUEST_METHOD'] !== 'POST' && isset($_GET['register']) && $_GET['register'] === '1') {
    $showRegisterForm = true;
}

// 检测第三方登录插件状态
$wechat_plugin = get_plugin_by_id(12);
$qq_plugin = get_plugin_by_id(13);
$email_link_plugin = get_plugin_by_id(52);

$email_tool_installed = !empty($email_link_plugin);
$email_tool_enabled = $email_tool_installed;
if ($email_tool_installed && isset($email_link_plugin['config_params']) && is_array($email_link_plugin['config_params']) && isset($email_link_plugin['config_params']['插件开关'])) {
    $email_switch_value = trim((string)$email_link_plugin['config_params']['插件开关']);
    if (strpos($email_switch_value, '|') !== false) {
        $parts = explode('|', $email_switch_value, 2);
        $email_switch_value = trim((string)$parts[0]);
    }
    $email_tool_enabled = in_array(strtolower($email_switch_value), array('1', 'true', 'on', 'yes', '开启'), true);
}

$wechat_enabled = ($wechat_plugin && isset($wechat_plugin['config_params']['插件开关']) && $wechat_plugin['config_params']['插件开关'] === 'true');
$qq_enabled = ($qq_plugin && isset($qq_plugin['config_params']['插件开关']) && $qq_plugin['config_params']['插件开关'] === 'true');

// 动态设置第三方登录标题
if ($wechat_enabled && $qq_enabled) {
    $social_title = '你还可使用第三方登录';
} elseif ($wechat_enabled) {
    $social_title = '你还可以用微信快捷登录';
} elseif ($qq_enabled) {
    $social_title = '你还可以用QQ快捷登录';
} else {
    $social_title = '你还未安装快捷登录插件';
}
?>
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录/注册——<?php echo escape($settings['site_name']); ?></title>
    <link rel="icon" href="<?php echo escape($favicon_data_uri); ?>" type="image/svg+xml" />
    <link rel="shortcut icon" href="<?php echo escape($favicon_data_uri); ?>" type="image/svg+xml" />
    <meta name="keywords" content="<?php echo escape($settings['site_keywords']); ?>">
    <meta name="description" content="<?php echo escape($settings['site_description']); ?>">

    <!-- 直接在HTML中定义主题色，避免闪烁 -->
    <style>
        :root {
            --primary-color: <?php echo $settings['primary_color'] ?? '#7c3aed';
                                ?>;
        }
    </style>

    <!-- 移除了Font Awesome CDN，使用SVG图标替代 -->
    <script src="assets/js/theme.js" defer></script>

    <!-- 登录状态管理JavaScript -->
    <script>
        (function() {
            const defaultColor = <?php echo json_encode($favicon_color, JSON_UNESCAPED_UNICODE); ?>;
            function buildFavicon(color) {
                const svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="12" fill="' + color + '"/><text x="32" y="45" text-anchor="middle" fill="#fff" font-size="46" font-family="Arial,Helvetica,sans-serif" font-weight="900">Q</text></svg>';
                return 'data:image/svg+xml,' + encodeURIComponent(svg);
            }
            function applyFaviconByTheme() {
                const cssColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim();
                const color = cssColor || defaultColor || '#10b981';
                const href = buildFavicon(color);
                const links = document.querySelectorAll('link[rel="icon"], link[rel="shortcut icon"]');
                links.forEach(function(link) {
                    link.href = href;
                });
            }
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', applyFaviconByTheme);
            } else {
                applyFaviconByTheme();
            }
            const observer = new MutationObserver(applyFaviconByTheme);
            observer.observe(document.documentElement, {
                attributes: true,
                attributeFilter: ['style', 'class']
            });
        })();

        // 检查登录状态并更新页面按钮显示
        function checkLoginStatus() {
            // 检查是否有登录状态标记
            const isLoggedIn = document.body.classList.contains('logged-in');

            // 更新页面按钮显示
            updateButtonDisplay(isLoggedIn);

            // 如果是登录状态，添加事件监听器
            if (isLoggedIn) {
                setupLogoutHandler();
            }
        }

        // 更新按钮显示状态
        function updateButtonDisplay(isLoggedIn) {
            // 更新导航栏按钮
            const navLoginBtn = document.querySelector('.nav-actions .btn-outline');
            const navRegisterBtn = document.querySelector('.nav-actions .btn-primary');
            const sidebarLoginBtn = document.querySelector('.user-actions .btn-primary');
            const sidebarRegisterBtn = document.querySelector('.user-actions .btn-outline');

            if (isLoggedIn) {
                // 隐藏登录注册按钮，显示退出按钮
                if (navLoginBtn) navLoginBtn.style.display = 'none';
                if (navRegisterBtn) navRegisterBtn.style.display = 'none';
                if (sidebarLoginBtn) sidebarLoginBtn.style.display = 'none';
                if (sidebarRegisterBtn) sidebarRegisterBtn.style.display = 'none';

                // 创建退出按钮
                createLogoutButtons();

                // 创建立即发帖按钮
                createPostButton();
            } else {
                // 显示登录注册按钮
                if (navLoginBtn) navLoginBtn.style.display = 'inline-block';
                if (navRegisterBtn) navRegisterBtn.style.display = 'inline-block';
                if (sidebarLoginBtn) sidebarLoginBtn.style.display = 'inline-block';
                if (sidebarRegisterBtn) sidebarRegisterBtn.style.display = 'inline-block';

                // 移除退出按钮
                removeLogoutButtons();

                // 移除立即发帖按钮
                removePostButton();
            }
        }

        // 创建退出按钮
        function createLogoutButtons() {
            // 导航栏退出按钮
            const navActions = document.querySelector('.nav-actions');
            if (navActions && !navActions.querySelector('.logout-btn')) {
                const logoutBtn = document.createElement('a');
                logoutBtn.href = '/admin/login.php?action=logout';
                logoutBtn.className = 'btn btn-danger logout-btn';
                logoutBtn.textContent = '退出';
                logoutBtn.style.marginLeft = '10px';
                navActions.appendChild(logoutBtn);
            }

            // 侧边栏退出按钮
            const userActions = document.querySelector('.user-actions');
            if (userActions && !userActions.querySelector('.logout-btn')) {
                const logoutBtn = document.createElement('a');
                logoutBtn.href = '/admin/login.php?action=logout';
                logoutBtn.className = 'btn btn-danger logout-btn';
                logoutBtn.textContent = '退出登录';
                logoutBtn.style.marginTop = '10px';
                logoutBtn.style.width = '100%';
                userActions.appendChild(logoutBtn);
            }
        }

        // 创建立即发帖按钮
        function createPostButton() {
            // 导航栏立即发帖按钮
            const navActions = document.querySelector('.nav-actions');
            if (navActions && !navActions.querySelector('.post-btn')) {
                const postBtn = document.createElement('a');
                postBtn.href = '/post';
                postBtn.className = 'btn btn-success post-btn';
                postBtn.textContent = '立即发帖';
                postBtn.style.marginLeft = '10px';
                navActions.appendChild(postBtn);
            }

            // 侧边栏立即发帖按钮
            const userActions = document.querySelector('.user-actions');
            if (userActions && !userActions.querySelector('.post-btn')) {
                const postBtn = document.createElement('a');
                postBtn.href = '/post';
                postBtn.className = 'btn btn-success post-btn';
                postBtn.textContent = '立即发帖';
                postBtn.style.marginTop = '10px';
                postBtn.style.width = '100%';
                userActions.appendChild(postBtn);
            }
        }

        // 移除退出按钮
        function removeLogoutButtons() {
            const logoutBtns = document.querySelectorAll('.logout-btn');
            logoutBtns.forEach(btn => btn.remove());
        }

        // 移除立即发帖按钮
        function removePostButton() {
            const postBtns = document.querySelectorAll('.post-btn');
            postBtns.forEach(btn => btn.remove());
        }

        // 设置退出处理程序
        function setupLogoutHandler() {
            const logoutBtns = document.querySelectorAll('.logout-btn');
            logoutBtns.forEach(btn => {
                btn.addEventListener('click', function(e) {
                    e.preventDefault();
                    if (confirm('确定要退出登录吗？')) {
                        // 在跳转到退出处理URL前，先清除所有与登录相关的localStorage数据
                        try {
                            localStorage.removeItem('is_logged_in');
                            localStorage.removeItem('qkcms_logged_in');
                            localStorage.removeItem('qkcms_user_nickname');
                            localStorage.removeItem('username');
                        } catch (err) {
                            console.error('清除localStorage失败:', err);
                        }
                        // 移除logged-in类
                        document.body.classList.remove('logged-in');
                        // 跳转到退出处理URL
                        window.location.href = this.href;
                    }
                });
            });
        }

        // 页面加载完成后检查登录状态
        document.addEventListener('DOMContentLoaded', function() {
            checkLoginStatus();
        });

        // 监听登录成功事件（从登录页面跳转回来时触发）
        window.addEventListener('load', function() {
            // 检查URL参数判断是否登录成功
            const urlParams = new URLSearchParams(window.location.search);
            if (urlParams.has('login_success')) {
                // 标记为已登录状态
                document.body.classList.add('logged-in');
                checkLoginStatus();
            }
        });

        // 统一显示加载动画函数
        function showLoading(text) {
            const loading = document.getElementById('login-loading');
            const loadingText = document.getElementById('loading-text');
            if (loading && loadingText) {
                loadingText.textContent = text || '正在加载...';
                loading.style.display = 'flex';
            }
        }

        // 简化的登录表单提交处理
        document.addEventListener('DOMContentLoaded', function() {
            const loginForm = document.getElementById('login-form');
            if (loginForm) {
                loginForm.addEventListener('submit', function(e) {
                    e.preventDefault();

                    const username = document.getElementById('username').value;
                    const password = document.getElementById('password').value;

                    // 显示加载动画
                    showLoading('正在登录中...');

                    // 直接提交表单，让PHP处理登录和跳转
                    // 创建隐藏表单进行提交，避免AJAX的延迟
                    const hiddenForm = document.createElement('form');
                    hiddenForm.method = 'POST';
                    hiddenForm.style.display = 'none';

                    const loginInput = document.createElement('input');
                    loginInput.type = 'hidden';
                    loginInput.name = 'login';
                    loginInput.value = '1';
                    hiddenForm.appendChild(loginInput);

                    const usernameInput = document.createElement('input');
                    usernameInput.type = 'hidden';
                    usernameInput.name = 'username';
                    usernameInput.value = username;
                    hiddenForm.appendChild(usernameInput);

                    const passwordInput = document.createElement('input');
                    passwordInput.type = 'hidden';
                    passwordInput.name = 'password';
                    passwordInput.value = password;
                    hiddenForm.appendChild(passwordInput);

                    document.body.appendChild(hiddenForm);

                    // 稍微延时一点点提交，让用户能看到动画
                    setTimeout(() => {
                        hiddenForm.submit();
                    }, 100);
                });
            }

            // 注册表单提交处理
            const registerForm = document.getElementById('register-form');
            if (registerForm) {
                registerForm.addEventListener('submit', function() {
                    showLoading('正在注册中...');
                });
            }
        });

        // 为所有页面添加消息监听，处理异步登录成功事件
        window.addEventListener('message', function(event) {
            if (event.data && event.data.type === 'login_success') {
                // 标记为已登录状态
                document.body.classList.add('logged-in');

                // 立即更新UI，避免闪烁
                updateButtonDisplay(true);

                // 同步登录状态到localStorage
                localStorage.setItem('is_logged_in', 'true');

                // 如果有用户信息，保存到localStorage
                if (event.data.user_info) {
                    localStorage.setItem('username', event.data.user_info.username);
                }
            }
        });
    </script>
    <style>
        /* 全局样式和主题配色方案 */
        :root {
            --primary: var(--primary-color, #7c3aed);
            --primary-dark: #<?php echo substr(ltrim($settings['primary_color'] ?? '#7c3aed', '#'), 0, 6);
                                ?>80;
            --primary-light: #<?php echo substr(ltrim($settings['primary_color'] ?? '#7c3aed', '#'), 0, 6);
                                ?>FF;
            --secondary: #<?php echo substr(ltrim($settings['primary_color'] ?? '#7c3aed', '#'), 0, 6);
                            ?>FF;
            --text-primary: #1e293b;
            --text-secondary: #64748b;
            --text-light: #94a3b8;
            --bg-primary: #ffffff;
            --bg-secondary: #f8fafc;
            --bg-tertiary: #f1f5f9;
            --bg-quaternary: #e2e8f0;
            --border-color: #e2e8f0;
            --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
            --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            --error-color: #ef4444;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: "Microsoft YaHei", "微软雅黑", -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            color: var(--text-primary);
            background: #f8fafc;
            line-height: 1.6;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            padding: 20px;
            position: relative;
            overflow: hidden;
        }

        .container {
            width: 100%;
            max-width: 400px;
            margin: 0 auto;
        }

        /* 按钮样式 */
        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
            padding: 10px 20px;
            border-radius: 6px;
            font-weight: 500;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s ease;
            border: none;
            outline: none;
            width: 100%;
        }

        .btn-primary {
            background-color: var(--primary);
            color: white;
        }

        .btn-primary:hover {
            filter: brightness(0.9);
            transform: translateY(-1px);
            box-shadow: var(--shadow-md);
        }

        /* 登录卡片样式 */
        .login-card {
            background-color: var(--bg-primary);
            border-radius: 16px;
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.05);
            padding: 40px;
            width: 100%;
            position: relative;
            overflow: hidden;
            z-index: 1;
            backdrop-filter: blur(8px);
            border: 1px solid rgba(255, 255, 255, 0.8);
        }


        /* 认证选项卡样式 */
        .auth-tabs {
            display: flex;
            border-radius: 8px;
            overflow: hidden;
            margin: 20px 0;
            border: 1px solid var(--border-color);
        }

        .auth-tab {
            flex: 1;
            padding: 10px 20px;
            background-color: transparent;
            border: none;
            cursor: pointer;
            font-weight: 500;
            color: var(--text-secondary);
            transition: all 0.3s ease;
        }

        .auth-tab.active {
            background-color: var(--primary);
            color: white;
        }

        .auth-tab:hover:not(.active) {
            background-color: var(--bg-tertiary);
        }

        /* 成功提示 */
        .success-message {
            background-color: rgba(16, 185, 129, 0.1);
            color: #10b981;
            padding: 12px 16px;
            border-radius: 6px;
            border: 1px solid rgba(16, 185, 129, 0.2);
            margin-bottom: 20px;
            font-size: 13px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .login-header {
            text-align: center;
            margin-bottom: 0px;
        }

        .login-logo {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 12px;
            font-size: 30px;
            font-weight: 700;
            color: var(--primary);
            margin-bottom: 16px;
            text-decoration: none
        }

        .logo-icon {
            width: 32px;
            height: 32px;
        }

        .login-title {
            font-size: 20px;
            font-weight: 600;
            color: var(--text-primary);
            margin-bottom: 8px;
        }

        .login-subtitle {
            font-size: 14px;
            color: var(--text-secondary);
        }

        /* 表单样式 */
        .form-group {
            margin-bottom: 20px;
            position: relative;
        }

        .form-label {
            display: block;
            font-size: 14px;
            font-weight: 500;
            color: var(--text-primary);
            margin-bottom: 3px;
        }

        .form-label-row {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 3px;
        }

        .form-inline-link {
            font-size: 12px;
            color: var(--text-secondary) !important;
            text-decoration: none;
            cursor: pointer;
        }

        .form-inline-link:hover {
            text-decoration: underline;
        }

        .email-bound-tip {
            margin-top: 6px;
            font-size: 12px;
            color: #059669;
            display: none;
        }

        .form-input {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid var(--border-color);
            border-radius: 8px;
            font-size: 14px;
            color: var(--text-primary);
            background-color: var(--bg-primary);
            transition: all 0.3s ease;
            outline: none;
        }

        .form-input:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(147, 51, 234, 0.1);
        }

        .form-input::placeholder {
            color: var(--text-light);
        }

        .form-icon {
            position: absolute;
            right: 14px;
            top: 40px;
            color: var(--text-light);
            font-size: 20px;
            width: 20px;
            height: 20px;
        }

        .cursor-pointer {
            cursor: pointer;
        }

        .form-icon.cursor-pointer:hover {
            color: var(--primary);
        }

        /* 错误提示 */
        .error-message {
            background-color: rgba(239, 68, 68, 0.1);
            color: var(--error-color);
            padding: 12px 16px;
            border-radius: 6px;
            border: 1px solid rgba(239, 68, 68, 0.2);
            margin-bottom: 20px;
            font-size: 13px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        /* 页脚样式 */
        .login-footer {
            text-align: center;
            margin-top: 24px;
            font-size: 13px;
            color: var(--text-secondary);
        }

        .login-footer a {
            color: var(--primary);
            text-decoration: none;
            transition: color 0.3s ease;
        }

        .login-footer a:hover {
            color: var(--primary-dark);
        }




        /* 背景容器 */
        .bg-animation-container {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: -1;
            overflow: hidden;
        }

        /* 柔和背景元素 */
        .bg-element {
            position: absolute;
            border-radius: 50%;
            background: var(--primary);
            opacity: 0.1;
            /* 适当增加透明度，使其更加明显但仍保持柔和 */
            filter: blur(50px);
            /* 稍微减少模糊度，使效果更加明显 */
        }

        /* 第一个背景元素 */
        .bg-element-1 {
            width: 600px;
            height: 600px;
            top: -300px;
            left: -200px;
            animation: floatAnimation 60s ease-in-out infinite;
            animation-delay: 0s;
        }

        /* 第二个背景元素 */
        .bg-element-2 {
            width: 800px;
            height: 800px;
            bottom: -400px;
            right: -300px;
            background: var(--primary-light);
            animation: floatAnimation 80s ease-in-out infinite;
            animation-delay: -20s;
        }

        /* 第三个背景元素 */
        .bg-element-3 {
            width: 500px;
            height: 500px;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: var(--primary-dark);
            animation: floatAnimation 70s ease-in-out infinite;
            animation-delay: -40s;
        }

        /* 自然浮动动画 */
        @keyframes floatAnimation {

            0%,
            100% {
                transform: translate(0, 0) scale(1);
            }

            25% {
                transform: translate(50px, 50px) scale(1.05);
            }

            50% {
                transform: translate(0, 100px) scale(1);
            }

            75% {
                transform: translate(-50px, 50px) scale(0.95);
            }
        }




        <script src="/assets/js/toast.js"></script><style>

        /* 独立页面模式：恢复居中和阴影 */
        body.is-full-page {
            display: flex !important;
            justify-content: center !important;
            align-items: center !important;
            background: linear-gradient(135deg, var(--bg-primary) 0%, var(--bg-secondary) 100%) !important;
            min-height: 100vh !important;
            padding: 20px !important;
        }

        body.is-full-page .container {
            width: 100% !important;
            max-width: 400px !important;
            margin: 0 auto !important;
        }

        body.is-full-page .login-card {
            background-color: var(--bg-primary) !important;
            border-radius: 16px !important;
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.05) !important;
            padding: 40px !important;
            width: 100% !important;
            height: 520px !important;
            /* 全屏页面恢复 520px 高度 */
            position: relative !important;
            overflow: hidden !important;
            z-index: 1 !important;
            backdrop-filter: blur(8px) !important;
            border: 1px solid rgba(255, 255, 255, 0.8) !important;
            display: flex !important;
            flex-direction: column !important;
            justify-content: center !important;
            /* 内容垂直居中 */
        }

        /* 独立页面模式下的顶部横线 */
        body.is-full-page .login-card::before {
            content: '' !important;
            position: absolute !important;
            top: 0 !important;
            left: 0 !important;
            right: 0 !important;
            height: 4px !important;
            background: linear-gradient(90deg, var(--primary-light), var(--primary), var(--primary-dark)) !important;
            z-index: 2 !important;
            display: block !important;
        }

        body.is-full-page .auth-tabs,
        body.is-full-page #login-form,
        body.is-full-page #register-form,
        body.is-full-page .login-header,
        body.is-full-page .login-footer {
            padding: 0 !important;
            margin-left: 0 !important;
            margin-right: 0 !important;
        }

        body.is-full-page .bg-animation-container {
            display: block !important;
        }

        /* 模态框模式：全填充 */
        body.is-modal {
            font-family: "Microsoft YaHei", "微软雅黑", sans-serif !important;
            background: #fff !important;
            margin: 0 !important;
            padding: 0 !important;
            min-height: 100vh;
            display: block !important;
            overflow-y: auto !important;
        }

        body.is-modal .bg-animation-container {
            display: none !important;
        }

        body.is-modal .container {
            width: 100% !important;
            max-width: none !important;
            margin: 0 !important;
            padding: 0 !important;
            background: #fff !important;
        }

        body.is-modal .login-card {
            box-shadow: none !important;
            border: none !important;
            background: #fff !important;
            width: 100% !important;
            margin: 0 !important;
            padding: 20px 0 0 0 !important;
            /* 弹窗模式：底部无内边距，减少高度 */
            border-radius: 0 !important;
        }

        body.is-modal .login-card::before {
            display: none !important;
            content: none !important;
        }

        body.is-modal .login-logo {
            font-size: 24px !important;
            /* 减小字体大小 */
            margin-bottom: 10px !important;
            /* 减小底部间距 */
            pointer-events: none !important;
            /* 弹窗模式下禁用 LOGO 点击跳转 */
            cursor: default !important;
            text-decoration: none !important;
        }

        body.is-modal .login-header {
            width: 100% !important;
            max-width: none !important;
            padding: 10px 60px 0 60px !important;
            /* 减小顶部边距 */
            box-sizing: border-box !important;
        }

        body.is-modal #login-form,
        body.is-modal #register-form {
            width: 100% !important;
            max-width: none !important;
            padding: 0 60px !important;
            box-sizing: border-box !important;
        }

        /* 统一表单初始显示逻辑，由 PHP 控制，方便 JS 切换 */
        #register-form {
            display: <?php echo (isset($showRegisterForm) && $showRegisterForm) ? 'block' : 'none'; ?>;
        }

        #login-form {
            display: <?php echo (isset($showRegisterForm) && $showRegisterForm) ? 'none' : 'block'; ?>;
        }

        body.is-modal .form-group {
            margin-bottom: 15px !important;
            /* 减小表单组间距 */
        }

        body.is-modal .form-label {
            color: var(--text-secondary) !important;
            font-weight: normal !important;
            margin-bottom: 4px !important;
            /* 减小标签底部间距 */
        }

        body.is-modal .btn {
            margin-top: 5px !important;
            /* 减小按钮顶部间距 */
        }

        body.is-modal .auth-tabs {
        
            margin: 10px 60px !important;
            margin-top: 15px !important;
          
        }

        body.is-modal .login-footer {
            margin-top: 15px !important;
            /* 减小页脚间距 */
            padding: 0 60px !important;
        }

        /* 第三方登录占位（共用） */
        .social-login-container {
            margin-top: 15px;
            /* 减小间距 */
            padding-bottom: 15px;
            text-align: center;
            width: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }

        body.is-modal .social-login-container {
            margin-top: 10px !important;
            /* 弹窗模式：进一步减小与上方表单的间距 */
            padding-bottom: 0px !important;
        }

        .social-login-title {
            font-size: 13px;
            /* 稍微减小字体 */
            color: var(--text-secondary);
            margin-bottom: 10px;
            /* 减小底部间距 */
            width: 100%;
            text-align: center;
        }

        .social-login-buttons {
            display: flex;
            justify-content: center;
            gap: 15px;
            /* 减小按钮间距 */
            width: 100%;
        }

        .social-login-item {
            width: 38px;
            /* 稍微减小尺寸 */
            height: 38px;
            border-radius: 50%;
            background: #fff;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
            text-decoration: none;
            overflow: hidden;
        }

        .social-login-item:hover:not(.disabled) {
            transform: scale(1.1);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        .social-login-item.disabled {
            filter: grayscale(1);
            opacity: 0.5;
            cursor: not-allowed;
            pointer-events: none;
        }

        .social-login-item img {
            width: 26px;
            /* 稍微减小图标尺寸 */
            height: 26px;
            object-fit: contain;
            display: block;
        }

        /* 全局统一提示框样式（同步自 admin.css） */
        #toast-container {
            position: fixed;
            top: 50% !important;
            left: 50% !important;
            transform: translate(-50%, -50%) !important;
            z-index: 10001 !important;
            display: flex;
            flex-direction: column;
            gap: 10px;
            align-items: center;
            pointer-events: none;
        }

        .toast {
            background-color: rgba(0, 0, 0, 0.85) !important;
            color: white !important;
            padding: 12px 24px !important;
            border-radius: 6px !important;
            font-size: 14px !important;
            font-weight: 500 !important;
            max-width: 400px !important;
            white-space: normal !important;
            text-align: center !important;
            line-height: 1.5 !important;
            opacity: 0 !important;
            transform: scale(0.9) !important;
            transition: opacity 0.3s ease, transform 0.3s ease !important;
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1) !important;
            display: inline-flex !important;
            align-items: center !important;
            justify-content: center !important;
            min-height: 44px !important;
            backdrop-filter: blur(4px) !important;
        }

        .toast.toast-visible {
            opacity: 1 !important;
            transform: scale(1) !important;
        }

        .toast.toast-error {
            background-color: rgba(255, 69, 0, 0.85) !important;
        }

        .toast.toast-success {
            background-color: rgba(16, 185, 129, 0.85) !important;
        }

        /* 隐藏原有的 PHP 消息（全局隐藏，改用 Toast） */
        .error-message,
        .success-message {
            display: none !important;
        }

        /* 登录加载动画 */
        .login-loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: #ffffff;
            display: none;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            z-index: 100;
        }

        .qk-spinner {
            width: 72px;
            height: 72px;
            border-radius: 50%;
            background: conic-gradient(from 0deg, var(--primary), rgba(124, 58, 237, 0.08));
            -webkit-mask: radial-gradient(farthest-side, transparent calc(100% - 10px), #000 0);
            mask: radial-gradient(farthest-side, transparent calc(100% - 10px), #000 0);
            margin-bottom: 14px;
            animation: qk-spin 0.9s linear infinite;
            position: relative;
        }

        .qk-spinner::after {
            content: '';
            position: absolute;
            inset: -10px;
            border-radius: 50%;
            background: radial-gradient(circle, rgba(124, 58, 237, 0.25), transparent 60%);
            animation: qk-pulse 1.1s ease-in-out infinite;
        }

        @keyframes qk-spin {
            0% {
                transform: rotate(0);
            }

            100% {
                transform: rotate(360deg);
            }
        }

        @keyframes qk-pulse {
            0% {
                transform: scale(0.88);
                opacity: 0.5;
            }
            50% {
                transform: scale(1.02);
                opacity: 0.9;
            }
            100% {
                transform: scale(0.88);
                opacity: 0.5;
            }
        }

        .loading-text {
            color: #64748b;
            font-size: 16px;
        }

    </style>
</head>

<body class="<?php echo isset($_GET['is_modal']) ? 'is-modal' : 'is-full-page'; ?>">
    <!-- 柔和背景装饰元素 -->
    <div class="bg-animation-container" <?php echo isset($_GET['is_modal']) ? 'style="display:none;"' : ''; ?>>
        <div class="bg-element bg-element-1"></div>
        <div class="bg-element bg-element-2"></div>
        <div class="bg-element bg-element-3"></div>
    </div>
    <div class="container">
        <div class="login-card">
            <!-- 登录加载动画 -->
            <div id="login-loading" class="login-loading-overlay">
                <div class="qk-spinner"></div>
                <div class="loading-text" id="loading-text">正在登录中...</div>
            </div>
            <div class="login-header"> <a href="index.php" class="login-logo"> <?php echo escape($settings['site_name']); ?> </a>

                <!-- 登录/注册切换选项卡 -->
                <div class="auth-tabs">
                    <button id="login-tab" class="auth-tab <?php echo (!isset($showRegisterForm) || !$showRegisterForm) ? 'active' : ''; ?>" onclick="showLoginForm()">登录</button>
                    <button id="register-tab" class="auth-tab <?php echo (isset($showRegisterForm) && $showRegisterForm) ? 'active' : ''; ?>" onclick="showRegisterForm()">注册</button>
                </div>
            </div>

            <!-- 消息提示 -->
            <?php if (!empty($error)): ?>
                <div class="error-message">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2" />
                        <line x1="12" y1="8" x2="12" y2="12" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
                        <line x1="12" y1="16" x2="12.01" y2="16" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
                    </svg>
                    <?php echo escape($error); ?>
                </div>
            <?php endif; ?>
            <?php if (!empty($success)): ?>
                <div class="success-message">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2" />
                        <path d="M8 12L11 15L16 10" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
                    </svg>
                    <?php echo escape($success); ?>
                </div>
            <?php endif; ?>

            <!-- 登录表单 -->
            <form id="login-form" method="post" action="">
                <input type="hidden" name="login" value="1">
                <div class="form-group">
                    <label for="username" class="form-label">用户名</label>
                    <input type="text" id="username" name="username" class="form-input" placeholder="请输入用户名" value="<?php echo isset($registered_username) ? htmlspecialchars($registered_username) : ''; ?>" required>
                    <svg class="form-icon" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                        <circle cx="12" cy="7" r="4"></circle>
                    </svg>
                </div>
                <div class="form-group">
                    <div class="form-label-row">
                        <label for="password" class="form-label" style="margin-bottom:0;">密码</label>
                        <?php if ($email_tool_enabled): ?>
                            <a href="javascript:void(0);" class="form-inline-link" onclick="openEmailDialog('recover')">忘记密码</a>
                        <?php endif; ?>
                    </div>
                    <input type="password" id="password" name="password" class="form-input" placeholder="请输入密码" value="<?php echo isset($registered_password) ? htmlspecialchars($registered_password) : ''; ?>" required>
                    <svg id="toggle-password" class="form-icon cursor-pointer" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" onclick="togglePasswordVisibility('password', 'toggle-password')">
                        <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
                        <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
                    </svg>
                </div>
                <button type="submit" class="btn btn-primary"> 登 录 </button>
            </form>

            <!-- 注册表单 -->
            <form id="register-form" method="post" action="">
                <input type="hidden" name="register" value="1">
                <div class="form-group">
                    <label for="reg_username" class="form-label">用户名</label>
                    <input type="text" id="reg_username" name="reg_username" class="form-input" placeholder="请输入用户名" required>
                    <svg class="form-icon" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                        <circle cx="12" cy="7" r="4"></circle>
                    </svg>
                </div>
                <div class="form-group">
                    <div class="form-label-row">
                        <label for="reg_password" class="form-label" style="margin-bottom:0;">密码</label>
                        <?php if ($email_tool_enabled): ?>
                            <a href="javascript:void(0);" class="form-inline-link" id="bind-email-link" onclick="openEmailDialog('bind')"><?php echo !empty($bound_reg_email) ? ('已绑定邮箱：' . escape($bound_reg_email)) : '绑定邮箱（用于找回密码）'; ?></a>
                        <?php endif; ?>
                    </div>
                    <input type="password" id="reg_password" name="reg_password" class="form-input" placeholder="请设置密码" required>
                    <svg id="toggle-reg-password" class="form-icon cursor-pointer" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" onclick="togglePasswordVisibility('reg_password', 'toggle-reg-password')">
                        <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
                        <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
                    </svg>
                    <input type="hidden" id="reg_email" name="reg_email" value="<?php echo isset($bound_reg_email) ? escape($bound_reg_email) : ''; ?>">
                    <input type="hidden" id="reg_email_token" name="reg_email_token" value="<?php echo isset($bound_reg_email_token) ? escape($bound_reg_email_token) : ''; ?>">
                </div>
                <button type="submit" class="btn btn-primary"> 注 册 </button>
            </form>

            <!-- 第三方登录静态 UI -->
            <div class="social-login-container">
                <div class="social-login-title"><?php echo $social_title; ?></div>
                <div class="social-login-buttons">
                    <?php
                    $redirect_param = isset($_GET['redirect']) ? '&redirect=' . urlencode($_GET['redirect']) : '';
                    ?>
                    <a href="<?php echo $wechat_enabled ? '/admin/Plugin/12_wechatlogin.php?action=login' . $redirect_param : 'javascript:void(0);'; ?>"
                        target="_top"
                        class="social-login-item wechat <?php echo !$wechat_enabled ? 'disabled' : ''; ?>"
                        title="<?php echo $wechat_enabled ? '微信扫码登录' : '微信登录暂未启用'; ?>">
                        <img src="/assets/images/weixin.png" alt="微信登录">
                    </a>
                    <a href="<?php echo $qq_enabled ? '/admin/Plugin/13_qqlogin.php?action=login' . $redirect_param : 'javascript:void(0);'; ?>"
                        target="_top"
                        class="social-login-item qq <?php echo !$qq_enabled ? 'disabled' : ''; ?>"
                        title="<?php echo $qq_enabled ? 'QQ快捷登录' : 'QQ登录暂未启用'; ?>">
                        <img src="/assets/images/qq.png" alt="QQ登录">
                    </a>
                </div>
            </div>
        </div>
    </div>
    <script>
        // 切换密码可见性函数
        function togglePasswordVisibility(passwordId, iconId) {
            const passwordInput = document.getElementById(passwordId);
            const icon = document.getElementById(iconId);

            // 切换密码输入框的类型
            const isPassword = passwordInput.type === 'password';
            passwordInput.type = isPassword ? 'text' : 'password';

            // 切换图标内容
            if (isPassword) {
                // 切换为可见图标
                icon.innerHTML = `
                    <path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7z"></path>
                    <circle cx="12" cy="12" r="3"></circle>
                `;
            } else {
                // 切换回隐藏图标
                icon.innerHTML = `
                    <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
                    <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
                `;
            }
        }

        // 登录成功后的处理函数
        function handleLoginSuccess() {
            // 设置localStorage登录状态
            localStorage.setItem('qkcms_logged_in', 'true');
            // 添加body的logged-in类
            document.body.classList.add('logged-in');
        }

        // 检查URL参数是否表示登录成功
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.has('login_success')) {
            handleLoginSuccess();
        }

        // 表单交互
        const formInputs = document.querySelectorAll('.form-input');
        formInputs.forEach(input => {
            input.addEventListener('focus', function() {
                this.parentElement.querySelector('.form-icon').style.color = 'var(--primary)';
            });

            input.addEventListener('blur', function() {
                this.parentElement.querySelector('.form-icon').style.color = 'var(--text-light)';
            });
        });

        // 显示登录表单
        function showLoginForm() {
            document.getElementById('login-form').style.display = 'block';
            document.getElementById('register-form').style.display = 'none';
            document.getElementById('login-tab').classList.add('active');
            document.getElementById('register-tab').classList.remove('active');
            document.getElementById('username').focus();
        }

        // 显示注册表单
        function showRegisterForm() {
            document.getElementById('login-form').style.display = 'none';
            document.getElementById('register-form').style.display = 'block';
            document.getElementById('register-tab').classList.add('active');
            document.getElementById('login-tab').classList.remove('active');
            document.getElementById('reg_username').focus();
        }

        const emailToolEnabled = <?php echo $email_tool_enabled ? 'true' : 'false'; ?>;
        let emailModalCloseWatchTimer = null;

        function clearParentEmailMask() {
            try {
                const hostWin = (window.parent && window.parent !== window) ? window.parent : window;
                const hostDoc = hostWin.document;
                if (!hostDoc) return;
                const mask = hostDoc.getElementById('qk-email-modal-mask');
                if (mask && mask.parentNode) {
                    mask.style.pointerEvents = 'none';
                    mask.setAttribute('data-closing', '1');
                    mask.classList.remove('visible');
                    hostWin.setTimeout(function() {
                        try {
                            if (mask.parentNode) {
                                mask.parentNode.removeChild(mask);
                            }
                        } catch (e) {}
                    }, 300);
                }
            } catch (e) {}
        }

        function stopEmailModalCloseWatch() {
            if (emailModalCloseWatchTimer) {
                clearInterval(emailModalCloseWatchTimer);
                emailModalCloseWatchTimer = null;
            }
        }

        function startEmailModalCloseWatch() {
            try {
                if (!(window.parent && window.parent !== window)) return;
                stopEmailModalCloseWatch();
                emailModalCloseWatchTimer = setInterval(function() {
                    try {
                        const modal = window.parent.document.getElementById('qk-modal-login_email');
                        if (!modal) {
                            clearParentEmailMask();
                            stopEmailModalCloseWatch();
                            return;
                        }
                        const computed = window.parent.getComputedStyle ? window.parent.getComputedStyle(modal) : null;
                        const hidden = modal.style.display === 'none' || (computed && computed.display === 'none');
                        if (hidden) {
                            clearParentEmailMask();
                            stopEmailModalCloseWatch();
                        }
                    } catch (e) {}
                }, 180);
            } catch (e) {}
        }

        function openEmailDialog(mode) {
            if (!emailToolEnabled) return;
            const m = mode === 'recover' ? 'recover' : 'bind';
            const modalHeight = m === 'recover' ? '450px' : '380px';
            try {
                if (window.parent && window.parent !== window) {
                    if (window.parent.QKModal && typeof window.parent.QKModal.show === 'function') {
                        window.parent.QKModal.show('login_email', '/admin/login.php?email_tool=1&mode=' + encodeURIComponent(m), {
                            title: m === 'recover' ? '忘记密码' : '绑定邮箱',
                            width: '500px',
                            height: modalHeight
                        });
                        startEmailModalCloseWatch();
                        return;
                    }
                }
            } catch (e) {}
            if (window.QKModal && typeof window.QKModal.show === 'function') {
                window.QKModal.show('login_email', '/admin/login.php?email_tool=1&mode=' + encodeURIComponent(m), {
                    title: m === 'recover' ? '忘记密码' : '绑定邮箱',
                    width: '420px',
                    height: modalHeight
                });
            } else {
                window.location.href = '/admin/login.php?email_tool=1&mode=' + encodeURIComponent(m) + '&is_modal=1';
            }
        }

        function closeEmailPopup() {
            stopEmailModalCloseWatch();
            clearParentEmailMask();
            try {
                if (window.parent && window.parent !== window) {
                    if (window.parent.QKModal && typeof window.parent.QKModal.close === 'function') {
                        window.parent.QKModal.close('login_email');
                    }
                    return;
                }
            } catch (e) {}
            if (window.QKModal && typeof window.QKModal.close === 'function') {
                window.QKModal.close('login_email');
            }
        }

        // 自动聚焦到用户名输入框
        document.addEventListener('DOMContentLoaded', function() {
            // PHP已经控制了表单显示，JS只负责聚焦输入框
            <?php if (isset($showRegisterForm) && $showRegisterForm): ?>
                // 注册表单显示时，聚焦到注册用户名输入框
                document.getElementById('reg_username').focus();
            <?php else: ?>
                // 登录表单显示时，聚焦到登录用户名输入框
                document.getElementById('username').focus();
            <?php endif; ?>

            // 统一使用 Toast 提示消息
            <?php if (!empty($error) || !empty($success)): ?>
                    (function() {
                        const msg = '<?php echo addslashes($error ?: $success); ?>';
                        const type = '<?php echo !empty($error) ? "error" : "success"; ?>';

                        const trigger = () => {
                            if (typeof showToast === 'function') {
                                showToast(msg, type);
                            } else if (window.parent && typeof window.parent.showToast === 'function') {
                                window.parent.showToast(msg, type);
                            } else {
                                // 极简版后备逻辑，不再弹出浏览器系统弹窗
                                let container = document.getElementById('toast-container');
                                if (!container) {
                                    container = document.createElement('div');
                                    container.id = 'toast-container';
                                    document.body.appendChild(container);
                                }
                                const toast = document.createElement('div');
                                toast.className = 'toast toast-' + type;
                                toast.innerText = msg;
                                container.appendChild(toast);
                                setTimeout(() => toast.classList.add('toast-visible'), 10);
                                setTimeout(() => {
                                    toast.classList.remove('toast-visible');
                                    setTimeout(() => toast.remove(), 300);
                                }, 2000);
                            }
                        };

                        // 稍微延时以确保脚本完全初始化
                        setTimeout(trigger, 200);
                    })();
            <?php endif; ?>
        });

        window.addEventListener('message', function(event) {
            if (!event || !event.data) return;
            if (event.data.type === 'qk_email_bound') {
                const emailInput = document.getElementById('reg_email');
                const tokenInput = document.getElementById('reg_email_token');
                const bindLink = document.getElementById('bind-email-link');
                if (emailInput && tokenInput) {
                    emailInput.value = event.data.email || '';
                    tokenInput.value = event.data.token || '';
                }
                if (bindLink && event.data.email) {
                    bindLink.textContent = '已绑定邮箱：' + event.data.email;
                }
                closeEmailPopup();
            }
            if (event.data.type === 'qk_password_reset_done') {
                closeEmailPopup();
                showLoginForm();
                if (event.data.username) {
                    const usernameInput = document.getElementById('username');
                    if (usernameInput) usernameInput.value = event.data.username;
                }
                if (typeof showToast === 'function') {
                    showToast('密码已重置，请登录', 'success');
                }
            }
        });

    </script>
</body>

</html>
<?php
// 解析插件标签
$content = ob_get_clean();
if (function_exists('parse_plugin_tags')) {
    $content = parse_plugin_tags($content);
}
echo $content;
