<?php
require __DIR__ . '/app/bootstrap.php';
require __DIR__ . '/app/database.php';

if (!app_is_installed()) {
    redirect('/install.php');
}

if (is_logged_in()) {
    redirect('/admin/dashboard/index.php');
}

$error = '';
$username = '';
$maxLoginAttempts = 5;
$lockMinutes = 15;
$captchaTtlSeconds = 300; // 验证码 5 分钟内有效

// 定期清理过期的限流文件（概率触发）
if (mt_rand(1, 20) === 1) {
    login_throttle_cleanup(3600);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_verify()) {
        $error = '页面已过期，请刷新后重试。';
    }
    $username = isset($_POST['username']) ? trim((string)$_POST['username']) : '';
    $password = isset($_POST['password']) ? (string)$_POST['password'] : '';
    $captcha = isset($_POST['captcha']) ? strtoupper(trim((string)$_POST['captcha'])) : '';
    $attemptInfo = login_throttle_get($username);
    $lockedUntil = (int)$attemptInfo['locked_until'];
    $currentTime = time();

    // 取出并立即清除 session 中的验证码（一次性消费，防重放）
    $captchaRecord = isset($_SESSION['admin_captcha']) && is_array($_SESSION['admin_captcha']) ? $_SESSION['admin_captcha'] : null;
    unset($_SESSION['admin_captcha']);
    $expectedCaptcha = $captchaRecord && isset($captchaRecord['code']) ? strtoupper((string)$captchaRecord['code']) : '';
    $captchaCreatedAt = $captchaRecord && isset($captchaRecord['created_at']) ? (int)$captchaRecord['created_at'] : 0;
    $captchaExpired = $captchaCreatedAt <= 0 || ($currentTime - $captchaCreatedAt) > $captchaTtlSeconds;

    if ($error !== '') {
        // CSRF 验证失败，跳过后续逻辑
    } elseif ($lockedUntil > $currentTime) {
        $remainingSeconds = $lockedUntil - $currentTime;
        $remainingMinutes = (int)ceil($remainingSeconds / 60);
        $error = '该管理员账号已被临时锁定，请在 ' . $remainingMinutes . ' 分钟后重试。';
    } else {
        if ($lockedUntil > 0) {
            $attemptInfo = array('count' => 0, 'locked_until' => 0);
        }

        if ($username === '' || $password === '' || $captcha === '') {
            $error = '请完整填写账号、密码和验证码。';
        } elseif ($expectedCaptcha === '' || $captchaExpired) {
            $error = '验证码已失效，请刷新后重新输入。';
        } elseif (!hash_equals($expectedCaptcha, $captcha)) {
            $error = '验证码错误，请重新输入。';
        } else {
            try {
                $admin = authenticate_admin($username, $password);

                if (!$admin) {
                    $newCount = (int)$attemptInfo['count'] + 1;

                    if ($newCount >= $maxLoginAttempts) {
                        login_throttle_set($username, $newCount, $currentTime + ($lockMinutes * 60));
                        $error = '账号或密码连续错误次数过多，该管理员账号已被临时锁定 ' . $lockMinutes . ' 分钟。';
                    } else {
                        login_throttle_set($username, $newCount, 0);
                        $remainingAttempts = $maxLoginAttempts - $newCount;
                        $error = '账号或密码错误，或当前管理员账号已被禁用。剩余尝试次数：' . $remainingAttempts;
                    }
                } else {
                    login_throttle_clear($username);
                    session_regenerate_id(true);
                    $_SESSION['admin_logged_in'] = true;
                    $_SESSION['admin_id'] = isset($admin['id']) ? (int)$admin['id'] : 0;
                    $_SESSION['admin_username'] = isset($admin['username']) ? (string)$admin['username'] : $username;
                    $_SESSION['admin_name'] = isset($admin['display_name']) ? (string)$admin['display_name'] : $username;
                    $_SESSION['admin_role'] = isset($admin['role']) ? (string)$admin['role'] : 'user';
                    if ($_SESSION['admin_role'] === 'user') {
                        $firstRow = db_connection()->query("SELECT id FROM admins ORDER BY id ASC LIMIT 1")->fetch(PDO::FETCH_ASSOC);
                        if ($firstRow && (int)$firstRow['id'] === (int)$admin['id']) {
                            db_connection()->prepare("UPDATE admins SET role = 'super_admin', updated_at = :now WHERE id = :id AND role = 'user'")
                                ->execute(array(':now' => date('Y-m-d H:i:s'), ':id' => (int)$admin['id']));
                            $_SESSION['admin_role'] = 'super_admin';
                        }
                    }
                    write_admin_operation_log(isset($admin['id']) ? (int)$admin['id'] : 0, isset($admin['username']) ? (string)$admin['username'] : $username, isset($admin['id']) ? (int)$admin['id'] : 0, isset($admin['username']) ? (string)$admin['username'] : $username, 'login_success', '管理员登录成功');
                    if (empty($admin['initialized_at'])) {
                        redirect('/user-init.php');
                    } else {
                        redirect('/admin/dashboard/index.php');
                    }
                }
            } catch (Exception $e) {
                $error = '系统认证异常，请稍后重试。';
            }
        }
    }
}
?><!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 e(APP_NAME); ?> - 后台登录</title>
    <link rel="stylesheet" href="assets/css/admin-ui.css">
