<?php
declare(strict_types=1);

require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'auth.php';

if (is_logged_in()) {
    header('Location: index.php');
    exit;
}

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

    if (login($username, $password)) {
        header('Location: index.php');
        exit;
    }
    $error = '账号或密码错误';
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>后台登录 - <?= APP_NAME ?></title>
    <style>
        body{
            margin:0;
            min-height:100vh;
            display:grid;
            place-items:center;
            background:radial-gradient(circle at top,#1d4ed8,#0f172a 45%);
            font-family:"Microsoft YaHei",Arial,sans-serif;
        }
        .card{
            width:380px;
            background:#fff;
            border-radius:14px;
            padding:28px;
            box-shadow:0 20px 40px rgba(2,6,23,.25);
        }
        h2{ margin:0 0 18px; color:#0f172a; }
        .group{ margin-bottom:12px; }
        label{ display:block; margin-bottom:6px; color:#475569; font-size:14px; }
        input{
            width:100%; padding:10px 12px; border:1px solid #cbd5e1; border-radius:8px; font-size:15px;
        }
        button{
            width:100%; margin-top:8px; border:0; background:#2563eb; color:#fff;
            padding:11px 0; border-radius:8px; font-weight:600; cursor:pointer;
        }
        .error{ color:#dc2626; margin-bottom:10px; font-size:14px; }
        .back{ text-align:center; margin-top:8px; }
        .back a{ color:#2563eb; text-decoration:none; font-size:13px; }
    </style>
</head>
<body>
<form class="card" method="post">
    <h2><?= APP_NAME ?> 后台</h2>
    <?php if ($error !== ''): ?>
        <div class="error"><?= h($error) ?></div>
    <?php endif; ?>
    <div class="group">
        <label>账号</label>
        <input name="username" type="text" required>
    </div>
    <div class="group">
        <label>密码</label>
        <input name="password" type="password" required>
    </div>
    <button type="submit">登录</button>
    <div class="back"><a href="../index.php">返回官网首页</a></div>
</form>
</body>
</html>
