<?php
session_start();
require 'config.php';
if (!isset($conn)) {
    die("连接失败：\$conn 未定义");
}

// 检测是否存在有效的 Token
$token = isset($_COOKIE['auth_token']) ? $_COOKIE['auth_token'] : null;
if ($token) {
    $stmt = $conn->prepare("SELECT id, username, email FROM users WHERE token = ?");
    $stmt->bind_param("s", $token);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($id, $username, $email);
    $stmt->fetch();

    if ($stmt->num_rows > 0) {
        // 存储用户信息到会话
        $_SESSION['user_id'] = $id;
        $_SESSION['username'] = $username;

        // 显示自动登录提示页面
        ?>
        <!DOCTYPE html>
        <html lang="zh-CN">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>自动登录中 | 圆周云境</title>
            <script src="https://cdn.tailwindcss.com"></script>
            <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
            <style>
            .toast-container {
                    position: fixed;
                    bottom: 20px;
                    right: 20px;
                    display: flex;
                    flex-direction: column;
                    gap: 10px;
                    z-index: 1000;
                }
                /* 修改提示框样式 */
                .toast {
                    background-color: #fff; /* 背景颜色改为白色 */
                    color: #333; /* 文本颜色改为深灰色 */
                    padding: 12px 20px; /* 增加内边距 */
                    border-radius: 8px; /* 增加圆角 */
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    width: 280px; /* 增加宽度 */
                    animation: fadeIn 0.5s ease-out forwards;
                    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1); /* 添加阴影 */
                    border: 1px solid #e0e0e0; /* 添加边框 */
                }
                .toast.hide {
                    animation: fadeOut 0.5s ease-out forwards;
                }
                @keyframes fadeIn {
                    from { opacity: 0; transform: translateY(10px); }
                    to { opacity: 1; transform: translateY(0); }
                }
                @keyframes fadeOut {
                    from { opacity: 1; transform: translateY(0); }
                    to { opacity: 0; transform: translateY(10px); }
                }
                @keyframes countdown {
                    from { width: 0%; }
                    to { width: 100%; }
                }
                .countdown-bar {
                    animation: countdown 3s linear forwards;
                }
            </style>
        </head>
        <body class="bg-gray-100 dark:bg-gray-900 flex items-center justify-center min-h-screen">
            <div class="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6 max-w-md w-full">
                <div class="flex items-center justify-center mb-6">
                    <div class="w-12 h-12 rounded-full bg-blue-100 dark:bg-blue-900 flex items-center justify-center">
                        <i class="fa fa-check text-blue-500 dark:text-blue-300 text-xl"></i>
                    </div>
                </div>
                <h2 class="text-xl font-bold text-center text-gray-800 dark:text-white mb-2">自动登录中</h2>
                <p class="text-gray-600 dark:text-gray-300 text-center mb-6">
                    检测到有效会话，将自动登录到您的账户
                </p>
                
                <div class="bg-gray-200 dark:bg-gray-700 rounded-full h-2 mb-6 overflow-hidden">
                    <div class="countdown-bar bg-blue-500 h-full" style="width: 100%;"></div>
                </div>
                
                <div class="bg-gray-100 dark:bg-gray-700 rounded-lg p-4">
                    <div class="flex items-center mb-2">
                        <i class="fa fa-user text-gray-500 dark:text-gray-300 mr-2"></i>
                        <span class="text-gray-700 dark:text-gray-200"><?php echo htmlspecialchars($username); ?></span>
                    </div>
                    <div class="flex items-center">
                        <i class="fa fa-envelope text-gray-500 dark:text-gray-300 mr-2"></i>
                        <span class="text-gray-700 dark:text-gray-200"><?php echo htmlspecialchars($email); ?></span>
                    </div>
                </div>
                
                <p class="text-center text-sm text-gray-500 dark:text-gray-400 mt-4">
                    3秒后自动跳转，或<a href="../console/index.php" class="text-blue-500 hover:underline">立即前往</a>
                </p>
                
                <p class="text-center text-sm text-gray-500 dark:text-gray-400 mt-4">
                    <a href="../console/logout.php" class="text-red-500 hover:underline">登录其他账号</a>
                </p>
            </div>
            
            <div class="toast-container"></div>
            
            <script>
                // 自动跳转
                setTimeout(function() {
                    window.location.href = "../console/?login=success";
                }, 3000);
            </script>
        </body>
        </html>
        <?php
        exit();
    }
}
?>

