<?php
require_once dirname(__DIR__) . '/core/lib/session.php';
cmsStartSession();
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'logout') {
    $logoutToken = (string) ($_POST['csrf_token'] ?? '');
    if (empty($_SESSION['admin_csrf_token']) || !hash_equals($_SESSION['admin_csrf_token'], $logoutToken)) {
        http_response_code(403);
        exit('退出请求校验失败');
    }
    unset($_SESSION['admin_id'], $_SESSION['admin_name'], $_SESSION['admin_realname'], $_SESSION['admin_role']);
    session_destroy();
    header('Location: /admin/login.php');
    exit;
}

require_once dirname(__DIR__) . '/core/db/db.php';
require_once dirname(__DIR__) . '/core/lib/common.php';
require_once dirname(__DIR__) . '/core/lib/login_security.php';

if (isset($_SESSION['admin_id']) && !empty($_SESSION['admin_id'])) {
    header('Location: /admin/index.php');
    exit;
}

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = trim($_POST['password'] ?? '');
    $captcha = trim($_POST['captcha'] ?? '');
    $clientIp = cmsLoginClientIp();

    $loginToken = (string) ($_POST['login_token'] ?? '');
    if (empty($_SESSION['login_token']) || !hash_equals($_SESSION['login_token'], $loginToken)) {
        $error = '登录页面已失效，请刷新后重试';
    } elseif (($loginLock = cmsGetLoginLock($username, $clientIp))['locked']) {
        $minutes = max(1, (int) ceil($loginLock['retry_after'] / 60));
        $error = '登录尝试过于频繁，请在 ' . $minutes . ' 分钟后重试';
    } elseif ($captcha === '' || !isset($_SESSION['captcha']) || strtolower($captcha) !== strtolower($_SESSION['captcha'])) {
        $error = '验证码错误';
    } elseif ($username === '' || $password === '') {
        $error = '请输入用户名和密码';
    } else {
        try {
            $db = \Core\Db\DB::getInstance();
            $admin = $db->fetch("SELECT * FROM {$db->table('admin')} WHERE username = ? AND is_enabled = 1 LIMIT 1", [$username]);
            if ($admin) {
                $passwordMatched = password_verify($password, $admin['password']);
                $legacyMd5Matched = !$passwordMatched && md5($password) === $admin['password'];
                if ($passwordMatched || $legacyMd5Matched) {
                    if ($legacyMd5Matched) {
                        $db->update('admin', [
                            'password' => password_hash($password, PASSWORD_DEFAULT),
                            'update_time' => time()
                        ], 'id = ?', [$admin['id']]);
                    }
                    session_regenerate_id(true);
                    $_SESSION['admin_id'] = $admin['id'];
                    $_SESSION['admin_name'] = $admin['username'];
                    $_SESSION['admin_realname'] = $admin['realname'];
                    $_SESSION['admin_role'] = $admin['role_id'];
                    $_SESSION['last_activity'] = time();
                    cmsClearLoginFailures($username, $clientIp);
                    cmsWriteLoginSecurityLog('登录成功', $username, '后台管理员登录成功');
                    $db->update('admin', ['last_login_time' => time(), 'last_login_ip' => $_SERVER['REMOTE_ADDR'] ?? ''], 'id = ?', [$admin['id']]);
                    header('Location: /admin/index.php');
                    exit;
                }
            }
            $lockedNow = cmsRecordLoginFailure($username, $clientIp);
            cmsWriteLoginSecurityLog($lockedNow ? '登录锁定' : '登录失败', $username, $lockedNow ? '凭据连续失败，已临时锁定' : '后台登录凭据错误');
            $error = $lockedNow ? '登录尝试过于频繁，请在 15 分钟后重试' : '用户名或密码错误';
        } catch (Exception $e) {
            $error = '系统错误，请稍后再试';
        }
    }
}

