<?php
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: ' . SITE_URL . 'admin.php');
    exit;
}

$error = '';
$login_method = $_GET['method'] ?? 'code'; // code=验证码登录, 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, email, email_notify, need_change_password 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);
            
            // ========== 检查是否需要修改密码（第三方用户首次登录） ==========
            if ($user['need_change_password'] == 1) {
                $_SESSION['need_change_password'] = true;
                $_SESSION['temp_user_id'] = $user['id'];
                $_SESSION['temp_username'] = $user['username'];
                header('Location: ' . SITE_URL . 'modules/user/force_change_password.php');
                exit;
            }
            // ========== 检查结束 ==========
            
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['role'] = $user['role'];
            
            // ========== 登录保护提醒 ==========
            $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
            $login_time = date('Y-m-d H:i:s');
            
            // 获取IP位置
            function getIpLocation($ip) {
                if ($ip == '127.0.0.1' || $ip == 'localhost') return '本地';
                $url = "https://v2.xxapi.cn/api/ip?ip=" . urlencode($ip);
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_TIMEOUT, 3);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                $response = curl_exec($ch);
                curl_close($ch);
                $data = json_decode($response, true);
                if ($data && $data['code'] == 200 && !empty($data['data']['address'])) {
                    return $data['data']['address'];
                }
                return '未知位置';
            }
            
            // 获取设备类型（使用增强函数）
            $device_info = getDetailedDeviceInfo($user_agent);
            $device = $device_info['full'];
            $city = getIpLocation($ip);
            
            // 每次登录都发送提醒（只要用户开启了邮件通知）
            if (!empty($user['email']) && ($user['email_notify'] ?? 1)) {
                sendLoginAlert($user, $ip, $city, $device, $login_time);
            }
            
            // 记录登录日志
            $db->query("INSERT INTO user_login_log (user_id, ip, city, device, user_agent) 
                        VALUES ({$user['id']}, '$ip', '$city', '$device', '" . addslashes($user_agent) . "')");
            // ========== 登录保护提醒结束 ==========
            
            header('Location: ' . SITE_URL . 'admin.php');
            exit;
        } else {
            // 登录失败，记录失败次数
            $fail_result = recordLoginFail($ip, $username);
            $error = $fail_result['message'];
        }
        $stmt->close();
    }
}

$site_name = getSiteConfig('site_name') ?? '万能授权系统';
$sys_version = getSiteConfig('sys_version') ?? '1.0.0';

