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

// 如果已经登录，跳转到管理首页
if (isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true) {
    header('Location: index.php');
    exit;
}

// 登录尝试限制
$login_attempts = $_SESSION['login_attempts'] ?? 0;
$last_attempt_time = $_SESSION['last_attempt_time'] ?? 0;
$lockout_time = 900; // 15分钟锁定

// 检查是否在锁定状态
if ($login_attempts >= 5 && (time() - $last_attempt_time) < $lockout_time) {
    $remaining_time = $lockout_time - (time() - $last_attempt_time);
    $lockout_message = "登录尝试次数过多，请 " . ceil($remaining_time / 60) . " 分钟后再试。";
} else {
    $lockout_message = '';
}

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && empty($lockout_message)) {
    $username = safe_input($_POST['username'] ?? '');
    $password = safe_input($_POST['password'] ?? '');
    $captcha = safe_input($_POST['captcha'] ?? '');

    // 验证验证码
    if (!isset($_SESSION['login_captcha']) || $captcha !== $_SESSION['login_captcha']) {
        $error = '验证码错误！';
        $_SESSION['login_attempts'] = $login_attempts + 1;
        $_SESSION['last_attempt_time'] = time();
    } else {
        // 验证用户名和密码
        if ($username === $config['admin']['username'] && md5($password) === $config['admin']['password']) {
            // 登录成功，重置尝试次数
            $_SESSION['admin_logged_in'] = true;
            $_SESSION['admin_username'] = $username;
            $_SESSION['admin_ip'] = $_SERVER['REMOTE_ADDR'];
            $_SESSION['admin_last_activity'] = time();
            $_SESSION['login_attempts'] = 0;
            $_SESSION['last_attempt_time'] = 0;
            
            // 清除验证码
            unset($_SESSION['login_captcha']);
            
            header('Location: index.php');
            exit;
        } else {
            $error = '用户名或密码错误！';
            $_SESSION['login_attempts'] = $login_attempts + 1;
            $_SESSION['last_attempt_time'] = time();
        }
    }
}

// 生成验证码
if (!isset($_SESSION['login_captcha']) || empty($_SESSION['login_captcha'])) {
    $captcha_code = generate_captcha_code();
    $_SESSION['login_captcha'] = $captcha_code;
} else {
    $captcha_code = $_SESSION['login_captcha'];
}