</head>
<body>
    <div class="login-shell">
        <div class="login-grid">
            <section class="login-copy">
                <div class="brand-admin">
                    <img class="brand-mark" src="admin-bee.png" alt="<?php echo e(APP_NAME); ?>" style="width:60px;height:44px;border-radius:12px;object-fit:cover;">
                    <div class="brand-copy">
                        <strong><?php echo e(APP_NAME); ?></strong>
                        <span>BeeAI Admin Login</span>
                    </div>
                </div>
                <h1>AI 驱动的智能批量建站平台</h1>
                <p>一键配置 AI 模型，自动生成 SEO 友好的多域名站点。从模板设计到内容发布，全流程可视化管理，让建站效率提升 10 倍。</p>
                <ul>
                    <li>多模型接入，智能生成高质量原创内容</li>
                    <li>多域名批量建站，独立模板与 SEO 策略</li>
                    <li>定时任务调度，7×24 小时自动化运营</li>
                </ul>
                <div class="login-meta">版本 <?php echo e(APP_VERSION); ?> · 开发者 <?php echo e(APP_DEVELOPER); ?></div>
            </section>
            <section class="login-panel">
                <h1>管理员登录</h1>
                <p>请输入账号、密码与验证码进入后台控制台。</p>
                <?php if ($error !== ''): ?>
                    <div class="mini-item" style="margin-top: 16px; border-color: rgba(220, 38, 38, 0.18); background: rgba(220, 38, 38, 0.06);">
                        <strong style="color: #dc2626;">登录失败</strong>
                        <p style="margin: 0; color: #b91c1c;"><?php echo e($error); ?></p>
                    </div>
                <?php endif; ?>
                <form class="login-form" method="post" action="login.php">
                    <?php echo csrf_field(); ?>
                    <div class="input-group">
                        <span>管理员账号</span>
                        <input class="input" type="text" name="username" value="<?php echo e($username); ?>" placeholder="请输入管理员账号">
                    </div>
                    <div class="input-group">
                        <span>登录密码</span>
                        <input class="input" type="password" name="password" placeholder="请输入登录密码">
                    </div>
                    <div class="input-group">
                        <span>图形验证码</span>
                        <div class="captcha-row">
                            <input class="input captcha-input" type="text" name="captcha" placeholder="请输入验证码" maxlength="6" autocomplete="off" required>
                            <img id="captchaImage" class="captcha-image" src="captcha.php?_=<?php echo (int)(microtime(true) * 1000); ?>" alt="点击刷新验证码" title="点击刷新验证码">
                        </div>
                    </div>
                    <div class="filter-row">
                        <label><input type="checkbox" checked disabled> 记住登录状态</label>
                        <a href="index.html">返回前台</a>
                    </div>
                    <button class="btn-primary" type="submit">登录后台</button>
                </form>
                <div class="login-meta">验证码区分大小写时会自动按大写比对 · 图片点击可刷新</div>
                <script>
                (function () {
                    var img = document.getElementById('captchaImage');
                    if (!img) return;
                    img.addEventListener('click', function () {
                        img.src = 'captcha.php?_=' + Date.now();
                    });
                })();
                </script>
            </section>
        </div>
    </div>
</body>
</html>