// 获取启用的快捷登录方式
$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'],
    'sina' => ['bg' => '#FF8200', 'icon' => 'weibo.svg', 'url' => '/api/union_login.php?type=sina'],
    'baidu' => ['bg' => '#2932E1', 'icon' => 'baidu.svg', 'url' => '/api/union_login.php?type=baidu'],
    'xiaomi' => ['bg' => '#FF6900', 'icon' => 'xiaomi.svg', 'url' => '/api/union_login.php?type=xiaomi'],
    'huawei' => ['bg' => '#FF0000', 'icon' => 'huawei.svg', 'url' => '/api/union_login.php?type=huawei'],
    'douyin' => ['bg' => '#000000', 'icon' => 'douyin.svg', 'url' => '/api/union_login.php?type=douyin'],
    'google' => ['bg' => '#4285F4', 'icon' => 'google.svg', 'url' => '/api/union_login.php?type=google'],
    'microsoft' => ['bg' => '#00A4EF', 'icon' => 'microsoft.svg', 'url' => '/api/union_login.php?type=microsoft'],
    'facebook' => ['bg' => '#1877F2', 'icon' => 'facebook.svg', 'url' => '/api/union_login.php?type=facebook'],
    'twitter' => ['bg' => '#1DA1F2', 'icon' => 'twitter.svg', 'url' => '/api/union_login.php?type=twitter'],
    'feishu' => ['bg' => '#00C4A0', 'icon' => 'feishu.svg', 'url' => '/api/feishu_login.php'],
    'wework' => ['bg' => '#2C7A3E', 'icon' => 'wework.svg', 'url' => '/api/union_login.php?type=wework'],
    'dingtalk' => ['bg' => '#1E9AEF', 'icon' => 'dingtalk.svg', 'url' => '/api/union_login.php?type=dingtalk'],
    '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">
    <title>登录 - <?php echo htmlspecialchars($site_name); ?></title>
    <link rel="stylesheet" href="/assets/css/style.css">
    <link rel="stylesheet" href="/assets/css/dark.css" id="dark-theme" disabled>
    <script src="/assets/js/main.js" defer></script>
    <link rel="stylesheet" href="/assets/css/app.css">
    <script src="/assets/js/iconify.min.js"></script>
    <link rel="icon" href="/assets/uploads/favicon.ico"> 

    <style>
    body{
        width:100%;
        height:100%;
        background: url(https://api.suyanw.cn/api/mao.php) no-repeat;
        background-size: cover;
    }
    .auth-card {
        max-width: 450px;
        margin: 50px auto;
        background: var(--bg-primary);
        border-radius: 20px;
        padding: 30px;
        box-shadow: 0 20px 40px rgba(0,0,0,0.1);
    }
    .login-tabs {
        display: flex;
        margin-bottom: 30px;
        border-bottom: 1px solid var(--border-color);
    }
    .login-tab {
        flex: 1;
        text-align: center;
        padding: 12px;
        cursor: pointer;
        color: var(--text-secondary);
        font-weight: 500;
        transition: all 0.2s;
        border-bottom: 2px solid transparent;
    }
    .login-tab.active {
        color: var(--primary-color);
        border-bottom-color: var(--primary-color);
    }
    .login-panel {
        display: none;
    }
    .login-panel.active {
        display: block;
    }
    .form-group {
        margin-bottom: 20px;
    }
    .form-group label {
        display: block;
        margin-bottom: 8px;
        font-weight: 500;
    }
    .form-group input {
        width: 100%;
        padding: 12px 16px;
        border: 1px solid var(--border-color);
        border-radius: 12px;
        background: var(--bg-primary);
        color: var(--text-primary);
        font-size: 14px;
        box-sizing: border-box;
    }
    .form-group input:focus {
        outline: none;
        border-color: #667eea;
    }
    .code-input-group {
        display: flex;
        gap: 10px;
    }
    .code-input-group input {
        flex: 1;
    }
    .code-input-group button {
        padding: 0 20px;
        white-space: nowrap;
        border-radius: 12px;
        border: 1px solid var(--border-color);
        background: var(--bg-secondary);
        color: var(--text-primary);
        cursor: pointer;
        font-size: 14px;
    }
    .code-input-group button:disabled {
        opacity: 0.6;
        cursor: not-allowed;
    }
    .btn-primary {
        width: 100%;
        padding: 12px;
        background: linear-gradient(135deg, #667eea, #764ba2);
        color: white;
        border: none;
        border-radius: 12px;
        font-size: 16px;
        font-weight: 600;
        cursor: pointer;
    }
    .btn-primary:disabled {
        opacity: 0.6;
        cursor: not-allowed;
    }
    .auth-footer {
        text-align: center;
        margin-top: 20px;
    }
    .alert {
        padding: 12px 16px;
        border-radius: 12px;
        margin-bottom: 20px;
        display: none;
    }
    .alert-error {
        background: rgba(239,68,68,0.1);
        border: 1px solid #ef4444;
        color: #ef4444;
    }
    .alert-success {
        background: rgba(16,185,129,0.1);
        border: 1px solid #10b981;
        color: #10b981;
    }
    /* 圆形图标样式 */
    .login-icons {
        display: flex;
        justify-content: center;
        gap: 20px;
        flex-wrap: wrap;
        margin-top: 20px;
    }
    .login-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 48px;
        height: 48px;
        border-radius: 50%;
        transition: transform 0.2s, box-shadow 0.2s;
        text-decoration: none;
    }
    .login-icon:hover {
        transform: scale(1.1);
    }
    .login-icon img {
        width: 26px;
        height: 26px;
    }
    </style>
</head>
<body>
<div class="auth-card">
    <div class="auth-header" style="text-align: center; margin-bottom: 20px;">
        <img src="/assets/uploads/logo_1774667898.png" alt="Logo" style="display: block; margin: 0 auto 15px auto; height: 60px;">
        <h1>登录账号</h1>
        <p>欢迎回来</p>
    </div>
    
    <!-- 切换标签 -->
    <div class="login-tabs">
        <div class="login-tab <?php echo $login_method == 'code' ? 'active' : ''; ?>" data-method="code">验证码登录</div>
        <div class="login-tab <?php echo $login_method == 'password' ? 'active' : ''; ?>" data-method="password">密码登录</div>
    </div>
    
    <div id="message" class="alert"></div>
    
    <!-- 验证码登录面板 -->
    <div id="codePanel" class="login-panel <?php echo $login_method == 'code' ? 'active' : ''; ?>">
        <form id="codeLoginForm">
            <div class="form-group">
                <label>邮箱</label>
                <div class="code-input-group">
                    <input type="email" id="code_email" name="email" required autofocus>
                    <button type="button" id="sendCodeBtn">发送验证码</button>
                </div>
            </div>
            <div class="form-group">
                <label>验证码</label>
                <input type="text" id="code" name="code" placeholder="请输入6位验证码" required>
            </div>
            <button type="submit" class="btn-primary" id="codeLoginBtn">登 录</button>
        </form>
    </div>
    
    <!-- 密码登录面板 -->
    <div id="passwordPanel" class="login-panel <?php echo $login_method == 'password' ? 'active' : ''; ?>">
        <form method="POST" action="?method=password">
            <div class="form-group">
                <label>用户名 / 邮箱</label>
                <input type="text" name="username" required autofocus>
            </div>
            <div class="form-group">
                <label>密码</label>
                <input type="password" name="password" required>
            </div>
            <?php if ($error): ?>
                <div class="alert alert-error" style="display: block;"><?php echo htmlspecialchars($error); ?></div>
            <?php endif; ?>
            <button type="submit" class="btn-primary">登 录</button>
        </form>
    </div>
    
    <!-- 第三方登录 - 圆形图标 -->
    <?php if (!empty($enabled_logins)): ?>
    <div style="text-align: center; margin: 25px 0 15px;">
        <div style="position: relative; text-align: center;">
            <div style="border-top: 1px solid var(--border-color);"></div>
            <span style="position: relative; top: -12px; background: var(--bg-primary); padding: 0 10px; color: var(--text-muted); font-size: 12px;">或使用第三方登录</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']; ?>; box-shadow: 0 2px 8px <?php echo $style['bg']; ?>40;"
                   onmouseover="this.style.boxShadow='0 4px 12px <?php echo $style['bg']; ?>80';"
                   onmouseout="this.style.boxShadow='0 2px 8px <?php echo $style['bg']; ?>40';">
                    <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="/modules/home/register.php">立即注册</a></p>
        <a href="/modules/home/forgot_password.php" style="font-size: 13px; color: var(--text-muted); text-decoration: none;">忘记密码？</a>
    </div>
</div>

<script>
let countdown = 0;
let timer = null;

// 切换登录方式
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('codePanel').classList.remove('active');
        document.getElementById('passwordPanel').classList.remove('active');
        if (method === 'code') {
            document.getElementById('codePanel').classList.add('active');
        } else {
            document.getElementById('passwordPanel').classList.add('active');
        }
    });
});