$captchaCode = substr(md5(uniqid('', true)), 0, 4);
$_SESSION['captcha'] = $captchaCode;
$_SESSION['login_token'] = bin2hex(random_bytes(32));
$imgWidth = 140;
$imgHeight = 50;
$img = imagecreatetruecolor($imgWidth, $imgHeight);
$bgColor = imagecolorallocate($img, 243, 246, 255);
imagefill($img, 0, 0, $bgColor);
for ($i = 0; $i < 3; $i++) {
    $lineColor = imagecolorallocate($img, rand(210, 230), rand(210, 230), rand(235, 255));
    imageline($img, rand(0, $imgWidth), rand(0, $imgHeight), rand(0, $imgWidth), rand(0, $imgHeight), $lineColor);
}
$textColor = imagecolorallocate($img, 92, 86, 244);
for ($i = 0; $i < strlen($captchaCode); $i++) {
    imagestring($img, 5, 16 + $i * 28, 15, $captchaCode[$i], $textColor);
}
for ($i = 0; $i < 50; $i++) {
    $dotColor = imagecolorallocate($img, rand(180, 210), rand(180, 210), rand(200, 235));
    imagesetpixel($img, rand(0, $imgWidth), rand(0, $imgHeight), $dotColor);
}
ob_start();
imagepng($img);
$captchaBase64 = base64_encode(ob_get_clean());
imagedestroy($img);

