<?php

require_once __DIR__ . '/common.php';

$pdo = db();

$siteTitle = get_setting('site.title', '六柱博客');

$errors = [];
$loginName = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!rate_limit_cooldown('admin_login', 2)) {
        $errors[] = '操作太频繁，请稍后重试。';
    }

    if (!admin_csrf_check($_POST['csrf_token'] ?? null)) {
        $errors[] = '请求已失效，请刷新页面后重试。';
    }

    $loginName = trim((string)($_POST['email'] ?? ''));
    $password  = (string)($_POST['password'] ?? '');
    $captcha   = (string)($_POST['captcha'] ?? '');

    if (!verify_captcha('admin_login', $captcha)) {
        $errors[] = '验证码错误，请重新输入。';
    }

    if ($loginName === '' || $password === '') {
        $errors[] = '请填写账号和密码。';
    }

    if (!$errors) {
        try {
            $stmt = $pdo->prepare("
                SELECT id, email, password_hash, nickname, role, status, email_verified
                FROM users
                WHERE email = :email
                LIMIT 1
            ");
            $stmt->execute([':email' => $loginName]);
            $user = $stmt->fetch();

            $now = time();
            $ip = $_SERVER['REMOTE_ADDR'] ?? '';
            $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';

            $loginOk = false;
            $userId = null;

            if (!$user) {
                $errors[] = '账号或密码错误。';
            } elseif (!password_verify($password, $user['password_hash'])) {
                $errors[] = '账号或密码错误。';
                $userId = (int)$user['id'];
            } elseif ($user['role'] !== 'admin') {
                $errors[] = '该账号不是管理员，无法登录后台。';
                $userId = (int)$user['id'];
            } elseif ($user['status'] !== 'active') {
                $errors[] = '账号状态异常，无法登录后台。';
                $userId = (int)$user['id'];
            } elseif ((int)$user['email_verified'] !== 1) {
                $errors[] = '该账号尚未完成邮箱验证，请先验证邮箱。';
                $userId = (int)$user['id'];
            } else {
                $userId = (int)$user['id'];
                
                $loginOk = true;
            }

            
            try {
                $stmtLog = $pdo->prepare("
                    INSERT INTO login_log (user_id, email, ip, user_agent, success, created_at)
                    VALUES (:user_id, :email, :ip, :user_agent, :success, :created_at)
                ");
                $stmtLog->execute([
                    ':user_id'    => $userId,
                    ':email'      => $loginName,
                    ':ip'         => $ip,
                    ':user_agent' => $ua,
                    ':success'    => $loginOk ? 1 : 0,
                    ':created_at' => $now,
                ]);
            } catch (Throwable $e) {
                
            }

            if ($loginOk) {
                
                admin_log('login_success', '后台登录成功: ' . $loginName, $userId);
                $_SESSION['user_id'] = $userId;
                session_harden_after_login();
                header('Location: index.php');
                exit;
            } else {
                
                admin_log('login_failed', '后台登录失败: ' . $loginName, $userId);
            }
        } catch (Throwable $e) {
            $errors[] = '登录失败，请稍后重试。';
        }
    }
}

$captchaQuestion = generate_captcha('admin_login');

?><!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>后台登录 - <?php echo h($siteTitle); ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        html, body { height:100%;  margin:0; padding:0; }
        body {
            margin: 0; padding:0;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;
            background: #0f172a;
            color: #e5e7eb;
        }

        a {
            color: #60a5fa;
            text-decoration: none;
        }

        a:hover {
            text-decoration: underline;
        }

        .page {
            max-width: 420px;
            margin: 60px auto;
            padding: 0 16px;
        }

        .card {
            background: #111827;
            border-radius: 6px;
            border: 1px solid #1f2937;
            padding: 18px 20px;
            box-shadow: 0 10px 25px rgba(15, 23, 42, 0.5);
        }

        .card-title {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 12px;
        }

        .form-group {
            margin-bottom: 10px;
        }

        .form-group label {
            display: block;
            font-size: 13px;
            margin-bottom: 4px;
        }

        .form-group input {
            width: 100%;
            padding: 6px 8px;
            border-radius: 4px;
            border: 1px solid #374151;
            background: #020617;
            color: #e5e7eb;
            font-size: 14px;
        }

        .btn {
            border-radius: 999px;
            border: 1px solid #3b82f6;
            background: #1d4ed8;
            color: #e5e7eb;
            font-size: 14px;
            padding: 6px 12px;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 4px;
            width: 100%;
            margin-top: 6px;
        }

        .errors {
            background: #7f1d1d;
            border: 1px solid #fecaca;
            color: #fee2e2;
            padding: 8px 10px;
            border-radius: 4px;
            font-size: 13px;
            margin-bottom: 10px;
        }

        .small-text {
            font-size: 12px;
            color: #9ca3af;
            margin-top: 6px;
        }
    </style>
</head>
<body style="margin:0;padding:0;"><div class="page">
    <div class="card">
        <div class="card-title">后台登录</div>

        <?php if ($errors): ?>
            <div class="errors">
                <?php foreach ($errors as $err): ?>
                    <div><?php echo h($err); ?></div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <form method="post" action="login.php" id="loginForm">
            <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
            <input type="hidden" name="client_auth_checked" id="client_auth_checked" value="0">
            <div class="form-group">
                <label for="email">管理员账号</label>
                <input type="text" id="email" name="email" required value="<?php echo h($loginName); ?>">
            </div>

            <div class="form-group">
                <label for="password">密码</label>
                <input type="password" id="password" name="password" required>
            </div>

            <div class="form-group">
                <label for="captcha">验证码（<?php echo h($captchaQuestion); ?>）</label>
                <input type="text" id="captcha" name="captcha" required>
            </div>

            <button type="submit" class="btn">登 录</button>
        </form>
        <div class="errors" id="authErrorBox" style="display:none;margin-top:10px;"></div>

        <div class="small-text">
            提示：只有 role 为 admin 且已通过邮箱验证的账号才能登录后台。<br>
            请使用你的管理员账号登录。
        </div>
    </div>
</div>
<script src="../assets/js/auth-verify.js?v=20260305b"></script>
<script>
    (function () {
        var form = document.getElementById('loginForm');
        if (!form) return;
        var btn = form.querySelector('button[type="submit"]');
        var checkedInput = document.getElementById('client_auth_checked');
        var authErrorBox = document.getElementById('authErrorBox');
        var allowSubmit = false;

        function setBtnLoading(text, disabled) {
            if (!btn) return;
            btn.disabled = !!disabled;
            btn.textContent = text;
        }

        function showAuthError(text) {
            if (!authErrorBox) return;
            authErrorBox.textContent = text || '登录失败，请稍后重试。';
            authErrorBox.style.display = 'block';
        }

        function clearAuthError() {
            if (!authErrorBox) return;
            authErrorBox.textContent = '';
            authErrorBox.style.display = 'none';
        }

        form.addEventListener('submit', function (event) {
            if (allowSubmit) {
                setBtnLoading('正在登录…', true);
                return;
            }

            clearAuthError();
            if (typeof window.checkAuth !== 'function') {
                event.preventDefault();
                setBtnLoading('登 录', false);
                showAuthError('登录失败，请稍后重试。');
                return;
            }

            event.preventDefault();
            setBtnLoading('正在登录…', true);
            Promise.resolve(window.checkAuth()).then(function (result) {
                if (!result || !result.success) {
                    setBtnLoading('登 录', false);
                    showAuthError((result && result.message) ? result.message : '网络异常，请稍后重试。');
                    return;
                }

                allowSubmit = true;
                if (checkedInput) checkedInput.value = '1';
                setBtnLoading('正在登录…', true);
                form.submit();
            }).catch(function () {
                setBtnLoading('登 录', false);
                showAuthError('网络异常，请稍后重试。');
            });
        }, true);
    })();
</script>
</body>
</html>





