<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {

    $username = $_POST["username"];
    $email = $_POST["email"];
    $password = $_POST["password"];
    $confirm = $_POST["confirm"];

    if (!$username || !$email || !$password || !$confirm) {
        echo "Semua field wajib diisi";
        exit;
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "Email tidak valid";
        exit;
    }

    if ($password !== $confirm) {
        echo "Password tidak cocok";
        exit;
    }

    // contoh simpan ke file JSON
    $file = "users.json";
    $users = file_exists($file) ? json_decode(file_get_contents($file), true) : [];

    foreach ($users as $u) {
        if ($u["username"] === $username) {
            echo "Username sudah digunakan";
            exit;
        }
        if ($u["email"] === $email) {
            echo "Email sudah digunakan";
            exit;
        }
    }

    $users[] = [
        "id" => time(),
        "username" => $username,
        "email" => $email,
        "password" => $password,
        "role" => "player"
    ];

    file_put_contents($file, json_encode($users, JSON_PRETTY_PRINT));
    echo "success";
}
?>
