<?php
$file_db = 'users.json';

if (isset($_POST['register'])) {
    $username = preg_replace('/[^a-zA-Z0-9]/', '', $_POST['user']); // Chỉ lấy chữ và số
    $password = $_POST['pass'];

    $users = file_exists($file_db) ? json_decode(file_get_contents($file_db), true) : [];

    if (isset($users[$username])) {
        $error = "Tài khoản này đã tồn tại!";
    } else {
        // Tạo user mới
        $users[$username] = [
            'username' => $username,
            'password' => $password,
            'coin' => 0, // Tặng 0 xu
            'role' => 'member'
        ];
        // Lưu lại vào file
        file_put_contents($file_db, json_encode($users));
        echo "<script>alert('Đăng ký thành công!'); window.location.href='login.php';</script>";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Đăng ký</title>
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <div class="container" style="display:flex; justify-content:center; align-items:center; height:100vh;">
        <div class="glass-panel">
            <h2 style="text-align:center; color: #ff0055;">ĐĂNG KÝ</h2>
            <?php if(isset($error)) echo "<p style='color:red; text-align:center'>$error</p>"; ?>
            <form method="POST">
                <input type="text" name="user" class="input-group" placeholder="Tài khoản (Viết liền k dấu)" required>
                <input type="password" name="pass" class="input-group" placeholder="Mật khẩu" required>
                <button type="submit" name="register" class="btn btn-primary" style="width:100%; background: #ff0055;">Tạo Tài Khoản</button>
            </form>
            <p style="text-align:center; margin-top:15px;">
                <a href="login.php" style="color:#aaa;">Đã có nick? Đăng nhập</a>
            </p>
        </div>
    </div>
</body>
</html>
