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

if (isLoggedIn()) {
    header('Location: index.php');
    exit;
}

$error = '';
$login_method = $_GET['method'] ?? 'password';

// 处理密码登录
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $login_method === 'password') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    
    $limit = checkLoginLimit($ip);
    if ($limit['locked']) {
        $error = $limit['message'];
    } elseif (empty($username) || empty($password)) {
        $error = '请输入用户名/邮箱和密码';
    } else {
        $stmt = $db->prepare("SELECT id, username, password, role, status FROM users WHERE username = ? OR email = ?");
        $stmt->bind_param("ss", $username, $username);
        $stmt->execute();
        $result = $stmt->get_result();
        $user = $result->fetch_assoc();

        if ($user && $user['status'] == 1 && password_verify($password, $user['password'])) {
            clearLoginFail($ip);
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['role'] = $user['role'];
            header('Location: index.php');
            exit;
        } else {
            $fail_result = recordLoginFail($ip, $username);
            $error = $fail_result['message'];
        }
        $stmt->close();
    }
}

$site_name = getSiteConfig('site_name') ?? '麟泓授权';
$site_logo = getSiteConfig('site_logo') ?? '/assets/uploads/logo.png';
$enabled_logins = $db->fetchAll("SELECT type, name FROM quick_login_config WHERE enabled = 1 ORDER BY sort ASC");

$login_styles = [
    'qq' => ['bg' => '#12B7F5', 'icon' => 'qq.svg', 'url' => '/api/qq_login.php'],
    'wx' => ['bg' => '#07C160', 'icon' => 'wechat.svg', 'url' => '/api/union_login.php?type=wx'],
    'alipay' => ['bg' => '#1677FF', 'icon' => 'alipay.svg', 'url' => '/api/union_login.php?type=alipay'],
    'gitee' => ['bg' => '#C71D23', 'icon' => 'gitee.svg', 'url' => '/api/gitee_login.php'],
    'github' => ['bg' => '#24292E', 'icon' => 'github.svg', 'url' => '/api/union_login.php?type=github'],
];
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title>登录 - <?php echo htmlspecialchars($site_name); ?></title>
    <link rel="stylesheet" href="/assets/css/style.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #ffffff;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        
        .login-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            padding: 24px 20px;
            max-width: 400px;
            margin: 0 auto;
            width: 100%;
        }
        
        .logo-section {
            text-align: center;
            margin-bottom: 40px;
            margin-top: 20px;
        }
        
        .logo-img {
            width: 64px;
            height: 64px;
            margin-bottom: 16px;
            border-radius: 16px;
            box-shadow: 0 8px 20px rgba(0,0,0,0.08);
        }
        
        .logo-section h1 {
            font-size: 28px;
            font-weight: 700;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            margin-bottom: 6px;
        }
        
        .logo-section p {
            color: #94a3b8;
            font-size: 14px;
            letter-spacing: 0.5px;
        }
        
        .login-tabs {
            display: flex;
            gap: 24px;
            margin-bottom: 32px;
            border-bottom: 2px solid #f0f0f0;
            padding-bottom: 12px;
        }
        
        .login-tab {
            font-size: 16px;
            font-weight: 600;
            color: #94a3b8;
            cursor: pointer;
            transition: all 0.2s;
            position: relative;
        }
        
        .login-tab.active {
            color: #667eea;
        }
        
        .login-tab.active::after {
            content: '';
            position: absolute;
            bottom: -14px;
            left: 0;
            right: 0;
            height: 3px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 3px;
        }
        
        .login-panel {
            display: none;
        }
        
        .login-panel.active {
            display: block;
        }
        
        .form-group {
            margin-bottom: 24px;
        }
        
        .form-label {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
            font-weight: 500;
            color: #1e293b;
            margin-bottom: 10px;
        }
        
        .input-wrapper {
    position: relative;
    display: flex;
    align-items: center;
}

