<?php
session_start();
$userFile = 'users.json';

$err = '';
if (!empty($_POST['user']) && !empty($_POST['pwd'])) {
    $user = trim($_POST['user']);
    $pwd = trim($_POST['pwd']);

    if (strlen($user) < 2 || strlen($user) > 16) {
        $err = '用户名长度 2-16 位';
    } elseif (strlen($pwd) < 4) {
        $err = '密码至少 4 位';
    } else {
        $users = json_decode(@file_get_contents($userFile), true) ?? [];
        foreach ($users as $u) {
            if (strtolower($u['name']) === strtolower($user)) {
                $err = '用户名已存在';
                break;
            }
        }
        if (!$err) {
            $users[] = [
                'name' => $user,
                'pwd'  => password_hash($pwd, PASSWORD_DEFAULT),
                'time' => date('Y-m-d H:i')
            ];
            file_put_contents($userFile, json_encode($users, JSON_UNESCAPED_UNICODE));
            header('Location: login.php');
            exit;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>注册</title>
<style>
*{box-sizing:border-box}
body{margin:0;padding:20px;background:#111;color:#fff;font-family:system-ui}
.box{max-width:400px;margin:0 auto;background:#222;padding:24px;border-radius:12px}
input{width:100%;padding:12px;margin:8px 0;background:#333;color:#fff;border:0;border-radius:8px;font-size:16px}
button{width:100%;padding:12px;background:#07c;color:#fff;border:0;border-radius:8px;font-size:16px;margin-top:8px}
.err{color:#f44;text-align:center}
a{color:#0cf;text-decoration:none}
</style>
</head>
<body>
<div class="box">
<h2>注册</h2>
<?php if($err) echo "<div class='err'>$err</div>";?>
<form method="post">
<input name="user" placeholder="用户名" required>
<input name="pwd" type="password" placeholder="密码" required>
<button type="submit">注册</button>
</form>
<p style="text-align:center">已有账号？<a href="login.php">去登录</a></p>
</div>
</body>
</html>
