<?php
require "config.php";

header("Content-Type: application/json");

if (!isset($_POST['username'], $_POST['password'])) {
    echo json_encode(["success" => false, "message" => "missing_fields"]);
    exit;
}

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

// Vérifier si l'utilisateur existe déjà
$check = $pdo->prepare("SELECT id FROM users WHERE username = ?");
$check->execute([$username]);

if ($check->rowCount() > 0) {
    echo json_encode(["success" => false, "message" => "exists"]);
    exit;
}

// Insérer
$insert = $pdo->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
$insert->execute([$username, $password]);

// RÉCUPÉRER L'ID DU NOUVEL UTILISATEUR
$userId = $pdo->lastInsertId();

// DÉMARRER LA SESSION POUR LE NOUVEL UTILISATEUR
$_SESSION['user'] = $username;
$_SESSION['user_id'] = $userId;

echo json_encode(["success" => true]);
exit;
?>