.input-icon {
    position: absolute;
    left: 16px;
    top: 50%;
    transform: translateY(-50%);
    width: 20px;
    height: 20px;
    pointer-events: none;
    z-index: 1;
}

.form-input {
    width: 100%;
    padding: 16px 16px 16px 52px;
    border: 2px solid #f0f0f0;
    border-radius: 16px;
    font-size: 15px;
    outline: none;
    transition: all 0.2s;
    background: #fafbfc;
    line-height: 1.4;
}

/* 验证码输入框组 */
.code-input-group {
    display: flex;
    gap: 12px;
}

.code-input-group .input-wrapper {
    flex: 1;
}

.code-input-group .form-input {
    padding-right: 8px;
}

.code-btn {
    padding: 0 20px;
    white-space: nowrap;
    background: #f8fafc;
    border: 2px solid #f0f0f0;
    border-radius: 16px;
    color: #667eea;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s;
    flex-shrink: 0;
}
        
        .code-btn:hover {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }
        
        .code-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        .form-extra {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 28px;
        }
        
        .remember-me {
            display: flex;
            align-items: center;
            gap: 8px;
            color: #64748b;
            font-size: 14px;
        }
        
        .remember-me input {
            width: 18px;
            height: 18px;
            accent-color: #667eea;
        }
        
        .forgot-link {
            color: #667eea;
            font-size: 14px;
            font-weight: 500;
            text-decoration: none;
        }
        
        .btn-login {
            width: 100%;
            padding: 18px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 16px;
            font-size: 17px;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
        }
        
        .btn-login:hover {
            transform: translateY(-2px);
            box-shadow: 0 12px 28px rgba(102, 126, 234, 0.4);
        }
        
        .btn-login:disabled {
            opacity: 0.7;
            cursor: not-allowed;
            transform: none;
        }
        
        .error-msg {
            background: #fef2f2;
            color: #dc2626;
            padding: 14px 18px;
            border-radius: 14px;
            margin-bottom: 24px;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 10px;
            border: 1px solid #fecaca;
        }
        
        .toast-msg {
            position: fixed;
            top: 80px;
            left: 50%;
            transform: translateX(-50%);
            padding: 12px 28px;
            border-radius: 50px;
            font-size: 14px;
            font-weight: 500;
            z-index: 9999;
            animation: fadeInOut 2s ease;
            box-shadow: 0 8px 20px rgba(0,0,0,0.15);
        }
        
        .toast-success {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
        }
        
        .toast-error {
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
            color: white;
        }
        
        @keyframes fadeInOut {
            0%, 100% { opacity: 0; transform: translateX(-50%) translateY(-10px); }
            10%, 90% { opacity: 1; transform: translateX(-50%) translateY(0); }
        }
        
        .other-login {
            text-align: center;
            margin-top: 40px;
        }
        
        .other-title {
            display: flex;
            align-items: center;
            color: #94a3b8;
            font-size: 13px;
            margin-bottom: 24px;
        }
        
        .other-title::before,
        .other-title::after {
            content: '';
            flex: 1;
            height: 1px;
            background: linear-gradient(90deg, transparent, #e2e8f0, transparent);
        }
        
        .other-title span {
            padding: 0 20px;
        }
        
        .login-icons {
            display: flex;
            justify-content: center;
            gap: 24px;
        }
        
        .login-icon {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 56px;
            height: 56px;
            border-radius: 18px;
            transition: all 0.3s;
            text-decoration: none;
            box-shadow: 0 4px 12px rgba(0,0,0,0.08);
        }
        
        .login-icon:hover {
            transform: translateY(-4px);
            box-shadow: 0 8px 20px rgba(0,0,0,0.12);
        }
        
        .login-icon img {
            width: 28px;
            height: 28px;
        }
        
        .auth-footer {
            text-align: center;
            margin-top: 32px;
        }
        
        .auth-footer p {
            color: #64748b;
            font-size: 15px;
        }
        
        .auth-footer a {
            color: #667eea;
            text-decoration: none;
            font-weight: 600;
            margin-left: 4px;
        }
        
        .copyright {
            text-align: center;
            color: #cbd5e1;
            font-size: 12px;
            padding: 24px 0 10px;
        }
        
        .loading-spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 2px solid rgba(255,255,255,0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 0.6s linear infinite;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="logo-section">
            <h1><?php echo htmlspecialchars($site_name); ?></h1>
            <p>但行前路 · 不负韶华</p>
        </div>
        
        <div class="login-tabs">
            <div class="login-tab <?php echo $login_method == 'password' ? 'active' : ''; ?>" data-method="password">密码登录</div>
            <div class="login-tab <?php echo $login_method == 'code' ? 'active' : ''; ?>" data-method="code">验证码登录</div>
        </div>
        
        <div id="message"></div>
        
        <!-- 密码登录 -->
        <div id="passwordPanel" class="login-panel <?php echo $login_method == 'password' ? 'active' : ''; ?>">
            <form method="POST" action="?method=password">
                <div class="form-group">
                    <div class="form-label">
                        <img src="https://api.iconify.design/mdi:account-outline.svg?color=%23667eea" width="18" height="18" alt="">
                        账号
                    </div>
                    <div class="input-wrapper">
                        <input type="text" name="username" class="form-input" placeholder="请输入账号/邮箱" required>
                    </div>
                </div>
                <div class="form-group">
                    <div class="form-label">
                        <img src="https://api.iconify.design/mdi:lock-outline.svg?color=%23667eea" width="18" height="18" alt="">
                        密码
                    </div>
                    <div class="input-wrapper">
                        <input type="password" name="password" class="form-input" placeholder="请输入密码" required>
                    </div>
                </div>
                
                <?php if ($error && $login_method == 'password'): ?>
                <div class="error-msg">
                    <img src="https://api.iconify.design/mdi:alert-circle.svg?color=%23dc2626" width="20" height="20" alt="">
                    <?php echo htmlspecialchars($error); ?>
                </div>
                <?php endif; ?>
                
                <div class="form-extra">
                    <label class="remember-me">
                        <input type="checkbox" name="remember"> 记住我
                    </label>
                </div>
                
                <button type="submit" class="btn-login">登 录</button>
            </form>
        </div>
        
        <!-- 验证码登录 -->
        <div id="codePanel" class="login-panel <?php echo $login_method == 'code' ? 'active' : ''; ?>">
            <form id="codeLoginForm">
                <div class="form-group">
                    <div class="form-label">
                        <img src="https://api.iconify.design/mdi:email-outline.svg?color=%23667eea" width="18" height="18" alt="">
                        邮箱
                    </div>
                    <div class="code-input-group">
                        <div class="input-wrapper">
                            <input type="email" id="code_email" name="email" class="form-input" placeholder="请输入邮箱" required>
                        </div>
                        <button type="button" id="sendCodeBtn" class="code-btn">发送验证码</button>
                    </div>
                </div>
                <div class="form-group">
                    <div class="form-label">
                        <img src="https://api.iconify.design/mdi:shield-key-outline.svg?color=%23667eea" width="18" height="18" alt="">
                        验证码
                    </div>
                    <div class="input-wrapper">
                        <input type="text" id="code" name="code" class="form-input" placeholder="请输入6位验证码" required>
                    </div>
                </div>
                
                <button type="submit" class="btn-login" id="codeLoginBtn">登 录</button>
            </form>
        </div>
        
        <!-- 第三方登录 -->
        <?php if (!empty($enabled_logins)): ?>
        <div class="other-login">
            <div class="other-title">
                <span>第三方登录</span>
            </div>
            <div class="login-icons">
                <?php foreach ($enabled_logins as $login): 
                    $type = $login['type'];
                    $style = $login_styles[$type] ?? ['bg' => '#667eea', 'icon' => 'default.svg', 'url' => '#'];
                ?>
                    <a href="<?php echo $style['url']; ?>" class="login-icon" style="background: <?php echo $style['bg']; ?>;">
                        <img src="/assets/svg/<?php echo $style['icon']; ?>" alt="<?php echo $login['name']; ?>">
                    </a>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>
        
        <div class="auth-footer">
            <p>还没有账号？<a href="/m/register.php">立即注册</a></p>
        </div>
        
        <div class="copyright">
            Copyright © 2025 <?php echo htmlspecialchars($site_name); ?>. All Rights Reserved.
        </div>
    </div>
    
    <script>
        // 切换标签
        document.querySelectorAll('.login-tab').forEach(tab => {
            tab.addEventListener('click', function() {
                const method = this.dataset.method;
                window.history.pushState({}, '', '?method=' + method);
                document.querySelectorAll('.login-tab').forEach(t => t.classList.remove('active'));
                this.classList.add('active');
                document.getElementById('passwordPanel').classList.toggle('active', method === 'password');
                document.getElementById('codePanel').classList.toggle('active', method === 'code');
            });
        });
        
        // Toast 提示
        function showToast(msg, type) {
            const toast = document.createElement('div');
            toast.className = `toast-msg toast-${type}`;
            toast.innerHTML = msg;
            document.body.appendChild(toast);
            setTimeout(() => toast.remove(), 2000);
        }
        
        // 倒计时
        let countdown = 0;
        let timer = null;
        
        function startCountdown(seconds) {
            const btn = document.getElementById('sendCodeBtn');
            countdown = seconds;
            btn.disabled = true;
            btn.textContent = `重新发送(${countdown}s)`;
            
            timer = setInterval(() => {
                countdown--;
                if (countdown <= 0) {
                    clearInterval(timer);
                    btn.disabled = false;
                    btn.textContent = '发送验证码';
                } else {
                    btn.textContent = `重新发送(${countdown}s)`;
                }
            }, 1000);
        }
        
        // 发送验证码
        document.getElementById('sendCodeBtn')?.addEventListener('click', async function() {
            const email = document.getElementById('code_email').value;
            
            if (!email) {
                showToast('请输入邮箱', 'error');
                return;
            }
            
            if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
                showToast('邮箱格式不正确', 'error');
                return;
            }
            
            this.disabled = true;
            this.textContent = '发送中...';
            
            try {
                const response = await fetch('/api/send_code.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: `email=${encodeURIComponent(email)}&type=login`
                });
                const data = await response.json();
                
                if (data.success) {
                    showToast(data.message, 'success');
                    startCountdown(60);
                } else {
                    showToast(data.message, 'error');
                    this.disabled = false;
                    this.textContent = '发送验证码';
                }
            } catch (error) {
                showToast('网络错误，请重试', 'error');
                this.disabled = false;
                this.textContent = '发送验证码';
            }
        });
        
        // 验证码登录
        document.getElementById('codeLoginForm')?.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const email = document.getElementById('code_email').value;
            const code = document.getElementById('code').value;
            
            if (!email || !code) {
                showToast('请输入邮箱和验证码', 'error');
                return;
            }
            
            const btn = document.getElementById('codeLoginBtn');
            btn.disabled = true;
            btn.innerHTML = '<span class="loading-spinner"></span> 登录中...';
            
            try {
                const response = await fetch('/api/verify_code.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: `type=login&login_email=${encodeURIComponent(email)}&login_code=${encodeURIComponent(code)}`
                });
                const data = await response.json();
                
                if (data.success) {
                    showToast(data.message, 'success');
                    setTimeout(() => window.location.href = 'index.php', 1000);
                } else {
                    showToast(data.message, 'error');
                    btn.disabled = false;
                    btn.innerHTML = '登 录';
                }
            } catch (error) {
                showToast('网络错误，请重试', 'error');
                btn.disabled = false;
                btn.innerHTML = '登 录';
            }
        });
    </script>
</body>
</html>