<?php
ob_start();
require_once '../../config.php';
require_once '../../includes/functions.php';

$site_name = getSiteConfig('site_name') ?? '麟泓授权';
$site_logo = getSiteConfig('site_logo') ?? '/assets/uploads/logo.png';

// 检查是否有记住的登录状态
$saved_user = null;
$saved_token = $_COOKIE['pc_login_token'] ?? '';

if ($saved_token) {
    $saved_user = $db->fetchOne("
        SELECT u.* FROM pc_login_sessions s
        JOIN users u ON s.user_id = u.id
        WHERE s.session_token = '$saved_token' AND s.is_active = 1
    ");
}

// 如果是 POST 请求，处理退出登录
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'logout') {
        setcookie('pc_login_token', '', time() - 3600, '/');
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit;
    }
}
?>
<!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 htmlspecialchars($site_name); ?></title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #f5f5f5;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .login-card {
            background: white;
            border-radius: 8px;
            width: 360px;
            padding: 48px 32px;
            text-align: center;
            box-shadow: 0 2px 12px rgba(0,0,0,0.08);
        }
        .app-icon {
            width: 80px;
            height: 80px;
            margin: 0 auto 24px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .app-icon img {
            width: 44px;
            height: 44px;
            filter: brightness(0) invert(1);
        }
        .app-name {
            font-size: 22px;
            font-weight: 600;
            color: #1a1a1a;
            margin-bottom: 24px;
        }
        
        <?php if ($saved_user): ?>
        /* 有记住的账号 */
        .user-avatar {
            width: 72px;
            height: 72px;
            margin: 0 auto 12px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid #f0f0f0;
        }
        .username {
            font-size: 20px;
            font-weight: 600;
            color: #1a1a1a;
            margin-bottom: 24px;
        }
        .btn-enter {
            width: 100%;
            padding: 14px;
            background: #07C160;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 18px;
            font-weight: 600;
            cursor: pointer;
            margin-bottom: 16px;
        }
        .btn-enter:hover {
            background: #06ad56;
        }
        .btn-enter:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        .links {
            display: flex;
            justify-content: center;
            gap: 24px;
            margin-top: 16px;
        }
        .links a, .links button {
            color: #999;
            font-size: 14px;
            text-decoration: none;
            background: none;
            border: none;
            cursor: pointer;
        }
        .links button:hover {
            color: #07C160;
        }
        <?php else: ?>
        /* 无记住的账号，显示传统登录 */
        .form-group {
            margin-bottom: 20px;
            text-align: left;
        }
        .form-group input {
            width: 100%;
            padding: 14px 16px;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            font-size: 15px;
            outline: none;
        }
        .form-group input:focus {
            border-color: #07C160;
        }
        .btn-login {
            width: 100%;
            padding: 14px;
            background: #07C160;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
        }
        <?php endif; ?>
    </style>
</head>
<body>
    <div class="login-card">
        <div class="app-icon">
            <img src="<?php echo htmlspecialchars($site_logo); ?>" alt="" onerror="this.src='/assets/uploads/logo.png'">
        </div>
        <div class="app-name"><?php echo htmlspecialchars($site_name); ?></div>
        
        <?php if ($saved_user): ?>
            <!-- 记住账号状态 -->
            <img src="<?php echo htmlspecialchars($saved_user['avatar'] ?? '/assets/uploads/default_avatar.png'); ?>" 
                 class="user-avatar" 
                 onerror="this.src='/assets/uploads/default_avatar.png'">
            <div class="username"><?php echo htmlspecialchars($saved_user['username']); ?></div>
            
            <button class="btn-enter" id="enterBtn" onclick="startLogin()">进入</button>
            
            <div class="links">
                <form method="POST" style="display: inline;">
                    <input type="hidden" name="action" value="logout">
                    <button type="submit">切换账号</button>
                </form>
                <a href="#">仅传输文件</a>
            </div>
        <?php else: ?>
            <!-- 传统登录 -->
            <form id="loginForm">
                <div class="form-group">
                    <input type="text" name="username" placeholder="用户名/邮箱" required>
                </div>
                <div class="form-group">
                    <input type="password" name="password" placeholder="密码" required>
                </div>
                <button type="submit" class="btn-login">登录</button>
            </form>
        <?php endif; ?>
    </div>
    
    <?php if ($saved_user): ?>
    <script>
        const userId = '<?php echo $saved_user["id"]; ?>';
        const savedToken = '<?php echo $saved_token; ?>';
        
        async function startLogin() {
            const btn = document.getElementById('enterBtn');
            btn.disabled = true;
            btn.textContent = '正在请求...';
            
            try {
                // 生成登录确认请求
                const res = await fetch('/api/pc_login_generate.php', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                    body: `user_id=${userId}&device_name=${encodeURIComponent('Windows 电脑')}`
                });
                const data = await res.json();
                
                if (data.code === 0) {
                    // 跳转到等待确认页面
                    window.location.href = '/modules/home/login_confirm.php?token=' + data.token;
                } else {
                    alert('请求失败，请重试');
                    btn.disabled = false;
                    btn.textContent = '进入';
                }
            } catch (e) {
                alert('网络错误');
                btn.disabled = false;
                btn.textContent = '进入';
            }
        }
    </script>
    <?php else: ?>
    <script>
        document.getElementById('loginForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            
            const res = await fetch('/api/pc_login_traditional.php', {
                method: 'POST',
                body: formData
            });
            const data = await res.json();
            
            if (data.code === 0) {
                // 记住登录状态
                document.cookie = `pc_login_token=${data.session_token}; path=/; max-age=2592000`;
                window.location.href = '/admin.php';
            } else {
                alert(data.msg || '登录失败');
            }
        });
    </script>
    <?php endif; ?>
</body>
</html>