2026-10-04 23:15:54 +02:00
< ? php
// Lade den minimalistischen Autoloader
require_once __DIR__ . '/../src/autoload.php' ;
// Auth-System initialisieren
App\Core\Auth :: start ();
use App\Core\Database ;
use App\Core\Auth ;
use App\Core\Mailer ;
use App\Models\Game ;
use App\Models\Tipp ;
use App\Models\User ;
use App\Models\Round ;
use App\Models\Season ;
use App\Models\Ranking ;
use App\Models\Payment ;
use App\Models\Quota ;
use App\Models\Roundmail ;
use App\Models\Setting ;
$uri = parse_url ( $_SERVER [ 'REQUEST_URI' ], PHP_URL_PATH );
$page = $_GET [ 'page' ] ? ? null ;
// Home-Seite erkennen
if (( $uri === '/' || $uri === '/index.php' ) && $page === null ) {
$page = 'home' ;
}
// Routing basierend auf Query-Parametern
if ( $page === 'reminder' ) {
// Von außen per Cron aufgerufen, ohne Login; abgesichert über REMINDER_TOKEN
header ( 'Content-Type: text/plain; charset=UTF-8' );
$expectedToken = ( string ) getenv ( 'REMINDER_TOKEN' );
$token = ( string )( $_SERVER [ 'HTTP_X_REMINDER_TOKEN' ] ? ? $_GET [ 'token' ] ? ? '' );
if ( $expectedToken === '' ) {
http_response_code ( 503 );
echo " Erinnerungen sind deaktiviert (REMINDER_TOKEN nicht gesetzt). \n " ;
exit ;
}
if ( ! hash_equals ( $expectedToken , $token )) {
http_response_code ( 403 );
echo " Ungültiges Token. \n " ;
exit ;
}
try {
$appUrl = getenv ( 'APP_URL' ) ? : (( ! empty ( $_SERVER [ 'HTTPS' ]) ? 'https' : 'http' ) . '://' . ( $_SERVER [ 'HTTP_HOST' ] ? ? 'localhost' ));
// Aufräumen läuft bei jedem Aufruf, auch wenn keine Erinnerung fällig ist
echo Roundmail :: deleteOldReminders () . " alte Erinnerungen gelöscht. \n " ;
echo Roundmail :: sendReminder ( $appUrl ) . " \n " ;
} catch ( \Throwable $e ) {
http_response_code ( 500 );
echo " Fehler: " . $e -> getMessage () . " \n " ;
}
exit ;
} elseif ( $page === 'login' ) {
// Wenn bereits eingeloggt, zur Rangliste weiterleiten
if ( Auth :: check ()) {
header ( 'Location: /index.php?page=ranking' );
exit ;
}
if ( $_SERVER [ 'REQUEST_METHOD' ] === 'POST' ) {
$firstname = $_POST [ 'firstname' ] ? ? '' ;
$lastname = $_POST [ 'lastname' ] ? ? '' ;
$password = $_POST [ 'password' ] ? ? '' ;
if ( Auth :: login ( $firstname , $lastname , $password )) {
header ( 'Location: /index.php?page=ranking' );
exit ;
} else {
$error = 'Ungültige Anmeldedaten.' ;
require __DIR__ . '/../src/Views/login.php' ;
}
} else {
require __DIR__ . '/../src/Views/login.php' ;
}
} elseif ( $page === 'register' ) {
if ( Auth :: check ()) {
header ( 'Location: /index.php?page=ranking' );
exit ;
}
if ( ! Setting :: isRegistrationOpen ()) {
http_response_code ( 403 );
$registrationClosed = true ;
require __DIR__ . '/../src/Views/register.php' ;
exit ;
}
if ( $_SERVER [ 'REQUEST_METHOD' ] === 'POST' ) {
$data = [
'firstname' => $_POST [ 'firstname' ] ? ? '' ,
'lastname' => $_POST [ 'lastname' ] ? ? '' ,
'email' => $_POST [ 'email' ] ? ? '' ,
'password' => $_POST [ 'password' ] ? ? '' ,
];
$password_confirm = $_POST [ 'password_confirm' ] ? ? '' ;
$error = null ;
if ( empty ( $data [ 'firstname' ]) || empty ( $data [ 'lastname' ]) || empty ( $data [ 'email' ]) || empty ( $data [ 'password' ])) {
$error = 'Alle Felder sind erforderlich.' ;
} elseif ( $data [ 'password' ] !== $password_confirm ) {
$error = 'Die Passwörter stimmen nicht überein.' ;
} elseif ( User :: findByEmail ( $data [ 'email' ])) {
$error = 'Diese E-Mail-Adresse ist bereits registriert.' ;
} else {
try {
if ( User :: create ( $data )) {
// Automatically log in the new user
if ( Auth :: login ( $data [ 'firstname' ], $data [ 'lastname' ], $data [ 'password' ])) {
header ( 'Location: /index.php?page=ranking' );
exit ;
} else {
// This should not happen if creation was successful
$error = 'Anmeldung nach Registrierung fehlgeschlagen. Bitte versuchen Sie, sich manuell anzumelden.' ;
require __DIR__ . '/../src/Views/login.php' ;
exit ;
}
} else {
$error = 'Ein Fehler ist bei der Registrierung aufgetreten.' ;
}
} catch ( \Throwable $e ) {
// Could be a unique constraint violation from DB
$error = 'Ein Datenbankfehler ist aufgetreten. Die E-Mail könnte bereits vergeben sein.' ;
}
}
// Show form again with error
require __DIR__ . '/../src/Views/register.php' ;
} else {
// Show registration form
require __DIR__ . '/../src/Views/register.php' ;
}
} elseif ( $page === 'logout' ) {
Auth :: logout ();
header ( 'Location: /index.php?page=login' );
exit ;
} elseif ( in_array ( $page , [ 'tipps' , 'tipp_round' , 'tipp_game' ], true )) {
// Tipps abgeben (Legacy TippsController: index, edit4/store4, edit/store)
Auth :: requireLogin ();
$user = Auth :: user ();
$activeSeason = Season :: getCurrent ();
if ( ! $activeSeason ) {
header ( 'Location: /' );
exit ;
}
if ( ! User :: isPaid ( $user [ 'id' ], $activeSeason [ 'id' ])) {
require __DIR__ . '/../src/Views/tipps/no_payment.php' ;
exit ;
}
// Nach dem Speichern zur ersten tippbaren Runde springen (wie im Legacy)
$tippsUrl = function () use ( $activeSeason ) {
$round = Round :: getFirstTippable ( $activeSeason [ 'id' ]);
return '/index.php?page=tipps' . ( $round ? '#round-' . $round [ 'id' ] : '' );
};
if ( $page === 'tipps' ) {
$rounds = [];
$firstTippableRoundId = null ;
foreach ( Round :: getBySeason ( $activeSeason [ 'id' ]) as $round ) {
$round [ 'games' ] = Game :: getGamesByRound ( $round [ 'id' ]);
$round [ 'tipps' ] = Tipp :: findByUserAndRound ( $user [ 'id' ], $round [ 'id' ]);
$round [ 'locked' ] = Round :: isLocked ( $round [ 'games' ]);
if ( $firstTippableRoundId === null && ! $round [ 'locked' ]) {
$firstTippableRoundId = ( int ) $round [ 'id' ];
}
$round [ 'lock_time' ] = Round :: getLockTime ( $round [ 'games' ]);
$round [ 'joker_usage' ] = Tipp :: formatJokerUsage (
Tipp :: getJokerUsage ( $user [ 'id' ], $activeSeason [ 'id' ], null , $round [ 'id' ])
);
$rounds [] = $round ;
}
$maxIdenticalJokertipps = ( int ) $activeSeason [ 'max_identical_jokertipps' ];
require __DIR__ . '/../src/Views/tipps/index.php' ;
exit ;
}
if ( $page === 'tipp_round' ) {
$round = Round :: getById (( int )( $_GET [ 'id' ] ? ? 0 ));
if ( ! $round || ( int ) $round [ 'season_id' ] !== ( int ) $activeSeason [ 'id' ]) {
header ( 'Location: ' . $tippsUrl ());
exit ;
}
$games = Game :: getGamesByRound ( $round [ 'id' ]);
$error = null ;
if ( $_SERVER [ 'REQUEST_METHOD' ] === 'POST' ) {
$jokerGameId = isset ( $_POST [ 'joker' ]) && $_POST [ 'joker' ] !== '' ? ( int ) $_POST [ 'joker' ] : null ;
$error = Tipp :: saveRound ( $user [ 'id' ], $round [ 'id' ], $_POST [ 'scores' ] ? ? [], $jokerGameId );
if ( $error === null ) {
header ( 'Location: ' . $tippsUrl ());
exit ;
}
$formScores = $_POST [ 'scores' ] ? ? [];
$formJoker = $jokerGameId ;
} else {
$tipps = Tipp :: findByUserAndRound ( $user [ 'id' ], $round [ 'id' ]);
$formScores = [];
$formJoker = null ;
foreach ( $games as $game ) {
$tipp = $tipps [ $game [ 'id' ]] ? ? null ;
$formScores [ $game [ 'id' ]] = [
'score1' => $tipp && ( int ) $tipp [ 'score1' ] >= 0 ? $tipp [ 'score1' ] : '' ,
'score2' => $tipp && ( int ) $tipp [ 'score2' ] >= 0 ? $tipp [ 'score2' ] : '' ,
];
if ( $tipp && $tipp [ 'joker' ]) {
$formJoker = ( int ) $game [ 'id' ];
}
}
}
$locked = Round :: isLocked ( $games );
require __DIR__ . '/../src/Views/tipps/round.php' ;
exit ;
}
// tipp_game: einzelnes Spiel tippen
$game = Game :: getById (( int )( $_GET [ 'id' ] ? ? 0 ));
$round = $game ? Round :: getById ( $game [ 'round_id' ]) : null ;
if ( ! $round || ( int ) $round [ 'season_id' ] !== ( int ) $activeSeason [ 'id' ]) {
header ( 'Location: ' . $tippsUrl ());
exit ;
}
$error = null ;
if ( $_SERVER [ 'REQUEST_METHOD' ] === 'POST' ) {
$error = Tipp :: saveSingle ( $user [ 'id' ], $game [ 'id' ], $_POST [ 'score1' ] ? ? '' , $_POST [ 'score2' ] ? ? '' , isset ( $_POST [ 'joker' ]));
if ( $error === null ) {
header ( 'Location: ' . $tippsUrl ());
exit ;
}
$formTipp = [ 'score1' => $_POST [ 'score1' ] ? ? '' , 'score2' => $_POST [ 'score2' ] ? ? '' , 'joker' => isset ( $_POST [ 'joker' ])];
} else {
$tipp = Tipp :: findByUserAndRound ( $user [ 'id' ], $round [ 'id' ])[ $game [ 'id' ]] ? ? null ;
$formTipp = [
'score1' => $tipp && ( int ) $tipp [ 'score1' ] >= 0 ? $tipp [ 'score1' ] : '' ,
'score2' => $tipp && ( int ) $tipp [ 'score2' ] >= 0 ? $tipp [ 'score2' ] : '' ,
'joker' => $tipp && $tipp [ 'joker' ],
];
}
$locked = Round :: isLocked ( Game :: getGamesByRound ( $round [ 'id' ]));
require __DIR__ . '/../src/Views/tipps/game.php' ;
2026-10-04 23:31:47 +02:00
} elseif ( $page === 'guide' ) {
// Info -> Anleitung: Regeln mit den Werten der aktiven Saison
Auth :: requireLogin ();
$currentSeason = Season :: getCurrent ();
$payouts = $currentSeason ? Quota :: computePayouts ( $currentSeason [ 'id' ]) : null ;
$maxIdenticalJokertipps = ( int )( $currentSeason [ 'max_identical_jokertipps' ] ? ? Season :: DEFAULT_MAX_IDENTICAL_JOKERTIPPS );
require __DIR__ . '/../src/Views/info/guide.php' ;
2026-10-04 23:15:54 +02:00
} elseif ( $page === 'info_quotas' ) {
// Info -> Quoten (Legacy UsersController::show_payouts)
Auth :: requireLogin ();
$currentSeason = Season :: getCurrent ();
$payouts = $currentSeason ? Quota :: computePayouts ( $currentSeason [ 'id' ]) : null ;
$activeUserCount = $currentSeason ? count ( User :: getPaid ( $currentSeason [ 'id' ])) : 0 ;
$stake = $currentSeason ? ( Quota :: getMapBySeason ( $currentSeason [ 'id' ])[ 'einsatz' ] ? ? 0 ) : 0 ;
require __DIR__ . '/../src/Views/info/quotas.php' ;
} elseif ( $page === 'money_ranking' ) {
// Info -> Geldrangliste (Legacy UsersController::money_ranking / money_ranking_detail)
Auth :: requireLogin ();
$user = Auth :: user ();
$currentSeason = Season :: getCurrent ();
if ( ! $currentSeason ) {
header ( 'Location: /' );
exit ;
}
if ( ! $user [ 'admin' ] && ! User :: isPaid ( $user [ 'id' ], $currentSeason [ 'id' ])) {
require __DIR__ . '/../src/Views/tipps/no_payment.php' ;
exit ;
}
[ 'result' => $result , 'season_start' => $seasonStart ] = Ranking :: computeForMoneyRanking ( $currentSeason [ 'id' ]);
if ( ! $result ) {
require __DIR__ . '/../src/Views/info/no_ranking.php' ;
exit ;
}
if ( isset ( $_GET [ 'user_id' ])) {
$detailUserId = ( int ) $_GET [ 'user_id' ];
if ( ! isset ( $result [ 'users' ][ $detailUserId ])) {
header ( 'Location: /index.php?page=money_ranking' );
exit ;
}
$detailUser = $result [ 'users' ][ $detailUserId ];
$payoutItems = Ranking :: payoutItems ( $result )[ $detailUserId ];
require __DIR__ . '/../src/Views/info/money_ranking_detail.php' ;
} else {
$moneyRanking = Ranking :: moneyRanking ( $result );
require __DIR__ . '/../src/Views/info/money_ranking.php' ;
}
} elseif ( $page === 'admin_accounts' ) {
// Kontoliste mit IBAN (Legacy UsersController::money_ranking_with_iban)
Auth :: requireLogin ();
Auth :: requireAdmin ();
$user = Auth :: user ();
$currentSeason = Season :: getCurrent ();
$result = null ;
$seasonStart = null ;
if ( $currentSeason ) {
[ 'result' => $result , 'season_start' => $seasonStart ] = Ranking :: computeForMoneyRanking ( $currentSeason [ 'id' ]);
}
$moneyRanking = $result ? Ranking :: moneyRanking ( $result ) : [];
require __DIR__ . '/../src/Views/admin/accounts.php' ;
} elseif ( $page === 'settings' ) {
// Eigene Spielerdaten (Legacy UsersController::useredit / storeUserEdit)
Auth :: requireLogin ();
$user = Auth :: user ();
$error = null ;
$message = $_SESSION [ 'settings_message' ] ? ? null ;
unset ( $_SESSION [ 'settings_message' ]);
if ( $_SERVER [ 'REQUEST_METHOD' ] === 'POST' ) {
$data = [
'email' => trim ( $_POST [ 'email' ] ? ? '' ),
'gets_reminders' => isset ( $_POST [ 'gets_reminders' ]),
];
foreach ( User :: BANK_FIELDS as $field ) {
$data [ $field ] = $_POST [ $field ] ? ? '' ;
}
$data [ 'iban' ] = strtoupper ( str_replace ( ' ' , '' , $data [ 'iban' ]));
if ( ! filter_var ( $data [ 'email' ], FILTER_VALIDATE_EMAIL )) {
$error = 'Bitte eine gültige E-Mail-Adresse eintragen.' ;
} elseif ( User :: emailExists ( $data [ 'email' ], $user [ 'id' ])) {
$error = 'Diese E-Mail-Adresse wird bereits von einem anderen Spieler verwendet.' ;
} else {
User :: updateProfile ( $user [ 'id' ], $data );
$_SESSION [ 'settings_message' ] = 'Deine Daten wurden gespeichert.' ;
header ( 'Location: /index.php?page=settings' );
exit ;
}
// Eingaben bei Fehler erhalten
$user = array_merge ( $user , $data );
}
require __DIR__ . '/../src/Views/settings.php' ;
} elseif ( $page === 'admin' ) {
// Die Admin-Punkte stehen im Popup-Menü der Navigation; hier wird nur noch
// der Registrierungsschalter aus dem Menü verarbeitet.
Auth :: requireLogin ();
Auth :: requireAdmin ();
if ( $_SERVER [ 'REQUEST_METHOD' ] === 'POST' && ( $_POST [ 'action' ] ? ? '' ) === 'set_registration' ) {
Setting :: setRegistrationOpen (( $_POST [ 'registration_open' ] ? ? '' ) === '1' );
// Zurück zur Seite, auf der das Menü benutzt wurde (nur lokale Pfade)
$return = ( string )( $_POST [ 'return' ] ? ? '' );
$isLocal = str_starts_with ( $return , '/' ) && ! str_starts_with ( $return , '//' );
header ( 'Location: ' . ( $isLocal ? $return : '/index.php?page=admin_users' ));
exit ;
}
header ( 'Location: /index.php?page=admin_users' );
exit ;
} elseif ( $page === 'admin_seasons' ) {
Auth :: requireLogin ();
Auth :: requireAdmin ();
$message = null ;
$error = null ;
if ( $_SERVER [ 'REQUEST_METHOD' ] === 'POST' ) {
$action = $_POST [ 'action' ] ? ? '' ;
$seasonId = $_POST [ 'id' ] ? ? null ;
$redirect = '/index.php?page=admin_seasons' ;
try {
if ( $action === 'create' || $action === 'update' ) {
$data = [
'name' => trim ( $_POST [ 'name' ] ? ? '' ),
'rounds' => $_POST [ 'rounds' ] ? ? '' ,
'max_identical_jokertipps' => $_POST [ 'max_identical_jokertipps' ] ? ? '' ,
];
if ( $data [ 'name' ] === '' || ! ctype_digit (( string ) $data [ 'rounds' ]) || ( int ) $data [ 'rounds' ] < 1
|| ! ctype_digit (( string ) $data [ 'max_identical_jokertipps' ])) {
throw new \Exception ( 'Name, Runden und maximale Anzahl gleicher Joker sind erforderlich.' );
}
$quotasToSave = [];
foreach ( Quota :: editableNames () as $name ) {
$quotasToSave [ $name ] = str_replace ( ',' , '.' , trim ( $_POST [ 'quotas' ][ $name ] ? ? '' ));
}
$quotaError = Quota :: validate ( $quotasToSave );
if ( $quotaError ) {
throw new \Exception ( $quotaError );
}
if ( $action === 'create' ) {
$newSeasonId = Season :: create ( $data );
if ( ! $newSeasonId ) {
throw new \Exception ( " Saison konnte nicht erstellt werden. " );
}
Quota :: saveForSeason ( $newSeasonId , $quotasToSave );
Season :: setCurrent ( $newSeasonId );
$_SESSION [ 'admin_message' ] = " Saison erfolgreich erstellt und als aktiv gesetzt. " ;
} elseif ( $seasonId ) {
Season :: update ( $seasonId , $data );
Quota :: saveForSeason ( $seasonId , $quotasToSave );
$_SESSION [ 'admin_message' ] = " Saison erfolgreich aktualisiert. " ;
$redirect = '/index.php?page=admin_seasons&edit_id=' . ( int ) $seasonId ;
}
} elseif ( $action === 'set_current' && $seasonId ) {
Season :: setCurrent ( $seasonId );
$_SESSION [ 'admin_message' ] = " Aktive Saison wurde geändert. " ;
} elseif ( $action === 'delete' && $seasonId ) {
Season :: delete ( $seasonId );
$_SESSION [ 'admin_message' ] = " Saison wurde gelöscht. " ;
}
} catch ( \Throwable $e ) {
$_SESSION [ 'admin_error' ] = " Fehler: " . $e -> getMessage ();
$_SESSION [ 'admin_form' ] = $_POST ;
if ( $action === 'update' && $seasonId ) {
$redirect = '/index.php?page=admin_seasons&edit_id=' . ( int ) $seasonId ;
}
}
header ( 'Location: ' . $redirect );
exit ;
}
if ( isset ( $_SESSION [ 'admin_message' ])) {
$message = $_SESSION [ 'admin_message' ];
unset ( $_SESSION [ 'admin_message' ]);
}
if ( isset ( $_SESSION [ 'admin_error' ])) {
$error = $_SESSION [ 'admin_error' ];
unset ( $_SESSION [ 'admin_error' ]);
}
$failedForm = $_SESSION [ 'admin_form' ] ? ? null ;
unset ( $_SESSION [ 'admin_form' ]);
$seasons = Season :: getAll ();
$currentSeason = Season :: getCurrent ();
$editSeason = isset ( $_GET [ 'edit_id' ]) ? Season :: findById (( int ) $_GET [ 'edit_id' ]) : null ;
$payouts = null ;
// Formularwerte: Bearbeiten = Werte der Saison, Neu = Werte der aktiven Saison bzw. Legacy-Defaults
$template = $editSeason ? : $currentSeason ;
$formValues = [
'name' => $editSeason [ 'name' ] ? ? '' ,
'rounds' => $template [ 'rounds' ] ? ? 48 ,
'max_identical_jokertipps' => $template [ 'max_identical_jokertipps' ] ? ? Season :: DEFAULT_MAX_IDENTICAL_JOKERTIPPS ,
'quotas' => array_merge ( Quota :: defaults (), $template ? Quota :: getMapBySeason ( $template [ 'id' ]) : []),
];
if ( $editSeason ) {
$payouts = Quota :: computePayouts ( $editSeason [ 'id' ]);
$paidUserCount = count ( User :: getPaid ( $editSeason [ 'id' ]));
$roundCount = count ( Round :: getBySeason ( $editSeason [ 'id' ]));
}
if ( $failedForm ) {
$formValues = array_merge ( $formValues , array_intersect_key ( $failedForm , $formValues ));
}
require __DIR__ . '/../src/Views/admin/seasons.php' ;
} elseif ( $page === 'admin_rounds' ) {
Auth :: requireLogin ();
Auth :: requireAdmin ();
$currentSeason = Season :: getCurrent ();
$seasonId = ( int )( $_GET [ 'season_id' ] ? ? ( $currentSeason [ 'id' ] ? ? 0 ));
if ( $_SERVER [ 'REQUEST_METHOD' ] === 'POST' ) {
$roundId = ( int )( $_POST [ 'round_id' ] ? ? 0 );
$redirect = '/index.php?page=admin_rounds&season_id=' . $seasonId . '#round-' . $roundId ;
try {
$round = Round :: getById ( $roundId );
if ( ! $round ) {
throw new \Exception ( 'Runde nicht gefunden.' );
}
$name = trim ( $_POST [ 'name' ] ? ? '' );
if ( $name === '' ) {
throw new \Exception ( 'Der Rundenname darf nicht leer sein.' );
}
// Erst alle Spiele prüfen, dann speichern
$gamesToSave = [];
foreach ( $_POST [ 'games' ] ? ? [] as $gameId => $input ) {
$game = Game :: getById (( int ) $gameId );
if ( ! $game || ( int ) $game [ 'round_id' ] !== $roundId ) {
throw new \Exception ( 'Spiel gehört nicht zu dieser Runde.' );
}
$label = $game [ 'team1' ] . ' : ' . $game [ 'team2' ];
$team1 = trim ( $input [ 'team1' ] ? ? '' );
$team2 = trim ( $input [ 'team2' ] ? ? '' );
if ( $team1 === '' || $team2 === '' ) {
throw new \Exception ( " Mannschaften fehlen bei \" $label\ " . " );
}
$kickoff = \DateTime :: createFromFormat ( 'Y-m-d\\TH:i' , $input [ 'kickoff' ] ? ? '' )
? : \DateTime :: createFromFormat ( 'Y-m-d\\TH:i:s' , $input [ 'kickoff' ] ? ? '' );
if ( ! $kickoff ) {
throw new \Exception ( " Ungültiger Anstoß bei \" $label\ " . " );
}
$score1 = trim ( $input [ 'score1' ] ? ? '' );
$score2 = trim ( $input [ 'score2' ] ? ? '' );
if ( $score1 === '' && $score2 === '' ) {
$score1 = $score2 = - 1 ;
} elseif ( ctype_digit ( $score1 ) && ctype_digit ( $score2 )) {
$score1 = ( int ) $score1 ;
$score2 = ( int ) $score2 ;
} else {
throw new \Exception ( " Ergebnis bei \" $label\ " muss aus zwei Zahlen bestehen oder ganz leer sein . " );
}
$gamesToSave [( int ) $gameId ] = [
'team1' => $team1 ,
'team2' => $team2 ,
'kickoff' => $kickoff -> format ( 'Y-m-d H:i:00' ),
'score1' => $score1 ,
'score2' => $score2 ,
];
}
$db = Database :: getConnection ();
$db -> beginTransaction ();
try {
Round :: updateName ( $roundId , $name );
Round :: updateReport ( $roundId , $_POST [ 'report' ] ? ? '' );
foreach ( $gamesToSave as $gameId => $data ) {
Game :: update ( $gameId , $data );
}
$db -> commit ();
} catch ( \Throwable $e ) {
$db -> rollBack ();
throw $e ;
}
$_SESSION [ 'admin_message' ] = " \" $name\ " wurde gespeichert . " ;
} catch ( \Throwable $e ) {
$_SESSION [ 'admin_error' ] = " Fehler: " . $e -> getMessage ();
$_SESSION [ 'admin_form' ] = $_POST ;
}
header ( 'Location: ' . $redirect );
exit ;
}
$message = $_SESSION [ 'admin_message' ] ? ? null ;
$error = $_SESSION [ 'admin_error' ] ? ? null ;
$failedForm = $_SESSION [ 'admin_form' ] ? ? null ;
unset ( $_SESSION [ 'admin_message' ], $_SESSION [ 'admin_error' ], $_SESSION [ 'admin_form' ]);
$seasons = Season :: getAll ();
$season = Season :: findById ( $seasonId );
$rounds = [];
$firstIncompleteRoundId = null ;
if ( $season ) {
foreach ( Round :: getBySeason ( $seasonId ) as $round ) {
$round [ 'games' ] = Game :: getGamesByRound ( $round [ 'id' ]);
$round [ 'completed' ] = Round :: isCompleted ( $round [ 'games' ]);
$round [ 'lock_time' ] = Round :: getLockTime ( $round [ 'games' ]);
if ( $firstIncompleteRoundId === null && ! $round [ 'completed' ]) {
$firstIncompleteRoundId = ( int ) $round [ 'id' ];
}
$rounds [] = $round ;
}
}
require __DIR__ . '/../src/Views/admin/rounds.php' ;
} elseif ( $page === 'admin_roundmails' ) {
Auth :: requireLogin ();
Auth :: requireAdmin ();
if ( $_SERVER [ 'REQUEST_METHOD' ] === 'POST' ) {
$redirect = '/index.php?page=admin_roundmails' ;
try {
$topic = trim ( $_POST [ 'topic' ] ? ? '' );
$text = trim ( $_POST [ 'message' ] ? ? '' );
$recipients = Roundmail :: parseRecipients ( $_POST [ 'recipients' ] ? ? '' );
if ( $topic === '' || $text === '' ) {
throw new \Exception ( 'Thema und Nachricht sind erforderlich.' );
}
if ( ! empty ( $recipients [ 'invalid' ])) {
throw new \Exception ( 'Ungültige E-Mail-Adressen: ' . implode ( ', ' , $recipients [ 'invalid' ]));
}
if ( empty ( $recipients [ 'valid' ])) {
throw new \Exception ( 'Keine Empfänger angegeben.' );
}
$sender = Auth :: user ();
$html = Roundmail :: textToHtml ( $text );
$failed = Mailer :: send ( $recipients [ 'valid' ], $topic , $html , $sender [ 'email' ] ? ? null );
$sent = array_values ( array_diff ( $recipients [ 'valid' ], $failed ));
if ( ! empty ( $sent )) {
Roundmail :: create (( int ) $sender [ 'id' ], $sent , $topic , $html );
}
$_SESSION [ 'admin_message' ] = 'Mail an ' . count ( $sent ) . ' Empfänger versendet.' ;
if ( ! empty ( $failed )) {
$_SESSION [ 'admin_error' ] = 'Nicht zustellbar: ' . implode ( ', ' , $failed );
}
} catch ( \Throwable $e ) {
$_SESSION [ 'admin_error' ] = 'Fehler: ' . $e -> getMessage ();
$_SESSION [ 'admin_form' ] = $_POST ;
$redirect = '/index.php?page=admin_roundmails&new=1' ;
}
header ( 'Location: ' . $redirect );
exit ;
}
$message = $_SESSION [ 'admin_message' ] ? ? null ;
$error = $_SESSION [ 'admin_error' ] ? ? null ;
$failedForm = $_SESSION [ 'admin_form' ] ? ? null ;
unset ( $_SESSION [ 'admin_message' ], $_SESSION [ 'admin_error' ], $_SESSION [ 'admin_form' ]);
$viewMail = isset ( $_GET [ 'id' ]) ? Roundmail :: findById (( int ) $_GET [ 'id' ]) : null ;
$compose = isset ( $_GET [ 'new' ]);
if ( $compose ) {
$currentSeason = Season :: getCurrent ();
$tippableRound = $currentSeason ? Round :: getFirstTippable ( $currentSeason [ 'id' ]) : null ;
$recipientGroups = $currentSeason ? Roundmail :: recipientGroups ( $currentSeason [ 'id' ], $tippableRound ) : [];
$baseUrl = rtrim ( getenv ( 'APP_URL' ) ? : (( ! empty ( $_SERVER [ 'HTTPS' ]) ? 'https' : 'http' ) . '://' . ( $_SERVER [ 'HTTP_HOST' ] ? ? 'localhost' )), '/' );
$tippLink = $baseUrl . '/' ;
$mailConfigured = ( bool ) getenv ( 'SMTP_HOST' );
} elseif ( ! $viewMail ) {
$perPage = 20 ;
$totalMails = Roundmail :: count ();
$totalPages = max ( 1 , ( int ) ceil ( $totalMails / $perPage ));
$currentPage = min ( max ( 1 , ( int )( $_GET [ 'p' ] ? ? 1 )), $totalPages );
$mails = Roundmail :: getPage ( $perPage , ( $currentPage - 1 ) * $perPage );
}
require __DIR__ . '/../src/Views/admin/roundmails.php' ;
} elseif ( $page === 'admin_users' ) {
Auth :: requireLogin ();
Auth :: requireAdmin ();
$currentSeason = Season :: getCurrent ();
$message = null ;
$error = null ;
if ( $_SERVER [ 'REQUEST_METHOD' ] === 'POST' ) {
$action = $_POST [ 'action' ] ? ? '' ;
$userId = $_POST [ 'id' ] ? ? null ;
$redirect = '/index.php?page=admin_users' ;
try {
if ( $action === 'create' || $action === 'update' ) {
$data = [
'firstname' => $_POST [ 'firstname' ],
'lastname' => $_POST [ 'lastname' ],
'email' => $_POST [ 'email' ],
'password' => $_POST [ 'password' ],
'admin' => isset ( $_POST [ 'admin' ]) ? 1 : 0 ,
];
if ( $action === 'create' ) {
if ( empty ( $data [ 'password' ])) {
throw new \Exception ( 'Passwort ist erforderlich.' );
}
User :: create ( $data );
$_SESSION [ 'admin_message' ] = " Benutzer erfolgreich erstellt. " ;
} elseif ( $userId ) {
User :: update ( $userId , $data );
if ( $currentSeason ) {
Payment :: setPaidStatus ( $userId , $currentSeason [ 'id' ], isset ( $_POST [ 'has_paid' ]));
}
$_SESSION [ 'admin_message' ] = " Benutzer erfolgreich aktualisiert. " ;
}
} elseif ( $action === 'delete' && $userId ) {
User :: delete ( $userId );
$_SESSION [ 'admin_message' ] = " Benutzer erfolgreich gelöscht. " ;
}
} catch ( \Throwable $e ) {
$_SESSION [ 'admin_error' ] = " Fehler: " . $e -> getMessage ();
if ( $action === 'update' && $userId ) {
$redirect = '/index.php?page=admin_users&edit_id=' . $userId ;
}
}
header ( 'Location: ' . $redirect );
exit ;
}
if ( isset ( $_SESSION [ 'admin_message' ])) {
$message = $_SESSION [ 'admin_message' ];
unset ( $_SESSION [ 'admin_message' ]);
}
if ( isset ( $_SESSION [ 'admin_error' ])) {
$error = $_SESSION [ 'admin_error' ];
unset ( $_SESSION [ 'admin_error' ]);
}
$users = User :: getAll ();
$payments = [];
if ( $currentSeason ) {
$payments = Payment :: getPaymentsBySeason ( $currentSeason [ 'id' ]);
}
$editUser = null ;
if ( isset ( $_GET [ 'edit_id' ])) {
$editUser = User :: findById (( int ) $_GET [ 'edit_id' ]);
}
require __DIR__ . '/../src/Views/admin/users.php' ;
} elseif ( $page === 'round' && isset ( $_GET [ 'id' ])) {
Auth :: requireLogin ();
try {
$roundId = ( int ) $_GET [ 'id' ];
$selectedRound = Round :: getById ( $roundId );
if ( ! $selectedRound ) {
http_response_code ( 404 );
echo " 404 Not Found: Runde nicht gefunden. " ;
exit ;
}
// Alle Runden der Saison holen
$allRoundsInSeason = Round :: getBySeason ( $selectedRound [ 'season_id' ]);
$roundsToShow = [];
$all_game_ids = [];
foreach ( $allRoundsInSeason as $round ) {
if ( $round [ 'id' ] <= $selectedRound [ 'id' ]) {
$gamesOfRound = Game :: getGamesByRound ( $round [ 'id' ]);
$round [ 'games' ] = $gamesOfRound ;
$roundsToShow [] = $round ;
if ( ! empty ( $gamesOfRound )) {
$all_game_ids = array_merge ( $all_game_ids , array_column ( $gamesOfRound , 'id' ));
}
}
}
// Hole alle zahlenden User der Saison
$db = Database :: getConnection ();
$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 ORDER BY u.name ASC " );
$stmt_users -> execute ([ $selectedRound [ 'season_id' ]]);
$users = $stmt_users -> fetchAll ( \PDO :: FETCH_ASSOC );
// Hole alle relevanten Tipps
$tipps_map = [];
if ( ! empty ( $all_game_ids ) && ! empty ( $users )) {
$user_ids = array_column ( $users , 'id' );
$game_placeholders = implode ( ',' , array_fill ( 0 , count ( $all_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 ( $all_game_ids , $user_ids ));
foreach ( $stmt_tipps -> fetchAll ( \PDO :: FETCH_ASSOC ) as $tipp ) {
$tipps_map [ $tipp [ 'user_id' ]][ $tipp [ 'game_id' ]] = $tipp ;
}
}
// Lade das View-Template für die Rundenansicht
require __DIR__ . '/../src/Views/round.php' ;
} catch ( Throwable $e ) {
http_response_code ( 500 );
echo " <p style='color:red;'>Fehler: " . htmlspecialchars ( $e -> getMessage ()) . " </p> " ;
}
} elseif ( $page === 'ranking' ) {
Auth :: requireLogin ();
try {
$currentSeason = Season :: getCurrent ();
if ( ! $currentSeason ) {
throw new \Exception ( " Keine aktuelle Saison gefunden. " );
}
// Auswählbar sind nur gesperrte Runden (erstes Spiel angepfiffen),
// Standard ist die letzte Runde mit Ergebnis
$allRounds = [];
$defaultRound = null ;
foreach ( Round :: getBySeason ( $currentSeason [ 'id' ]) as $round ) {
$roundGames = Game :: getGamesByRound ( $round [ 'id' ]);
if ( empty ( $roundGames ) || ! Game :: isLocked ( $roundGames [ 0 ][ 'kickoff' ])) {
continue ;
}
$allRounds [] = $round ;
foreach ( $roundGames as $game ) {
if (( int ) $game [ 'score1' ] > - 1 ) {
$defaultRound = $round ;
break ;
}
}
}
$selectedRound = $defaultRound ? ? ( $allRounds [ 0 ] ? ? null );
if ( isset ( $_GET [ 'round_id' ])) {
foreach ( $allRounds as $round ) {
if (( int ) $round [ 'id' ] === ( int ) $_GET [ 'round_id' ]) {
$selectedRound = $round ;
}
}
}
$ranking = [];
$games = [];
if ( $selectedRound ) {
$result = Ranking :: compute ( $currentSeason [ 'id' ], $selectedRound [ 'id' ]);
$ranking = Ranking :: roundTable ( $result );
$games = $result [ 'rounds' ][ $selectedRound [ 'id' ]][ 'games' ] ? ? [];
}
require __DIR__ . '/../src/Views/ranking.php' ;
} catch ( Throwable $e ) {
http_response_code ( 500 );
echo " <p style='color:red;'>Fehler: " . htmlspecialchars ( $e -> getMessage ()) . " </p> " ;
}
} elseif ( $page === 'home' ) {
Auth :: requireLogin ();
try {
$db = Database :: getConnection ();
$userCount = $db -> query ( " SELECT COUNT(*) FROM users " ) -> fetchColumn ();
$currentSeason = Season :: getCurrent ();
if ( $currentSeason ) {
$rounds = Round :: getBySeason ( $currentSeason [ 'id' ]);
} else {
$rounds = [];
}
// Testdaten für die Startseite
$scoreTest = Tipp :: getScoreLocal ( 2 , 1 , 2 , 1 , true );
$lastRoundId = $db -> query ( " SELECT round_id FROM games WHERE score1 > -1 ORDER BY id DESC LIMIT 1 " ) -> fetchColumn ();
if ( $lastRoundId ) {
$games = Game :: getGamesByRound ( $lastRoundId );
} else {
$games = [];
}
require __DIR__ . '/../src/Views/home.php' ;
} catch ( Throwable $e ) {
echo " <p style='color:red;'>Fehler: " . $e -> getMessage () . " </p> " ;
}
} elseif ( $uri === '/api/status' ) {
header ( 'Content-Type: application/json' );
echo json_encode ([ 'status' => 'ok' , 'version' => '2027.1' ]);
} else {
http_response_code ( 404 );
echo " 404 Not Found " ;
}