<?php
require "config.php";
header("Content-Type: application/json");

// Vérifier login
if (!isset($_SESSION["user_id"])) {
    echo json_encode(["success" => false, "error" => "not_logged"]);
    exit;
}

$user_id = intval($_SESSION["user_id"]);

// Vérifier team demandée
if (!isset($_POST["team"])) {
    echo json_encode(["success" => false, "error" => "no_team"]);
    exit;
}

$team = $_POST["team"];
if ($team !== "bleu" && $team !== "rouge") {
    echo json_encode(["success" => false, "error" => "invalid_team"]);
    exit;
}

// Vérifier si une partie est déjà en cours (2 joueurs présents)
$checkFull = $pdo->prepare("SELECT COUNT(*) as total FROM team_queue");
$checkFull->execute();
$totalPlayers = $checkFull->fetchColumn();

if ($totalPlayers >= 2) {
    echo json_encode(["success" => false, "error" => "game_full"]);
    exit;
}

// Vérifier si l'équipe est déjà prise
$checkTeam = $pdo->prepare("SELECT COUNT(*) FROM team_queue WHERE team = ?");
$checkTeam->execute([$team]);
$teamCount = $checkTeam->fetchColumn();

if ($teamCount >= 1) {
    echo json_encode(["success" => false, "error" => "team_full"]);
    exit;
}

// Supprimer l'ancienne entrée de CE joueur
$pdo->prepare("DELETE FROM team_queue WHERE user_id = ?")->execute([$user_id]);

// Ajouter CE joueur dans la file
$insert = $pdo->prepare("INSERT INTO team_queue (user_id, team) VALUES (?, ?)");
$insert->execute([$user_id, $team]);

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