<?php
require "config.php";

// Active l’affichage des erreurs PHP (pour debug)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 1. Vérifie si les champs existent
if (!isset($_POST['username'], $_POST['password'])) {
    echo "missing_fields";
    exit;
}

$username = trim($_POST['username']);
$password = $_POST['password'];

// 2. Vérifie les valeurs vides
if ($username === "" || $password === "") {
    echo "empty";
    exit;
}

// 3. Vérifie si le nom existe déjà
$req = $pdo->prepare("SELECT id FROM users WHERE username = ?");
$req->execute([$username]);

if ($req->rowCount() > 0) {
    echo "exists";
    exit;
}

// 4. Hash du mot de passe
$hashed = password_hash($password, PASSWORD_BCRYPT);

// 5. Insert
$insert = $pdo->prepare("INSERT INTO users (username, password) VALUES (?, ?)");

if ($insert->execute([$username, $hashed])) {
    echo "ok";
} else {
    echo "sql_error";
}