// 生成验证码函数
function generate_captcha_code($length = 4) {
    $chars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
    $code = '';
    for ($i = 0; $i < $length; $i++) {
        $code .= $chars[rand(0, strlen($chars) - 1)];
    }
    return $code;
}
?>
<!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($config['site']['name']); ?></title>
    <style>
        * { 
            box-sizing: border-box; 
            margin: 0;
            padding: 0;
        }
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .login-container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            padding: 2.5rem;
            width: 100%;
            max-width: 420px;
            position: relative;
            overflow: hidden;
        }
        .login-container::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, #667eea, #764ba2);
        }
        .login-header {
            text-align: center;
            margin-bottom: 2rem;
        }
        .login-header h3 {
            color: #333;
            margin-bottom: 0.5rem;
            font-weight: 600;
        }
        .login-header p {
            color: #666;
            font-size: 0.9rem;
        }
        .form-label { 
            display: block; 
            margin-bottom: 0.5rem; 
            font-weight: 500; 
            color: #333;
        }
        .form-control {
            display: block;
            width: 100%;
            padding: 0.75rem 1rem;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            margin-bottom: 1rem;
            font-size: 0.95rem;
            transition: all 0.3s ease;
        }
        .form-control:focus {
            border-color: #667eea;
            outline: 0;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        .form-group {
            margin-bottom: 1.5rem;
        }
        .captcha-group {
            display: flex;
            gap: 10px;
            align-items: flex-end;
        }
        .captcha-input {
            flex: 1;
        }
        .captcha-display {
            background: #f8f9fa;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            padding: 0.5rem 1rem;
            font-family: 'Courier New', monospace;
            font-size: 1.2rem;
            font-weight: bold;
            letter-spacing: 2px;
            color: #333;
            text-align: center;
            min-width: 120px;
            cursor: pointer;
            user-select: none;
        }
        .btn {
            display: block;
            width: 100%;
            padding: 0.75rem;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            border-radius: 8px;
            color: white;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
        }
        .btn:active {
            transform: translateY(0);
        }
        .btn:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        .alert {
            padding: 0.75rem 1rem;
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            border-radius: 8px;
            color: #721c24;
            margin-bottom: 1rem;
            font-size: 0.9rem;
        }
        .lockout-alert {
            background: #fff3cd;
            border-color: #ffeaa7;
            color: #856404;
        }
        .text-center { text-align: center; }
        .mb-4 { margin-bottom: 1.5rem; }
        .refresh-captcha {
            background: none;
            border: none;
            color: #667eea;
            cursor: pointer;
            font-size: 0.9rem;
            margin-top: 0.5rem;
        }
        .refresh-captcha:hover {
            text-decoration: underline;
        }
        .security-info {
            background: #e7f3ff;
            border: 1px solid #b3d9ff;
            border-radius: 8px;
            padding: 1rem;
            margin-top: 1.5rem;
            font-size: 0.8rem;
            color: #0066cc;
        }
        .security-info h4 {
            margin-bottom: 0.5rem;
            font-size: 0.9rem;
        }
        @media (max-width: 480px) {
            .login-container {
                padding: 2rem 1.5rem;
            }
            .captcha-group {
                flex-direction: column;
            }
            .captcha-display {
                min-width: auto;
            }
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="login-header">
            <h3>管理后台登录</h3>
            <p><?php echo htmlspecialchars($config['site']['name']); ?></p>
        </div>
        
        <?php if ($lockout_message): ?>
            <div class="alert lockout-alert">
                <?php echo htmlspecialchars($lockout_message); ?>
            </div>
        <?php endif; ?>
        
        <?php if ($error && empty($lockout_message)): ?>
            <div class="alert"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>
        
        <?php if (empty($lockout_message)): ?>
        <form method="POST" id="loginForm">
            <div class="form-group">
                <label for="username" class="form-label">用户名</label>
                <input type="text" class="form-control" id="username" name="username" required 
                       value="<?php echo htmlspecialchars($_POST['username'] ?? ''); ?>">
            </div>
            
            <div class="form-group">
                <label for="password" class="form-label">密码</label>
                <input type="password" class="form-control" id="password" name="password" required>
            </div>
            
            <div class="form-group">
                <label class="form-label">验证码</label>
                <div class="captcha-group">
                    <input type="text" class="form-control captcha-input" name="captcha" 
                           placeholder="输入验证码" required maxlength="4">
                    <div class="captcha-display" id="captchaDisplay" onclick="refreshCaptcha()">
                        <?php echo htmlspecialchars($captcha_code); ?>
                    </div>
                </div>
                <button type="button" class="refresh-captcha" onclick="refreshCaptcha()">
                    刷新验证码
                </button>
            </div>
            
            <button type="submit" class="btn" id="loginBtn">登录</button>
        </form>
        
        <div class="security-info">
            <h4>🔒 安全提示</h4>
            <p>• 请确保在安全的网络环境下登录</p>
            <p>• 登录成功后请及时修改默认密码</p>
            <p>• 连续登录失败5次将锁定15分钟</p>
        </div>
        <?php else: ?>
        <div class="text-center">
            <p class="text-muted">账户已被暂时锁定，请稍后再试。</p>
            <button type="button" class="btn" onclick="location.reload()" style="margin-top: 1rem;">
                重新加载页面
            </button>
        </div>
        <?php endif; ?>
    </div>

    <script>
        function refreshCaptcha() {
            fetch('?refresh_captcha=1')
                .then(response => response.text())
                .then(html => {
                    // 创建一个临时元素来解析返回的HTML
                    const temp = document.createElement('div');
                    temp.innerHTML = html;
                    const newCaptcha = temp.querySelector('#captchaDisplay');
                    if (newCaptcha) {
                        document.getElementById('captchaDisplay').textContent = newCaptcha.textContent;
                    }
                })
                .catch(error => {
                    console.error('刷新验证码失败:', error);
                    // 如果AJAX失败，刷新整个页面
                    location.reload();
                });
        }

        // 表单提交保护
        document.getElementById('loginForm')?.addEventListener('submit', function(e) {
            const btn = document.getElementById('loginBtn');
            btn.disabled = true;
            btn.innerHTML = '登录中...';
            
            // 防止重复提交
            setTimeout(() => {
                btn.disabled = false;
                btn.innerHTML = '登录';
            }, 3000);
        });

        // 输入框回车提交
        document.addEventListener('DOMContentLoaded', function() {
            const inputs = document.querySelectorAll('input');
            inputs.forEach(input => {
                input.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        e.preventDefault();
                        document.getElementById('loginForm')?.submit();
                    }
                });
            });
        });

        // 自动聚焦用户名输入框
        document.getElementById('username')?.focus();
    </script>

    <?php
    // 处理验证码刷新请求
    if (isset($_GET['refresh_captcha'])) {
        $new_captcha = generate_captcha_code();
        $_SESSION['login_captcha'] = $new_captcha;
        echo '<div id="captchaDisplay">' . htmlspecialchars($new_captcha) . '</div>';
        exit;
    }
    ?>
</body>
</html>