<?php
session_start();

// 配置文件路径
$configFile = __DIR__ . '/config/config.php';

// 如果配置文件已经存在，直接跳转到登录
if (file_exists($configFile)) {
    header('Location: login.php');
    exit;
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['username'], $_POST['password'], $_POST['password_confirm'])) {
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    $passwordConfirm = trim($_POST['password_confirm']);

    if ($username && $password && $passwordConfirm) {
        if ($password !== $passwordConfirm) {
            $error = "两次输入的密码不一致";
        } else {
            // 确保 config 目录存在
            if (!is_dir(__DIR__ . '/config')) {
                mkdir(__DIR__ . '/config', 0755, true);
            }

            // 密码加密
            $passwordHash = password_hash($password, PASSWORD_DEFAULT);

            // 写入配置文件
            $configContent = "<?php\nreturn [\n    'username' => '" . addslashes($username) . "',\n    'password' => '" . addslashes($passwordHash) . "'\n];\n";
            file_put_contents($configFile, $configContent);

            // 设置登录状态
            $_SESSION['logged_in'] = true;

            header('Location: index.php');
            exit;
        }
    } else {
        $error = "请输入完整的用户名和密码";
    }
}
?>
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>初始化账号</title>
<style>
body { font-family: "Segoe UI", Arial, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background:#f9fafc; }
.setup-box { background: #fff; padding: 30px 50px; border-radius: 10px; box-shadow: 0 3px 12px rgba(0,0,0,0.15); }
h2 { margin-bottom: 20px; color:#2c3e50; text-align:center; }
input { display: block; padding: 10px; margin-bottom: 15px; width: 240px; border-radius: 6px; border:1px solid #ccc; box-sizing: border-box; }
button { padding: 10px; width: 100%; background: #4CAF50; color: #fff; border: none; border-radius:6px; cursor: pointer; font-size:15px; }
button:hover { opacity:0.9; }
.error { color: #f44336; margin-bottom: 10px; text-align:center; }
</style>
</head>
<body>
<div class="setup-box">
<h2>初始化账号</h2>
<?php if (!empty($error)) echo "<div class='error'>{$error}</div>"; ?>
<form method="post">
<input type="text" name="username" placeholder="设置用户名" required>
<input type="password" name="password" placeholder="设置密码" required>
<input type="password" name="password_confirm" placeholder="确认密码" required>
<button type="submit">保存账号</button>
</form>
</div>
</body>
</html>
