black-sheep-bluff/app/Services/RoomService.php
2026-09-18 06:46:56 +02:00

336 lines
13 KiB
PHP

<?php
declare(strict_types=1);
/**
* Spiel-Kernlogik (1:1 aus api.php uebernommen):
* Raum laden, Stimmen auswerten, Runde abschliessen, Admin-Check.
*/
final class RoomService
{
public static function loadRoom(PDO $pdo, string $code, bool $revealLiars = false): ?array
{
$stmt = $pdo->prepare(
'SELECT code, revealed, liar_keys, normal_question, imposter_question,
round_num, voted_out_keys, round_outcome, voting_open, active_emojis,
reveal_index, revealed_keys, imposter_weights, questions_revealed
FROM gtl_rooms WHERE code = ?'
);
$stmt->execute([$code]);
$room = $stmt->fetch();
if ($room === false) return null;
$j = fn($v) => (!empty($v) && is_string($v)) ? (json_decode($v, true) ?: []) : [];
$ps = $pdo->prepare(
'SELECT p.pkey, p.name, p.user_id, p.question, p.answer, p.answered, p.score,
p.vote_for, p.vote_locked, p.vote_request, p.late_join,
u.avatar, u.color, u.sticker, u.color2, u.name_style, u.name_font
FROM gtl_players p
LEFT JOIN gtl_users u ON u.id = p.user_id
WHERE p.room_code = ? ORDER BY p.id ASC'
);
$ps->execute([$code]);
$players = [];
foreach ($ps->fetchAll() as $row) {
// Parse vote_for: JSON array (new) or legacy single pkey string
$voteRaw = $row['vote_for'] ?? null;
if ($voteRaw !== null && str_starts_with(ltrim((string) $voteRaw), '[')) {
$parsedVotes = json_decode($voteRaw, true) ?: [];
} elseif ($voteRaw !== null && $voteRaw !== '') {
$parsedVotes = [$voteRaw];
} else {
$parsedVotes = [];
}
$players[$row['pkey']] = [
'pkey' => $row['pkey'],
'name' => $row['name'],
'userId' => $row['user_id'] ? (int) $row['user_id'] : null,
'avatar' => $row['avatar'] ?? null,
'color' => $row['color'] ?? null,
'color2' => $row['color2'] ?? null,
'nameStyle' => $row['name_style'] ?? 'solid',
'nameFont' => $row['name_font'] ?? null,
'question' => $row['question'] ?? '',
'answer' => $row['answer'] ?? '',
'answered' => (bool) $row['answered'],
'score' => (int) $row['score'],
'votes' => $parsedVotes,
'voteLocked' => (bool) ($row['vote_locked'] ?? false),
'voteRequest' => (bool) ($row['vote_request'] ?? false),
'lateJoin' => (bool) ($row['late_join'] ?? false),
'sticker' => $row['sticker'] ?? null,
];
}
$outcome = $room['round_outcome'] ?? null;
return [
'code' => $room['code'],
'revealed' => (bool) $room['revealed'],
// liarKeys only sent after resolution — prevents clients from seeing imposters early.
// Admin spectators ($revealLiars) get them immediately to mirror the host view.
'liarKeys' => ($outcome || $revealLiars) ? $j($room['liar_keys']) : [],
'normalQuestion' => $room['normal_question'] ?? '',
'imposterQuestion' => $room['imposter_question'] ?? '',
'roundNum' => (int) $room['round_num'],
'votedOutKeys' => $j($room['voted_out_keys']),
'roundOutcome' => $outcome,
'votingOpen' => (bool) ($room['voting_open'] ?? false),
'revealIndex' => (int) ($room['reveal_index'] ?? -1),
'revealedKeys' => $j($room['revealed_keys'] ?? ''),
'questionsRevealed'=> (bool) ($room['questions_revealed'] ?? false),
'imposterWeights' => $room['imposter_weights'] ?? null,
'activeEmojis' => array_values(array_filter(
$j($room['active_emojis'] ?? '[]'),
fn($e) => ($e['ts'] ?? 0) >= (time() - 4)
)),
'players' => $players,
'chat' => (function() use ($pdo, $code) {
try {
$cs = $pdo->prepare(
'SELECT player_name, message, created_at FROM gtl_chat_messages
WHERE room_code=? ORDER BY created_at DESC, id DESC LIMIT 30'
);
$cs->execute([$code]);
return array_reverse($cs->fetchAll());
} catch (Throwable) { return []; }
})(),
];
}
/**
* Bestimmt, wer herausgewählt wurde.
*
* Regeln:
* - Nur Niemand hat Max-Stimmen → niemand raus
* - Tie Niemand + User, User ist Imposter → Imposter raus
* - Tie Niemand + User, User ist kein Imposter → niemand raus (Tie geht an Niemand)
* - Tie zwischen echten Spielern (ohne Niemand) → alle raus
*
* @param array<array<string,mixed>> $players
* @param array<string> $liarKeys
* @return array<string> pkeys der herausgewählten Spieler
*/
public static function resolveVotes(array $players, array $liarKeys): array
{
$tally = ['__nobody__' => 0];
foreach ($players as $p) {
$tally[$p['pkey']] = 0;
}
foreach ($players as $p) {
$votes = $p['votes'] ?? [];
if (!is_array($votes)) $votes = [];
if (empty($votes)) {
$tally['__nobody__']++;
} else {
// __nobody__ is exclusive: if present, count only as nobody
if (in_array('__nobody__', $votes, true)) {
$tally['__nobody__']++;
} else {
foreach ($votes as $vf) {
if (array_key_exists($vf, $tally)) {
$tally[$vf]++;
}
}
}
}
}
$max = max($tally);
if ($max === 0) return [];
$top = array_keys(array_filter($tally, fn($v) => $v === $max));
// Nur Niemand → niemand raus
if ($top === ['__nobody__']) {
return [];
}
$hasNobody = in_array('__nobody__', $top, true);
$realCandidates = array_values(array_filter($top, fn($k) => $k !== '__nobody__'));
if (!$hasNobody) {
// Reiner Tie zwischen echten Spielern → alle raus
return $realCandidates;
}
// Tie Niemand + Spieler: nur Imposters unter den Tied fliegen raus
// (Innocent überlebt den Tie mit Niemand)
return array_values(array_filter($realCandidates, fn($pk) => in_array($pk, $liarKeys, true)));
}
/**
* Archiviert die aktuelle Runde in gtl_game_rounds + gtl_round_players.
* Idempotent: läuft resolve_round vorher, wird nur outcome aktualisiert.
* Stats werden NICHT hier aktualisiert (nur in resolve_round).
*/
public static function archiveRound(PDO $pdo, array $state, int $now): void
{
$code = $state['code'];
$roundNum = $state['roundNum'];
$outcome = $state['roundOutcome'] ?: null;
$liarKeys = $state['liarKeys'];
$votedOut = $state['votedOutKeys'];
$existing = $pdo->prepare('SELECT id FROM gtl_game_rounds WHERE room_code=? AND round_num=?');
$existing->execute([$code, $roundNum]);
$row = $existing->fetch();
if ($row) {
// Nur Outcome aktualisieren falls noch nicht gesetzt
if ($outcome && !$pdo->query("SELECT outcome FROM gtl_game_rounds WHERE id={$row['id']}")->fetchColumn()) {
$pdo->prepare('UPDATE gtl_game_rounds SET outcome=? WHERE id=?')
->execute([$outcome, $row['id']]);
}
return; // Spieler bereits archiviert
}
$pdo->prepare('INSERT INTO gtl_game_rounds (room_code, round_num, played_at, outcome) VALUES (?,?,?,?)')
->execute([$code, $roundNum, $now, $outcome]);
$roundId = (int) $pdo->lastInsertId();
$ins = $pdo->prepare(
'INSERT IGNORE INTO gtl_round_players
(round_id, user_id, player_name, pkey, was_imposter, voted_out, question, answer)
VALUES (?,?,?,?,?,?,?,?)'
);
foreach ($state['players'] as $p) {
$ins->execute([
$roundId,
$p['userId'],
$p['name'],
$p['pkey'],
in_array($p['pkey'], $liarKeys, true) ? 1 : 0,
in_array($p['pkey'], $votedOut, true) ? 1 : 0,
$p['question'],
$p['answer'],
]);
}
}
/**
* Führt die Rundenauswertung durch. Liest liar_keys direkt aus der DB,
* damit die Redaktion in loadRoom() (liarKeys=[] solange roundOutcome=null) umgangen wird.
* Schreibt Ergebnis, Archiv, Punkte und Profil-Stats.
*
* @return array Neuer state nach Auswertung (loadRoom-Ergebnis).
*/
public static function performResolveRound(PDO $pdo, string $code, int $now): array
{
$j = fn($v) => (!empty($v) && is_string($v)) ? (json_decode($v, true) ?: []) : [];
// Liar-Keys direkt lesen — loadRoom() würde sie ohne roundOutcome verstecken
$lkStmt = $pdo->prepare('SELECT liar_keys FROM gtl_rooms WHERE code=?');
$lkStmt->execute([$code]);
$lkRow = $lkStmt->fetch();
$liarKeys = $j($lkRow['liar_keys'] ?? '');
$state = self::loadRoom($pdo, $code);
$players = $state['players'];
// Nachzügler (Zuschauer dieser Runde) zählen nicht für Voting/Verlauf/Statistik
$activePlayers = array_filter($players, fn($p) => empty($p['lateJoin']));
$votedOut = self::resolveVotes(array_values($activePlayers), $liarKeys);
if (empty($liarKeys)) {
$outcome = 'no_liar';
} elseif (empty($votedOut)) {
$outcome = 'imposters_win';
} elseif (empty(array_diff($liarKeys, $votedOut))) {
$outcome = 'innocents_win';
} else {
$outcome = 'imposters_win';
}
$allPkeys = array_keys($players);
$pdo->prepare(
'UPDATE gtl_rooms SET voted_out_keys=?, round_outcome=?, revealed=1, reveal_index=9999,
revealed_keys=?, updated_at=? WHERE code=?'
)->execute([json_encode($votedOut), $outcome, json_encode($allPkeys), $now, $code]);
// Verlauf speichern
$existing = $pdo->prepare('SELECT id FROM gtl_game_rounds WHERE room_code=? AND round_num=?');
$existing->execute([$code, $state['roundNum']]);
$existingRow = $existing->fetch();
if ($existingRow) {
$roundId = (int) $existingRow['id'];
$pdo->prepare('UPDATE gtl_game_rounds SET outcome=? WHERE id=?')
->execute([$outcome, $roundId]);
$updVo = $pdo->prepare('UPDATE gtl_round_players SET voted_out=? WHERE round_id=? AND pkey=?');
foreach ($players as $p) {
$updVo->execute([in_array($p['pkey'], $votedOut, true) ? 1 : 0, $roundId, $p['pkey']]);
}
} else {
$pdo->prepare(
'INSERT INTO gtl_game_rounds (room_code, round_num, played_at, outcome) VALUES (?,?,?,?)'
)->execute([$code, $state['roundNum'], $now, $outcome]);
$roundId = (int) $pdo->lastInsertId();
$ins = $pdo->prepare(
'INSERT IGNORE INTO gtl_round_players
(round_id, user_id, player_name, pkey, was_imposter, voted_out, question, answer)
VALUES (?,?,?,?,?,?,?,?)'
);
foreach ($activePlayers as $p) {
$ins->execute([
$roundId, $p['userId'], $p['name'], $p['pkey'],
in_array($p['pkey'], $liarKeys, true) ? 1 : 0,
in_array($p['pkey'], $votedOut, true) ? 1 : 0,
$p['question'], $p['answer'],
]);
}
}
// Punkte + Profil-Stats
$updStats = $pdo->prepare(
'UPDATE gtl_user_stats SET
games_played = games_played + 1,
games_won = games_won + ?,
games_lost = games_lost + ?,
times_imposter = times_imposter + ?,
imposter_wins = imposter_wins + ?,
imposter_losses = imposter_losses + ?,
innocent_wins = innocent_wins + ?,
innocent_losses = innocent_losses + ?
WHERE user_id = ?'
);
$updScore = $pdo->prepare(
'UPDATE gtl_players SET score=score+1, updated_at=? WHERE room_code=? AND pkey=?'
);
foreach ($activePlayers as $p) {
$wasImposter = in_array($p['pkey'], $liarKeys, true);
$wasVotedOut = in_array($p['pkey'], $votedOut, true);
$playerWon = $wasImposter ? !$wasVotedOut : ($outcome === 'innocents_win');
if ($playerWon) {
$updScore->execute([$now, $code, $p['pkey']]);
}
if (!$p['userId']) continue;
$updStats->execute([
$playerWon ? 1 : 0,
$playerWon ? 0 : 1,
$wasImposter ? 1 : 0,
$wasImposter && $playerWon ? 1 : 0,
$wasImposter && !$playerWon ? 1 : 0,
!$wasImposter && $playerWon ? 1 : 0,
!$wasImposter && !$playerWon ? 1 : 0,
$p['userId'],
]);
}
return self::loadRoom($pdo, $code);
}
public static function requireAdminApi(PDO $pdo, $authUserId): void
{
if (!$authUserId) respond(['error' => 'Bitte erst einloggen.'], 401);
$st = $pdo->prepare('SELECT role FROM gtl_users WHERE id = ?');
$st->execute([$authUserId]);
if ($st->fetchColumn() !== 'admin') respond(['error' => 'Keine Berechtigung.'], 403);
}
}