diff --git a/src/Models/Ranking.php b/src/Models/Ranking.php index f9f61ee..e3a614f 100644 --- a/src/Models/Ranking.php +++ b/src/Models/Ranking.php @@ -4,157 +4,351 @@ namespace App\Models; use App\Core\Database; +/** + * Rangliste, Tagessieg und Ausschüttungen einer Saison + * (portiert aus Legacy Tipp::getRoundTipps und Quota::getPayoutList). + * + * Regeln: + * - Wertung: nur Spieler mit Zahlung für die Saison. + * - Gesamtpunkte: Summe der Rundenpunkte (Tipp::evaluateRound) bis zur gewählten Runde. + * - Rang: nach Gesamtpunkten, Gleichstand = geteilter Rang (1, 1, 3). + * - Tagessieg (nur abgeschlossene Runden): meiste exakte Treffer, dann höchster Joker-Wert. + * Bei mehr als 6 Tagessiegern bleiben nur die mit den meisten Rundenpunkten. + * Ohne Tagessieger wandert das Preisgeld in die nächste Runde mit Tagessieger. + * - Platzierungsgeld: nur wenn die letzte Runde der Saison angezeigt wird. + * Geteilte Ränge teilen sich das Geld; unbesetzte Plätze gehen an die Gruppe darüber. + */ class Ranking { + /** Ab mehr als so vielen Tagessiegern entscheiden die Rundenpunkte */ + const MAX_DAY_WINNERS = 6; + /** - * Berechnet die detaillierte Rangliste für eine gegebene Saison, gefiltert nach einer Runde. + * Berechnet die komplette Wertung einer Saison bis einschließlich $maxRoundId. * - * @param int $seasonId Die ID der Saison. - * @param int|null $selectedRoundId Die ID der anzuzeigenden Runde. - * @return array Ein Array mit allen benötigten Daten für die Ansicht. + * @param int $seasonId + * @param int $maxRoundId + * @return array [ + * 'max_round_id' => int, + * 'users' => user_id => Zeile aus `users` (nur bezahlte Spieler), + * 'rounds' => round_id => ['round', 'games', 'completed', 'entries' => user_id => Auswertung], + * 'ranks' => user_id => Rang (sortiert nach Rang), + * 'totals' => user_id => Gesamtpunkte, + * 'tipps' => user_id => game_id => Tipp (nur für $maxRoundId), + * 'is_final' => bool, + * 'ranking_payouts' => user_id => Betrag, + * 'payouts' => Ergebnis von Quota::computePayouts, + * ] */ - public static function getRanking($seasonId, $selectedRoundId = null) { - $db = Database::getConnection(); + public static function compute($seasonId, $maxRoundId) { + $maxRoundId = (int)$maxRoundId; + $allRounds = Round::getBySeason($seasonId); + $gamesByRound = self::loadGames($seasonId, $maxRoundId); + $tippsByRound = self::loadTipps($seasonId, $maxRoundId); + $payouts = Quota::computePayouts($seasonId); - // 1. Hole alle Benutzer, die für diese Saison bezahlt haben - $stmt_users = $db->prepare("SELECT u.id, u.name FROM users u JOIN payments p ON u.id = p.user_id WHERE p.season_id = ? AND u.deleted IS NULL AND p.paid_date IS NOT NULL"); - $stmt_users->execute([$seasonId]); - $users = $stmt_users->fetchAll(\PDO::FETCH_ASSOC); - - if (empty($users)) { - return ['ranking' => [], 'games' => [], 'allRounds' => [], 'selectedRound' => null, 'dailyWinners' => []]; + $users = []; + foreach (User::getPaid($seasonId) as $user) { + $users[(int)$user['id']] = $user; } - $user_ids = array_column($users, 'id'); + $userIds = array_keys($users); - // 2. Hole alle Runden der Saison für den Filter (nur gesperrte Runden) - $stmt_rounds = $db->prepare(" - SELECT r.* FROM rounds r - WHERE r.season_id = ? - AND EXISTS ( - SELECT 1 FROM games g - WHERE g.round_id = r.id AND DATE_SUB(g.kickoff, INTERVAL 1 MINUTE) <= NOW() - ) - ORDER BY r.id ASC - "); - $stmt_rounds->execute([$seasonId]); - $allRounds = $stmt_rounds->fetchAll(\PDO::FETCH_ASSOC); + $totals = array_fill_keys($userIds, 0); + $rounds = []; + $dayPrizePot = 0.0; - // 3. Bestimme die anzuzeigende Runde - if ($selectedRoundId) { - $selectedRound = Round::getById($selectedRoundId); - } else { - // Finde die letzte gespielte Runde - $stmt_last_round = $db->prepare("SELECT r.* FROM rounds r JOIN games g ON r.id = g.round_id WHERE r.season_id = ? AND g.score1 > -1 ORDER BY r.id DESC LIMIT 1"); - $stmt_last_round->execute([$seasonId]); - $selectedRound = $stmt_last_round->fetch(); - } - // Fallback: Erste Runde der Saison, wenn keine Runde gefunden wurde - if (!$selectedRound && !empty($allRounds)) { - $selectedRound = $allRounds[0]; - } - if (!$selectedRound) { - return ['ranking' => [], 'games' => [], 'allRounds' => $allRounds, 'selectedRound' => null, 'dailyWinners' => []]; - } - - // 4. Hole die Spiele der ausgewählten Runde - $gamesOfSelectedRound = Game::getGamesByRound($selectedRound['id']); - - // 5. Hole die beendeten Spiele für die Gesamtpunktzahl (bis zur ausgewählten Runde) - $stmt_finished_games = $db->prepare(" - SELECT g.id, g.score1, g.score2 FROM games g - JOIN rounds r ON g.round_id = r.id - WHERE r.season_id = ? AND g.score1 > -1 AND r.id <= ? - "); - $stmt_finished_games->execute([$seasonId, $selectedRound['id']]); - $finished_games_all = $stmt_finished_games->fetchAll(\PDO::FETCH_ASSOC); - $finished_games_map = array_column($finished_games_all, null, 'id'); - - // 6. Hole alle relevanten Tipps - $tipps_map = []; - if (!empty($finished_games_all)) { - $game_ids = array_column($finished_games_all, 'id'); - $game_placeholders = implode(',', array_fill(0, count($game_ids), '?')); - $user_placeholders = implode(',', array_fill(0, count($user_ids), '?')); - $stmt_tipps = $db->prepare("SELECT user_id, game_id, score1 AS tipp1, score2 AS tipp2, joker FROM tipps WHERE game_id IN ($game_placeholders) AND user_id IN ($user_placeholders)"); - $stmt_tipps->execute(array_merge($game_ids, $user_ids)); - foreach ($stmt_tipps->fetchAll(\PDO::FETCH_ASSOC) as $tipp) { - $tipps_map[$tipp['user_id']][$tipp['game_id']] = $tipp; + foreach ($allRounds as $round) { + $roundId = (int)$round['id']; + if ($roundId > $maxRoundId) { + break; + } + $games = $gamesByRound[$roundId] ?? []; + if (empty($games)) { + continue; } - } - // 7. Berechne Punkte und Details für jeden User - $rankingData = []; - $round_scores = []; - foreach ($users as $user) { - $user_id = $user['id']; - $total_score = 0; - $round_score = 0; - $tipps_details = []; - - // Gesamtpunkte über alle Spiele berechnen - foreach ($finished_games_map as $game_id => $game) { - if (isset($tipps_map[$user_id][$game_id])) { - $tipp = $tipps_map[$user_id][$game_id]; - $total_score += Tipp::getScoreLocal($game['score1'], $game['score2'], $tipp['tipp1'], $tipp['tipp2'], $tipp['joker']); + $completed = true; + foreach ($games as $game) { + if ((int)$game['score1'] < 0 || (int)$game['score2'] < 0) { + $completed = false; } } - // Details für die Spiele der ausgewählten Runde - foreach ($gamesOfSelectedRound as $game) { - $game_id = $game['id']; - $tipp = $tipps_map[$user_id][$game_id] ?? null; - $points = 0; - $color = ''; - $text = '-'; - $is_joker = false; + $entries = []; + foreach ($userIds as $userId) { + $entry = Tipp::evaluateRound($games, $tippsByRound[$roundId][$userId] ?? []); + $totals[$userId] += $entry['points']; + $entry['total'] = $totals[$userId]; + $entry['is_day_winner'] = false; + $entry['payout'] = 0.0; + $entries[$userId] = $entry; + } - if (isset($finished_games_map[$game_id]) && $tipp) { - $finished_game = $finished_games_map[$game_id]; - $points = Tipp::getScoreLocal($finished_game['score1'], $finished_game['score2'], $tipp['tipp1'], $tipp['tipp2'], $tipp['joker']); - $color = Tipp::getCol($finished_game['score1'], $finished_game['score2'], $tipp['tipp1'], $tipp['tipp2'], $tipp['joker']); - $round_score += $points; + // Tagessieg: Preisgeld sammelt sich, bis es einen Sieger gibt + $dayPrizePot += $payouts['tagessieg']; + $winners = $completed ? self::determineDayWinners($entries) : []; + if (!empty($winners)) { + $perWinner = round($dayPrizePot / count($winners), 2); + $dayPrizePot = 0.0; + foreach ($winners as $userId) { + $entries[$userId]['is_day_winner'] = true; + $entries[$userId]['payout'] = $perWinner; } - if ($tipp) { - $text = $tipp['tipp1'] . ':' . $tipp['tipp2']; - $is_joker = (bool)$tipp['joker']; - } - $tipps_details[$game_id] = compact('text', 'points', 'color', 'is_joker'); } - $rankingData[] = ['id' => $user_id, 'name' => $user['name'], 'score' => $total_score, 'round_score' => $round_score, 'tipps' => $tipps_details]; - $round_scores[$user_id] = $round_score; + + $rounds[$roundId] = [ + 'round' => $round, + 'games' => $games, + 'completed' => $completed, + 'entries' => $entries, + ]; } - // 8. Tagessieger ermitteln - $dailyWinners = []; - if (!empty($round_scores)) { - $max_round_score = max($round_scores); - if ($max_round_score > 0) { - $dailyWinners = array_keys($round_scores, $max_round_score); - } - } + $ranks = self::computeRanks($totals, $users); - // 9. Sortieren nach Gesamtpunkten - usort($rankingData, fn($a, $b) => $b['score'] <=> $a['score'] ?: strcmp($a['name'], $b['name'])); - - // 10. Rang hinzufügen - $rank = 0; - $last_score = -1; - $ranked_list = []; - foreach ($rankingData as $i => $entry) { - if ($entry['score'] !== $last_score) { - $rank = $i + 1; - $last_score = $entry['score']; - } - $entry['rank'] = $rank; - $ranked_list[] = $entry; - } + $lastRound = end($allRounds); + $isFinal = $lastRound && (int)$lastRound['id'] === $maxRoundId && isset($rounds[$maxRoundId]); return [ - 'ranking' => $ranked_list, - 'games' => $gamesOfSelectedRound, - 'allRounds' => $allRounds, - 'selectedRound' => $selectedRound, - 'dailyWinners' => $dailyWinners, + 'max_round_id' => $maxRoundId, + 'users' => $users, + 'rounds' => $rounds, + 'ranks' => $ranks, + 'totals' => $totals, + 'tipps' => $tippsByRound[$maxRoundId] ?? [], + 'is_final' => $isFinal, + 'ranking_payouts' => $isFinal ? self::computeRankingPayouts($ranks, $payouts) : [], + 'payouts' => $payouts, ]; } + + /** + * Zeilen der Ranglisten-Tabelle für die gewählte Runde, sortiert nach Rang. + * + * @param array $result Ergebnis von compute() + * @return array + */ + public static function roundTable(array $result) { + $roundId = $result['max_round_id']; + if (!isset($result['rounds'][$roundId])) { + return []; + } + $round = $result['rounds'][$roundId]; + + $rows = []; + foreach ($result['ranks'] as $userId => $rank) { + $entry = $round['entries'][$userId]; + $cells = []; + foreach ($round['games'] as $game) { + $tipp = $result['tipps'][$userId][$game['id']] ?? null; + $tipp1 = $tipp ? (int)$tipp['score1'] : -1; + $tipp2 = $tipp ? (int)$tipp['score2'] : -1; + $joker = $tipp ? (bool)$tipp['joker'] : false; + $cells[$game['id']] = [ + 'text' => ($tipp1 < 0 ? 'x' : $tipp1) . ':' . ($tipp2 < 0 ? 'x' : $tipp2), + 'joker' => $joker, + 'color' => Tipp::getCol((int)$game['score1'], (int)$game['score2'], $tipp1, $tipp2, $joker), + ]; + } + + $rows[] = [ + 'user_id' => $userId, + 'name' => $result['users'][$userId]['name'], + 'rank' => $rank, + 'total' => $entry['total'], + 'points' => $entry['points'], + 'is_day_winner' => $entry['is_day_winner'], + 'payout' => $entry['payout'], + 'ranking_payout' => $result['ranking_payouts'][$userId] ?? 0, + 'cells' => $cells, + ]; + } + return $rows; + } + + /** + * Einzelne Ausschüttungen je Spieler (Legacy Quota::getPayoutList). + * + * @param array $result Ergebnis von compute() + * @return array user_id => [['label' => ..., 'amount' => ...], ...] + */ + public static function payoutItems(array $result) { + $items = array_fill_keys(array_keys($result['users']), []); + + foreach ($result['rounds'] as $round) { + foreach ($round['entries'] as $userId => $entry) { + if ($entry['payout'] > 0) { + $items[$userId][] = [ + 'label' => $round['round']['name'] . ' (Tagessieg)', + 'amount' => $entry['payout'], + ]; + } + } + } + + foreach ($result['ranking_payouts'] as $userId => $amount) { + if ($amount > 0) { + $items[$userId][] = [ + 'label' => 'Platzierungssieg Rang ' . $result['ranks'][$userId], + 'amount' => $amount, + ]; + } + } + + return $items; + } + + /** + * Geldrangliste: Summe aller Ausschüttungen je Spieler, absteigend sortiert. + * + * @param array $result Ergebnis von compute() + * @return array Liste von ['user_id', 'name', 'amount', 'iban', 'bankname', 'blz', 'kontonr'] + */ + public static function moneyRanking(array $result) { + $list = []; + foreach (self::payoutItems($result) as $userId => $items) { + $user = $result['users'][$userId]; + $list[] = [ + 'user_id' => $userId, + 'name' => $user['name'], + 'amount' => array_sum(array_column($items, 'amount')), + 'iban' => $user['iban'], + 'bankname' => $user['bankname'], + 'blz' => $user['blz'], + 'kontonr' => $user['kontonr'], + ]; + } + + usort($list, fn($a, $b) => [$b['amount'], $a['name']] <=> [$a['amount'], $b['name']]); + return $list; + } + + /** + * Tagessieger einer Runde. + * + * @param array $entries user_id => Auswertung (Tipp::evaluateRound) + * @return array user_ids + */ + private static function determineDayWinners(array $entries) { + $best = null; + foreach ($entries as $entry) { + if ($best === null || Tipp::compareDayScore($entry, $best) < 0) { + $best = $entry; + } + } + if ($best === null || $best['exact'] === 0) { + return []; + } + + $winners = array_keys(array_filter( + $entries, + fn($entry) => Tipp::compareDayScore($entry, $best) === 0 + )); + + if (count($winners) > self::MAX_DAY_WINNERS) { + $maxPoints = max(array_map(fn($userId) => $entries[$userId]['points'], $winners)); + $winners = array_values(array_filter( + $winners, + fn($userId) => $entries[$userId]['points'] === $maxPoints + )); + } + + return $winners; + } + + /** + * Ränge nach Gesamtpunkten (geteilte Ränge bei Gleichstand), bei Gleichstand nach Name sortiert. + * + * @return array user_id => Rang, in Ranglisten-Reihenfolge + */ + private static function computeRanks(array $totals, array $users) { + $order = array_keys($totals); + usort($order, fn($a, $b) => + [$totals[$b], $users[$a]['name']] <=> [$totals[$a], $users[$b]['name']] + ); + + $ranks = []; + $previousTotal = null; + $rank = 0; + foreach ($order as $position => $userId) { + if ($totals[$userId] !== $previousTotal) { + $rank = $position + 1; + $previousTotal = $totals[$userId]; + } + $ranks[$userId] = $rank; + } + return $ranks; + } + + /** + * Verteilt das Platzierungsgeld (Plätze 1..10) auf die Spieler. + * + * @return array user_id => Betrag + */ + private static function computeRankingPayouts(array $ranks, array $payouts) { + $groups = []; + foreach ($ranks as $userId => $rank) { + if ($rank <= Quota::PLACES) { + $groups[$rank][] = $userId; + } + } + + $result = []; + for ($place = 1; $place <= Quota::PLACES; $place++) { + // Unbesetzter Platz (z.B. Platz 2 bei zwei Erstplatzierten) geht an die Gruppe darüber + $rank = $place; + while ($rank > 0 && !isset($groups[$rank])) { + $rank--; + } + if ($rank === 0) { + continue; + } + $share = $payouts['platz' . $place] / count($groups[$rank]); + foreach ($groups[$rank] as $userId) { + $result[$userId] = ($result[$userId] ?? 0) + $share; + } + } + return $result; + } + + /** + * @return array round_id => Liste der Spiele + */ + private static function loadGames($seasonId, $maxRoundId) { + $db = Database::getConnection(); + $stmt = $db->prepare( + "SELECT g.* FROM games g + JOIN rounds r ON r.id = g.round_id + WHERE r.season_id = ? AND r.id <= ? + ORDER BY g.round_id, g.kickoff, g.id" + ); + $stmt->execute([$seasonId, $maxRoundId]); + + $result = []; + foreach ($stmt->fetchAll() as $game) { + $result[(int)$game['round_id']][] = $game; + } + return $result; + } + + /** + * @return array round_id => user_id => game_id => Tipp + */ + private static function loadTipps($seasonId, $maxRoundId) { + $db = Database::getConnection(); + $stmt = $db->prepare( + "SELECT g.round_id, t.user_id, t.game_id, t.score1, t.score2, t.joker + FROM tipps t + JOIN games g ON g.id = t.game_id + JOIN rounds r ON r.id = g.round_id + WHERE r.season_id = ? AND r.id <= ?" + ); + $stmt->execute([$seasonId, $maxRoundId]); + + $result = []; + foreach ($stmt->fetchAll() as $row) { + $result[(int)$row['round_id']][(int)$row['user_id']][(int)$row['game_id']] = $row; + } + return $result; + } }