function showMessage(msg, type) {
    const msgDiv = document.getElementById('message');
    msgDiv.innerHTML = msg;
    msgDiv.className = 'alert alert-' + type;
    msgDiv.style.display = 'block';
    setTimeout(() => {
        msgDiv.style.display = 'none';
    }, 3000);
}

function startCountdown(seconds) {
    const btn = document.getElementById('sendCodeBtn');
    countdown = seconds;
    btn.disabled = true;
    btn.innerHTML = `重新发送(${countdown}s)`;
    
    timer = setInterval(() => {
        countdown--;
        if (countdown <= 0) {
            clearInterval(timer);
            btn.disabled = false;
            btn.innerHTML = '发送验证码';
        } else {
            btn.innerHTML = `重新发送(${countdown}s)`;
        }
    }, 1000);
}

// 发送验证码
document.getElementById('sendCodeBtn')?.addEventListener('click', async function() {
    const email = document.getElementById('code_email').value;
    
    if (!email) {
        showMessage('请输入邮箱', 'error');
        return;
    }
    
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
        showMessage('邮箱格式不正确', 'error');
        return;
    }
    
    this.disabled = true;
    this.innerHTML = '发送中...';
    
    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) {
            showMessage(data.message, 'success');
            startCountdown(60);
        } else {
            showMessage(data.message, 'error');
            this.disabled = false;
            this.innerHTML = '发送验证码';
        }
    } catch (error) {
        showMessage('网络错误，请重试', 'error');
        this.disabled = false;
        this.innerHTML = '发送验证码';
    }
});

// 验证码登录提交
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) {
        showMessage('请输入邮箱和验证码', 'error');
        return;
    }
    
    const loginBtn = document.getElementById('codeLoginBtn');
    loginBtn.disabled = true;
    loginBtn.innerHTML = '登录中...';
    
    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) {
            showMessage(data.message, 'success');
            setTimeout(() => {
                window.location.href = '/admin.php';
            }, 1000);
        } else {
            showMessage(data.message, 'error');
            loginBtn.disabled = false;
            loginBtn.innerHTML = '登 录';
        }
    } catch (error) {
        showMessage('网络错误，请重试', 'error');
        loginBtn.disabled = false;
        loginBtn.innerHTML = '登 录';
    }
});
</script>
</body>
</html>