<!DOCTYPE html>
<html lang="zh-CN" class="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
    <title>圆周云境 | 登录与注册</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 配置Tailwind -->
    <script>
        tailwind.config = {
            darkMode: 'class',
            theme: {
                extend: {
                    colors: {
                        primary: {
                            light: '#165DFF',
                            dark: '#3C7EFF'
                        },
                        secondary: {
                            light: '#36BFFA',
                            dark: '#5AC8FA'
                        },
                        dark: {
                            light: '#1D2939',
                            dark: '#F9FAFB'
                        },
                        light: {
                            light: '#F9FAFB',
                            dark: '#1D2939'
                        },
                        'gray-medium': {
                            light: '#667085',
                            dark: '#98A2B3'
                        },
                        'dark-bg': '#0F172A',
                        'dark-card': '#1E293B',
                        'dark-border': '#334155'
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                    boxShadow: {
                        'card': '0 10px 30px -5px rgba(0, 0, 0, 0.1)',
                        'button': '0 4px 6px -1px rgba(22, 93, 255, 0.2)',
                        'dark-card': '0 10px 30px -5px rgba(0, 0, 0, 0.3)'
                    }
                },
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .form-input-focus {
                @apply ring-2 ring-primary-light/30 border-primary-light dark:ring-primary-dark/30 dark:border-primary-dark;
            }
            .auth-btn {
                @apply w-full py-3 px-4 bg-primary-light text-white font-medium rounded-lg shadow-button transition-all duration-300 hover:bg-primary-light/90 hover:-translate-y-1 active:translate-y-0 focus:outline-none focus:ring-2 focus:ring-primary-light/50 dark:bg-primary-dark dark:hover:bg-primary-dark/90 dark:focus:ring-primary-dark/50;
            }
            .toggle-btn {
                @apply py-2 px-4 font-medium rounded-lg transition-all duration-300 border;
            }
            .toggle-btn-active {
                @apply bg-primary-light/10 text-primary-light border-primary-light dark:bg-primary-dark/10 dark:text-primary-dark dark:border-primary-dark;
            }
            .toggle-btn-inactive {
                @apply bg-transparent text-gray-medium-light hover:bg-gray-100 border-gray-200 dark:text-gray-medium-dark dark:hover:bg-gray-800 dark:border-gray-700;
            }
            .fade-in {
                animation: fadeIn 0.3s ease-in-out forwards;
            }
            .fade-out {
                animation: fadeOut 0.3s ease-in-out forwards;
            }
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        @keyframes fadeOut {
            from { opacity: 1; transform: translateY(0); }
            to { opacity: 0; transform: translateY(-10px); }
        }
        .toast-container {
                    position: fixed;
                    bottom: 20px;
                    right: 20px;
                    display: flex;
                    flex-direction: column;
                    gap: 10px;
                    z-index: 1000;
                }
                /* 修改提示框样式 */
                .toast {
                    background-color: black; /* 背景颜色改为白色 */
                    color: #fff; /* 文本颜色改为深灰色 */
                    padding: 12px 20px; /* 增加内边距 */
                    border-radius: 8px; /* 增加圆角 */
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    width: 280px; /* 增加宽度 */
                    animation: fadeIn 0.5s ease-out forwards;
                    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1); /* 添加阴影 */
                    border: 1px solid #e0e0e0; /* 添加边框 */
                }
                .toast.hide {
                    animation: fadeOut 0.5s ease-out forwards;
                }
    </style>
</head>
<body class="bg-gradient-to-br from-light-light to-gray-100 dark:from-dark-bg dark:to-gray-900 font-inter min-h-screen flex flex-col">
    <!-- 顶部导航 -->
    <header class="bg-white dark:bg-dark-card shadow-sm sticky top-0 z-50">
        <div class="container mx-auto px-4 py-4 flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <div class="w-10 h-10 rounded-lg bg-white dark:bg-white flex items-center justify-center border border-gray-200 dark:border-gray-300">
                    <img src="../logo-sm.png" alt="圆周云境logo" 
         class="w-8 h-8 object-contain filter brightness-90 contrast-110 
                group-hover:brightness-100 transition-all">
                </div>
                <h1 class="text-xl font-bold text-dark-light dark:text-dark-dark">CCSIT</h1>
            </div>
        </div>
        <div class="h-1 bg-gradient-to-r from-primary-light to-secondary-light dark:from-primary-dark dark:to-secondary-dark"></div>
    </header>

    <!-- 主内容区 -->
    <main class="flex-grow flex items-center justify-center p-4 md:p-8">
        <div class="w-full max-w-md">
            <!-- 卡片容器 -->
            <div class="bg-white dark:bg-dark-card rounded-2xl shadow-card dark:shadow-dark-card overflow-hidden transition-all duration-500 hover:shadow-lg dark:hover:shadow-lg">
                <!-- 卡片头部 -->
                <div class="p-6 bg-gradient-to-r from-primary-light to-secondary-light dark:from-primary-dark dark:to-secondary-dark text-white">
                    <h2 id="auth-title" class="text-2xl font-bold mb-2">CCSID</h2>
                    <p class="text-white/80 text-sm">CCSID统一登录系统</p>
                </div>
                
                <!-- 切换按钮 -->
                <div class="flex p-4 border-b border-gray-100 dark:border-dark-border">
                    <button id="switch-to-login" class="toggle-btn toggle-btn-active mr-2" onclick="switchToLogin()">
                        <i class="fa fa-sign-in mr-2"></i>登录
                    </button>
                    <button id="switch-to-register" class="toggle-btn toggle-btn-inactive" onclick="switchToRegister()">
                        <i class="fa fa-user-plus mr-2"></i>注册
                    </button>
                </div>
                
                <!-- 登录表单 -->
                <div id="login-form" class="p-6">
                    <form id="loginForm" class="space-y-5">
                        <div>
                            <label for="login-username" class="block text-sm font-medium text-gray-medium-light dark:text-gray-medium-dark mb-1">账号</label>
                            <div class="relative">
                                <div class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none text-gray-medium-light dark:text-gray-medium-dark">
                                    <i class="fa fa-user"></i>
                                </div>
                                <input type="text" id="login-username" name="username" placeholder="注册时填写的圆周云境用户账号" required 
                                    class="w-full pl-10 pr-4 py-3 border border-gray-200 dark:border-dark-border rounded-lg focus:outline-none transition-all duration-300 focus:form-input-focus bg-white dark:bg-dark-card text-gray-900 dark:text-gray-100">
                            </div>
                        </div>
                        
                        <div>
                            <label for="login-password" class="block text-sm font-medium text-gray-medium-light dark:text-gray-medium-dark mb-1">密码</label>
                            <div class="relative">
                                <div class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none text-gray-medium-light dark:text-gray-medium-dark">
                                    <i class="fa fa-lock"></i>
                                </div>
                                <input type="password" id="login-password" name="password" placeholder="密码" required 
                                    class="w-full pl-10 pr-4 py-3 border border-gray-200 dark:border-dark-border rounded-lg focus:outline-none transition-all duration-300 focus:form-input-focus bg-white dark:bg-dark-card text-gray-900 dark:text-gray-100">
                            </div>
                        </div>
                        
                        <div>
                            <label for="turnstile" class="block text-sm font-medium text-gray-medium-light dark:text-gray-medium-dark mb-2">请确认您是人类:</label>
                            <div class="cf-turnstile" data-sitekey="0x4AAAAAABj3qHrHXwWdG7WG"></div>
                        </div>
                        
                        <div class="pt-2">
                            <button type="submit" id="loginButton" class="auth-btn">
                                <i class="fa fa-sign-in mr-2"></i>登录
                            </button>
                        </div>
                    </form>
                </div>
                
                <!-- 注册表单 -->
                <div id="register-form" class="p-6 hidden">
                    <form id="registerForm" class="space-y-5">
                        <div>
                            <label for="username" class="block text-sm font-medium text-gray-medium-light dark:text-gray-medium-dark mb-1">用户名</label>
                            <div class="relative">
                                <div class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none text-gray-medium-light dark:text-gray-medium-dark">
                                    <i class="fa fa-user"></i>
                                </div>
                                <input type="text" id="username" name="username" required 
                                    class="w-full pl-10 pr-4 py-3 border border-gray-200 dark:border-dark-border rounded-lg focus:outline-none transition-all duration-300 focus:form-input-focus bg-white dark:bg-dark-card text-gray-900 dark:text-gray-100">
                            </div>
                        </div>
                        
                        <div>
                            <label for="email" class="block text-sm font-medium text-gray-medium-light dark:text-gray-medium-dark mb-1">邮箱</label>
                            <div class="relative">
                                <div class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none text-gray-medium-light dark:text-gray-medium-dark">
                                    <i class="fa fa-envelope"></i>
                                </div>
                                <input type="email" id="email" name="email" required 
                                    class="w-full pl-10 pr-4 py-3 border border-gray-200 dark:border-dark-border rounded-lg focus:outline-none transition-all duration-300 focus:form-input-focus bg-white dark:bg-dark-card text-gray-900 dark:text-gray-100">
                            </div>
                        </div>
                        
                        <div>
                            <label for="password" class="block text-sm font-medium text-gray-medium-light dark:text-gray-medium-dark mb-1">密码</label>
                            <div class="relative">
                                <div class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none text-gray-medium-light dark:text-gray-medium-dark">
                                    <i class="fa fa-lock"></i>
                                </div>
                                <input type="password" id="password" name="password" required 
                                    class="w-full pl-10 pr-4 py-3 border border-gray-200 dark:border-dark-border rounded-lg focus:outline-none transition-all duration-300 focus:form-input-focus bg-white dark:bg-dark-card text-gray-900 dark:text-gray-100">
                            </div>
                        </div>
                        
                        <div>
                            <label for="confirm-password" class="block text-sm font-medium text-gray-medium-light dark:text-gray-medium-dark mb-1">确认密码</label>
                            <div class="relative">
                                <div class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none text-gray-medium-light dark:text-gray-medium-dark">
                                    <i class="fa fa-lock"></i>
                                </div>
                                <input type="password" id="confirm-password" name="confirm-password" required 
                                    class="w-full pl-10 pr-4 py-3 border border-gray-200 dark:border-dark-border rounded-lg focus:outline-none transition-all duration-300 focus:form-input-focus bg-white dark:bg-dark-card text-gray-900 dark:text-gray-100">
                            </div>
                        </div>
                        
                        <div>
                            <label for="turnstile" class="block text-sm font-medium text-gray-medium-light dark:text-gray-medium-dark mb-2">请确认您是人类:</label>
                            <div class="cf-turnstile" data-sitekey="0x4AAAAAABj3qHrHXwWdG7WG"></div>
                        </div>
                        
                        <div class="pt-2">
                            <button type="submit" class="auth-btn">
                                <i class="fa fa-user-plus mr-2"></i>注册
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </main>

    <!-- Toast 容器 -->
    <div class="toast-container"></div>

    <script>
    
    
    const url = window.location.href;

    const params = new URLSearchParams(new URL(url).search);
    
    const error = params.get('error');
    
    if (!error == ''){
        if (error == "token_expired"){
            showToast('登录过期，请重新登录!');
        }
        if (error == "token_invalid"){
            showToast('无效请求，请重新登录!');
        }
    }
    
    let isAnimating = false;
    

    function detectColorScheme() {
        if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
            document.documentElement.classList.add('dark');
        } else {
            document.documentElement.classList.remove('dark');
        }
    }

    // 监听系统颜色模式变化
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
        if (e.matches) {
            document.documentElement.classList.add('dark');
        } else {
            document.documentElement.classList.remove('dark');
        }
    });
    // 表单切换功能
    function switchToLogin() {
        if (isAnimating) return;
        isAnimating = true;

        // 更新标题和按钮状态
        document.getElementById('auth-title').innerText = '登录CCSID';
        document.getElementById('switch-to-login').classList.replace('toggle-btn-inactive', 'toggle-btn-active');
        document.getElementById('switch-to-register').classList.replace('toggle-btn-active', 'toggle-btn-inactive');

        const loginForm = document.getElementById('login-form');
        const registerForm = document.getElementById('register-form');

        // 切换表单显示状态
        toggleForm(registerForm, loginForm, 'fade-out', 'fade-in', () => {
            isAnimating = false;
        });
    }

    function switchToRegister() {
        if (isAnimating) return;
        isAnimating = true;

        // 更新标题和按钮状态
        document.getElementById('auth-title').innerText = '注册CCSID';
        document.getElementById('switch-to-login').classList.replace('toggle-btn-active', 'toggle-btn-inactive');
        document.getElementById('switch-to-register').classList.replace('toggle-btn-inactive', 'toggle-btn-active');

        const loginForm = document.getElementById('login-form');
        const registerForm = document.getElementById('register-form');

        // 切换表单显示状态
        toggleForm(loginForm, registerForm, 'fade-out', 'fade-in', () => {
            isAnimating = false;
        });
    }

    // 表单切换动画逻辑
    function toggleForm(hideForm, showForm, hideClass, showClass, callback) {
        if (!hideForm.classList.contains('hidden')) {
            hideForm.classList.add(hideClass);
            setTimeout(() => {
                hideForm.classList.add('hidden');
                hideForm.classList.remove(hideClass);
                showForm.classList.remove('hidden');
                showForm.classList.add(showClass);
                setTimeout(() => {
                    showForm.classList.remove(showClass);
                    if (callback) callback();
                }, 300);
            }, 300);
        } else {
            showForm.classList.remove('hidden');
            showForm.classList.add(showClass);
            setTimeout(() => {
                showForm.classList.remove(showClass);
                if (callback) callback();
            }, 300);
        }
    }

        // 显示 Toast 通知
        function showToast(message, duration = 3000) {
            const toastContainer = document.querySelector('.toast-container');
            const toast = document.createElement('div');
            toast.classList.add('toast');
            toast.innerHTML = `
                <span>${message}</span>
                <button class="text-gray-500 hover:text-gray-700" onclick="this.parentElement.classList.add('hide');">&times;</button>
            `;
            toastContainer.appendChild(toast);

            setTimeout(() => {
                toast.classList.add('hide');
                setTimeout(() => {
                    toastContainer.removeChild(toast);
                }, 500);
            }, duration);
        }

        // 登录表单提交
        document.getElementById('loginForm').addEventListener('submit', function(event) {
            event.preventDefault();

            const formData = new FormData(this);
            const username = formData.get('username');
            const password = formData.get('password');
            const cfTurnstileResponse = formData.get('cf-turnstile-response');

            fetch('login.php', {
                method: 'POST',
                body: new URLSearchParams({
                    username: username,
                    password: password,
                    'cf-turnstile-response': cfTurnstileResponse
                })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('登录失败，服务器返回状态码: ' + response.status);
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    // 登录成功，跳转到控制台页面
                    showToast('登录成功，正在跳转...', 3000);
                    setTimeout(() => {
                        window.location.href = '../console/index.php?login=success';
                    }, 3000);
                } else {
                    // 登录失败，显示错误信息
                    showToast(data.message, 3000);
                }
            })
            .catch(error => {
                console.error('登录时发生错误:', error);
                showToast('登录时发生错误，请稍后再试。', 3000);
            });
        });

        // 注册表单提交
        document.getElementById('registerForm').addEventListener('submit', function(event) {
            event.preventDefault();

            const formData = new FormData(this);
            const username = formData.get('username');
            const email = formData.get('email');
            const password = formData.get('password');
            const confirmPassword = formData.get('confirm-password');
            const cfTurnstileResponse = formData.get('cf-turnstile-response');

            if (password !== confirmPassword) {
                showToast('密码和确认密码不匹配。', 3000);
                return;
            }

            fetch('register.php', {
                method: 'POST',
                body: new URLSearchParams({
                    username: username,
                    email: email,
                    password: password,
                    'cf-turnstile-response': cfTurnstileResponse
                })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('注册失败，服务器返回状态码: ' + response.status);
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    // 注册成功，跳转到登录表单
                    showToast('注册成功，请登录。', 3000);
                    switchToLogin();
                } else {
                    // 注册失败，显示错误信息
                    showToast(data.message, 3000);
                }
            })
            .catch(error => {
                console.error('注册时发生错误:', error);
                showToast('注册时发生错误，请稍后再试。', 3000);
            });
        });

        // 初始化页面
        window.onload = function() {
            // 检测并设置初始颜色模式
            detectColorScheme();

            // 初始化登录表单
            switchToLogin();

            // 添加输入框焦点效果
            const inputs = document.querySelectorAll('input');
            inputs.forEach(input => {
                input.addEventListener('focus', () => {
                    input.parentElement.classList.add('scale-[1.01]');
                    input.parentElement.style.transition = 'all 0.3s ease';
                });

                input.addEventListener('blur', () => {
                    input.parentElement.classList.remove('scale-[1.01]');
                });
            });
        };
    </script>
</body>
</html>