<?php
header('Content-Type: application/json');
session_start();
require_once '../db.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Méthode non autorisée.']);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);

$username = trim($data['username'] ?? '');
$email = trim($data['email'] ?? '');
$password = $data['password'] ?? '';

if (empty($username) || empty($email) || empty($password)) {
    echo json_encode(['success' => false, 'message' => 'Veuillez remplir tous les champs.']);
    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['success' => false, 'message' => 'Format d\'email invalide.']);
    exit;
}

try {
    // Vérifier si le username ou l'email existe déjà
    $stmt = $pdo->prepare("SELECT id FROM users WHERE email = :email OR username = :username");
    $stmt->execute(['email' => $email, 'username' => $username]);
    if ($stmt->fetch()) {
        echo json_encode(['success' => false, 'message' => 'Nom d\'utilisateur ou email déjà utilisé.']);
        exit;
    }

    // Hachage du mot de passe
    $hashedPassword = password_hash($password, PASSWORD_BCRYPT);

    // Début de transaction
    $pdo->beginTransaction();

    // Insérer l'utilisateur
    $stmt = $pdo->prepare("INSERT INTO users (username, email, password_hash) VALUES (:username, :email, :password)");
    $stmt->execute([
        'username' => $username,
        'email'    => $email,
        'password' => $hashedPassword
    ]);
    $userId = $pdo->lastInsertId();

    // Initialiser les stats RPG de l'étudiant (Niveau 1, 0 XP, 100 PV)
    $stmtStats = $pdo->prepare("INSERT INTO user_stats (user_id, level, current_xp, health_points, companion_state) VALUES (:user_id, 1, 0, 100, 'happy')");
    $stmtStats->execute(['user_id' => $userId]);

    $pdo->commit();

    // Connecter directement l'utilisateur
    $_SESSION['user_id'] = $userId;
    $_SESSION['username'] = $username;

    echo json_encode([
        'success' => true,
        'message' => 'Compte créé avec succès ! Bienvenue dans MMI Simulator.',
        'user' => [
            'id' => $userId,
            'username' => $username,
            'email' => $email
        ]
    ]);

} catch (PDOException $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    echo json_encode(['success' => false, 'message' => 'Erreur serveur : ' . $e->getMessage()]);
}
?>