<?php
include 'db.php';

if (isset($_POST['register'])) {
    $username = $_POST['username'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $referral_code = substr(md5(uniqid()), 0, 8);
    $referred_by = $_POST['referred_by'] ?? NULL;

    $check = $conn->query("SELECT id FROM users WHERE username='$username'");
    if ($check->num_rows > 0) {
        echo "User already exists!";
    } else {
        $conn->query("INSERT INTO users (username, password, balance, referral_code, referred_by) 
                      VALUES ('$username', '$password', 0, '$referral_code', '$referred_by')");
        if ($referred_by) {
            $conn->query("UPDATE users SET balance = balance + 0.005 WHERE referral_code='$referred_by'");
        }
        echo "Registration successful. <a href='login.php'>Login</a>";
    }
}
?>

<form method="POST">
    <input type="text" name="username" required placeholder="Username"><br>
    <input type="password" name="password" required placeholder="Password"><br>
    <input type="text" name="referred_by" placeholder="Referral Code (optional)"><br>
    <button type="submit" name="register">Register</button>
</form>