$siteName = 'EnterpriseCMS';
try {
    $db = \Core\Db\DB::getInstance();
    $nameConfig = $db->fetch("SELECT config_value FROM {$db->table('config')} WHERE config_key = 'site_name'");
    if ($nameConfig && !empty($nameConfig['config_value'])) {
        $siteName = $nameConfig['config_value'];
    }
} catch (Exception $e) {
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="/template/default/skin/images/logo.png">
    <title><?php echo htmlspecialchars($siteName, ENT_QUOTES, 'UTF-8'); ?> - 管理员登录</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css">
    <style>
        * { box-sizing: border-box; }
        body {
            margin: 0;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 24px;
            font-family: "Microsoft YaHei", "PingFang SC", -apple-system, BlinkMacSystemFont, sans-serif;
            background:
                radial-gradient(circle at 20% 16%, rgba(109, 94, 252, 0.28), transparent 26%),
                radial-gradient(circle at 86% 20%, rgba(79, 140, 255, 0.22), transparent 24%),
                linear-gradient(180deg, #101725 0%, #151d2d 46%, #111827 100%);
            color: #fff;
        }
        .login-shell {
            width: min(1180px, 100%);
            display: grid;
            grid-template-columns: minmax(0, 1.1fr) minmax(360px, 440px);
            gap: 28px;
            align-items: stretch;
        }
        .login-showcase {
            padding: 40px 42px;
            border-radius: 30px;
            background: rgba(255, 255, 255, 0.06);
            border: 1px solid rgba(255, 255, 255, 0.08);
            box-shadow: 0 28px 72px rgba(15, 23, 42, 0.22);
            backdrop-filter: blur(18px);
        }
        .showcase-badge {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            height: 36px;
            padding: 0 14px;
            border-radius: 999px;
            background: rgba(255, 255, 255, 0.1);
            color: #dce4ff;
            font-size: 12px;
            font-weight: 700;
            letter-spacing: 0.06em;
            text-transform: uppercase;
        }
        .showcase-title {
            margin: 24px 0 12px;
            font-size: 40px;
            line-height: 1.2;
            font-weight: 800;
            letter-spacing: -0.03em;
        }
        .showcase-desc {
            max-width: 620px;
            margin: 0;
            color: rgba(255, 255, 255, 0.72);
            font-size: 15px;
            line-height: 1.9;
        }
        .showcase-grid {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 16px;
            margin-top: 28px;
        }
        .showcase-card {
            min-height: 138px;
            padding: 18px;
            border-radius: 22px;
            background: rgba(255, 255, 255, 0.07);
            border: 1px solid rgba(255, 255, 255, 0.08);
        }
        .showcase-card i {
            width: 40px;
            height: 40px;
            border-radius: 14px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 16px;
            background: rgba(255, 255, 255, 0.12);
            color: #fff;
            font-size: 18px;
        }
        .showcase-card strong {
            display: block;
            margin-bottom: 8px;
            font-size: 16px;
        }
        .showcase-card span {
            display: block;
            color: rgba(255, 255, 255, 0.68);
            font-size: 13px;
            line-height: 1.8;
        }
        .login-card {
            padding: 30px;
            border-radius: 30px;
            background: rgba(255, 255, 255, 0.96);
            box-shadow: 0 28px 72px rgba(15, 23, 42, 0.26);
            color: #1f2937;
        }
        .login-head {
            margin-bottom: 24px;
        }
        .login-brand {
            display: inline-flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 18px;
        }
        .login-brand-icon {
            width: 48px;
            height: 48px;
            border-radius: 16px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            background: linear-gradient(135deg, #6d5efc, #4f8cff);
            color: #fff;
            font-size: 22px;
        }
        .login-brand-text strong {
            display: block;
            font-size: 18px;
            font-weight: 800;
            color: #1f2937;
        }
        .login-brand-text span {
            display: block;
            margin-top: 4px;
            color: #64748b;
            font-size: 12px;
        }
        .login-head h1 {
            margin: 0 0 8px;
            font-size: 28px;
            font-weight: 800;
            color: #111827;
        }
        .login-head p {
            margin: 0;
            color: #64748b;
            font-size: 13px;
            line-height: 1.8;
        }
        .error-message {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 18px;
            padding: 12px 14px;
            border-radius: 14px;
            background: #fff1f1;
            border: 1px solid #f9caca;
            color: #c81e1e;
            font-size: 13px;
            font-weight: 700;
        }
        .form-group {
            margin-bottom: 18px;
        }
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-size: 13px;
            font-weight: 700;
            color: #334155;
        }
        .field {
            position: relative;
        }
        .field i {
            position: absolute;
            left: 14px;
            top: 50%;
            transform: translateY(-50%);
            color: #94a3b8;
            font-size: 15px;
        }
        .field input {
            width: 100%;
            height: 48px;
            padding: 0 14px 0 42px;
            border-radius: 14px;
            border: 1px solid #dbe2f2;
            background: #fbfcff;
            color: #111827;
            font-size: 14px;
            outline: none;
            transition: border-color .18s ease, box-shadow .18s ease, background .18s ease;
        }
        .field input:focus {
            border-color: rgba(109, 94, 252, 0.5);
            box-shadow: 0 0 0 4px rgba(109, 94, 252, 0.08);
            background: #fff;
        }
        .captcha-row {
            display: grid;
            grid-template-columns: 1fr 132px;
            gap: 12px;
        }
        .captcha-img {
            width: 132px;
            height: 48px;
            border-radius: 14px;
            border: 1px solid #dbe2f2;
            background: #f8fbff;
            cursor: pointer;
        }
        .btn-login {
            width: 100%;
            height: 50px;
            border: none;
            border-radius: 14px;
            background: linear-gradient(135deg, #6d5efc 0%, #4f8cff 100%);
            color: #fff;
            font-size: 15px;
            font-weight: 800;
            cursor: pointer;
            box-shadow: 0 18px 28px rgba(109, 94, 252, 0.22);
            transition: transform .18s ease, box-shadow .18s ease;
        }
        .btn-login:hover {
            transform: translateY(-1px);
            box-shadow: 0 24px 34px rgba(109, 94, 252, 0.28);
        }
        .login-meta {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: 16px;
            color: #94a3b8;
            font-size: 12px;
        }
        .login-meta a {
            color: #6d5efc;
            text-decoration: none;
        }
        @media (max-width: 980px) {
            .login-shell {
                grid-template-columns: 1fr;
            }
            .login-showcase {
                display: none;
            }
        }
        @media (max-width: 520px) {
            body { padding: 14px; }
            .login-card { padding: 22px 18px; border-radius: 24px; }
            .captcha-row { grid-template-columns: 1fr; }
            .captcha-img { width: 100%; }
            .login-head h1 { font-size: 24px; }
        }
    </style>
</head>
<body>
    <div class="login-shell">
        <section class="login-showcase">
            <div class="showcase-badge"><i class="fa fa-circle-o-notch"></i> 控制员控制台</div>
            <h2 class="showcase-title">统一管理企业后台数据，兼顾内容、站点、会员与运营管理。</h2>
            <p class="showcase-desc">当前后台可以管理你网站的所有信息，安装登录后，请立即修改成自己的密码，不要泄露</p>
            <div class="showcase-grid">
                <div class="showcase-card">
                    <i class="fa fa-columns"></i>
                    <strong>工作台框架</strong>
                    <span>后台控制面板可管理所有的文章，产品信息请务必保存好后台管理密码不要外泄。</span>
                </div>
                <div class="showcase-card">
                    <i class="fa fa-list-alt"></i>
                    <strong>统一业务页</strong>
                    <span>列表、筛选、卡片、表单和分页将逐步共用同一套视觉语言。</span>
                </div>
                <div class="showcase-card">
                    <i class="fa fa-shield"></i>
                    <strong>系统管理</strong>
                    <span>模板、授权、日志、数据库和配置入口继续保留原有功能逻辑。</span>
                </div>
                <div class="showcase-card">
                    <i class="fa fa-line-chart"></i>
                    <strong>中台方向</strong>
                    <span>后台适合中国人使用习惯，方便快捷。灵活。</span>
                </div>
            </div>
        </section>

        <section class="login-card">
            <div class="login-head">
                <div class="login-brand">
                    <span class="login-brand-icon"><i class="fa fa-cubes"></i></span>
                    <span class="login-brand-text">
                        <strong><?php echo htmlspecialchars($siteName, ENT_QUOTES, 'UTF-8'); ?></strong>
                        <span>yutouCMS Admin</span>
                    </span>
                </div>
                <h1>管理员登录</h1>
                <p>请输入管理员账号、密码和验证码，进入新的后台工作台。</p>
            </div>

            <?php if ($error !== ''): ?>
            <div class="error-message"><i class="fa fa-warning"></i><span><?php echo htmlspecialchars($error, ENT_QUOTES, 'UTF-8'); ?></span></div>
            <?php endif; ?>

            <form method="post">
                <input type="hidden" name="login_token" value="<?php echo htmlspecialchars($_SESSION['login_token'], ENT_QUOTES, 'UTF-8'); ?>">
                <div class="form-group">
                    <label>用户名</label>
                    <div class="field">
                        <i class="fa fa-user-o"></i>
                        <input type="text" name="username" placeholder="请输入管理员用户名" required autocomplete="username">
                    </div>
                </div>

                <div class="form-group">
                    <label>密码</label>
                    <div class="field">
                        <i class="fa fa-lock"></i>
                        <input type="password" name="password" placeholder="请输入登录密码" required autocomplete="current-password">
                    </div>
                </div>

                <div class="form-group">
                    <label>验证码</label>
                    <div class="captcha-row">
                        <div class="field">
                            <i class="fa fa-shield"></i>
                            <input type="text" name="captcha" placeholder="请输入验证码" required>
                        </div>
                        <img src="data:image/png;base64,<?php echo $captchaBase64; ?>" alt="验证码" class="captcha-img" id="captchaImg" title="点击刷新">
                    </div>
                </div>

                <button type="submit" class="btn-login">进入后台</button>
            </form>

            <div class="login-meta">
                <span>版本入口：后台管理控制台</span>
                <a href="/" target="_blank">访问前台站点</a>
            </div>
        </section>
    </div>
    <script>
    document.getElementById('captchaImg').addEventListener('click', function () {
        this.src = '/admin/captcha.php?t=' + Math.random();
    });
    </script>
</body>
</html>
