getMessage() . "\n"; } exit; } elseif ($page === 'fetch_results') { // Ergebnis-Fetcher von außen aufrufbar (z.B. cron-job.org), ohne Login. header('Content-Type: text/plain; charset=UTF-8'); try { echo FetcherLog::deleteOld() . " alte Fetcher-Log-Einträge gelöscht.\n"; echo "== Bundesliga/DFB-Pokal (openligadb) ==\n"; echo \App\Core\ResultFetcher::openligadb(true); echo "\n\n== International (API-Football) ==\n"; echo \App\Core\ResultFetcher::apifootball(true); echo "\n"; } catch (\Throwable $e) { http_response_code(500); echo "Fehler: " . $e->getMessage() . "\n"; } exit; } elseif ($page === 'login') { // Wenn bereits eingeloggt, zur Startseite weiterleiten if (Auth::check()) { header('Location: /'); exit; } if ($_SERVER['REQUEST_METHOD'] === 'POST') { $firstname = $_POST['firstname'] ?? ''; $lastname = $_POST['lastname'] ?? ''; $password = $_POST['password'] ?? ''; if (Auth::login($firstname, $lastname, $password)) { header('Location: /'); 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: /'); exit; } if (!Setting::isRegistrationOpen()) { http_response_code(403); $registrationClosed = true; require __DIR__ . '/../src/Views/register.php'; exit; } if ($_SERVER['REQUEST_METHOD'] === 'POST') { $data = [ 'firstname' => trim($_POST['firstname'] ?? ''), 'lastname' => trim($_POST['lastname'] ?? ''), 'email' => trim($_POST['email'] ?? ''), 'password' => $_POST['password'] ?? '', 'iban' => trim($_POST['iban'] ?? ''), 'paypal' => trim($_POST['paypal'] ?? ''), 'mobile' => trim($_POST['mobile'] ?? ''), ]; $data['iban'] = Iban::normalize($data['iban']); $password_confirm = $_POST['password_confirm'] ?? ''; $error = null; if ( $data['firstname'] === '' || $data['lastname'] === '' || $data['email'] === '' || $data['mobile'] === '' || $data['password'] === '' ) { $error = 'Bitte fülle alle Pflichtfelder aus.'; } elseif ($data['iban'] === '' && $data['paypal'] === '') { $error = 'Bitte gib eine Zahlungsmöglichkeit an (IBAN oder PayPal).'; } elseif (empty($_POST['privacy'])) { $error = 'Bitte bestätige, dass du die Datenschutzhinweise gelesen hast.'; } elseif ($data['iban'] !== '' && !Iban::isValid($data['iban'])) { $error = 'Bitte eine gültige IBAN angeben.'; } 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: /'); 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; $jokerUsage = Tipp::formatJokerUsage( Tipp::getJokerUsage($user['id'], $activeSeason['id'], null, $round['id']) ); $maxIdenticalJokertipps = (int)$activeSeason['max_identical_jokertipps']; 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; $jokerUsage = Tipp::formatJokerUsage( Tipp::getJokerUsage($user['id'], $activeSeason['id'], null, $round['id']) ); $maxIdenticalJokertipps = (int)$activeSeason['max_identical_jokertipps']; 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'; } elseif ($page === 'datenschutz') { // Datenschutzhinweise: öffentlich, ohne Login erreichbar require __DIR__ . '/../src/Views/info/privacy.php'; } elseif ($page === 'guide') { // Info -> Anleitung: Regeln mit den Werten der angezeigten Saison Auth::requireLogin(); $currentSeason = Season::getViewSeason(); $payouts = $currentSeason ? Quota::computePayouts($currentSeason['id']) : null; $maxIdenticalJokertipps = (int)($currentSeason['max_identical_jokertipps'] ?? Season::DEFAULT_MAX_IDENTICAL_JOKERTIPPS); $jackpot = $currentSeason ? (float)$currentSeason['jackpot'] : 0.0; $jackpotStatus = $currentSeason ? Ranking::getJackpotStatus($currentSeason['id']) : ['won' => false, 'amount' => 0.0, 'perWinner' => 0.0, 'winners' => []]; require __DIR__ . '/../src/Views/info/guide.php'; } elseif ($page === 'guide_admin') { // Info -> Anleitung-Admin: Saison-/Quoten-Verwaltung (nur für Admins) Auth::requireLogin(); Auth::requireAdmin(); require __DIR__ . '/../src/Views/info/guide_admin.php'; } elseif ($page === 'info_quotas') { // Info -> Quoten (Legacy UsersController::show_payouts) Auth::requireLogin(); $currentSeason = Season::getViewSeason(); $payouts = $currentSeason ? Quota::computePayouts($currentSeason['id']) : null; $activeUserCount = $currentSeason ? count(User::getPaid($currentSeason['id'])) : 0; $stake = $currentSeason ? (Quota::getMapBySeason($currentSeason['id'])['einsatz'] ?? 0) : 0; $jackpot = $currentSeason ? (float)$currentSeason['jackpot'] : 0.0; $jackpotStatus = $currentSeason ? Ranking::getJackpotStatus($currentSeason['id']) : ['won' => false, 'amount' => 0.0, 'perWinner' => 0.0, 'winners' => []]; 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::getViewSeason(); 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::getViewSeason(); $result = null; $seasonStart = null; if ($currentSeason) { ['result' => $result, 'season_start' => $seasonStart] = Ranking::computeForMoneyRanking($currentSeason['id']); } $moneyRanking = $result ? Ranking::moneyRanking($result, true) : []; require __DIR__ . '/../src/Views/admin/accounts.php'; } elseif ($page === 'admin_message') { // Aktuelle Mitteilung für die Startseite (nur Admins) Auth::requireLogin(); Auth::requireAdmin(); if ($_SERVER['REQUEST_METHOD'] === 'POST') { Setting::setMessage($_POST['message'] ?? ''); $_SESSION['admin_message'] = 'Die aktuelle Mitteilung wurde gespeichert.'; header('Location: /index.php?page=admin_message'); exit; } $flashMessage = $_SESSION['admin_message'] ?? null; $error = $_SESSION['admin_error'] ?? null; unset($_SESSION['admin_message'], $_SESSION['admin_error']); $currentMessage = Setting::getMessage(); require __DIR__ . '/../src/Views/admin/message.php'; } elseif ($page === 'admin_fetcher_activity') { // Aktivitätslog des Ergebnis-Fetchers (nur Admins) Auth::requireLogin(); Auth::requireAdmin(); $from = $_GET['from'] ?? date('Y-m-d', strtotime('-7 days')); $to = $_GET['to'] ?? date('Y-m-d'); if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $from) || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $to)) { $from = date('Y-m-d', strtotime('-7 days')); $to = date('Y-m-d'); } $entries = FetcherLog::getRange($from, $to); require __DIR__ . '/../src/Views/admin/fetcher_activity.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']); // IBAN für die Anzeige entschlüsseln (in der DB liegt nur der Ciphertext) try { $user['iban'] = \App\Core\Crypto::decrypt($user['iban']); } catch (\Throwable $e) { $user['iban'] = ''; $error = 'Die hinterlegte IBAN konnte nicht entschlüsselt werden.'; } 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'] = Iban::normalize($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.'; } elseif ($data['iban'] !== '' && !Iban::isValid($data['iban'])) { $error = 'Bitte eine gültige IBAN angeben.'; } 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') { $action = $_POST['action'] ?? ''; // 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, '//'); if ($action === 'set_registration') { Setting::setRegistrationOpen(($_POST['registration_open'] ?? '') === '1'); } elseif ($action === 'set_view_season') { // Persönliche Saison-Ansicht des Admins umschalten (wirkt nur auf ihn) Season::setViewSeason($_POST['season_id'] ?? null); } 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'] ?? '', 'jackpot' => str_replace(',', '.', trim($_POST['jackpot'] ?? '')), ]; if ($data['name'] === '' || !ctype_digit((string)$data['rounds']) || (int)$data['rounds'] < 1 || !ctype_digit((string)$data['max_identical_jokertipps']) || !is_numeric($data['jackpot']) || (float)$data['jackpot'] < 0) { throw new \Exception('Name, Runden, maximale Anzahl gleicher Joker und Jackpot 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); // Nur die persönliche Ansicht des Admins umschalten – die für // alle Spieler aktive Saison bleibt unverändert. Season::setViewSeason($newSeasonId); $_SESSION['admin_message'] = "Saison erfolgreich erstellt und für dich als Ansicht gesetzt. Für alle Spieler bleibt die bisherige Saison aktiv."; } 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); Season::setViewSeason($seasonId); $_SESSION['admin_message'] = "Saison wurde für alle Spieler als aktiv gesetzt."; } elseif ($action === 'view' && $seasonId) { Season::setViewSeason($seasonId); $_SESSION['admin_message'] = "Saison wird jetzt nur für dich angezeigt."; } 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(); $viewSeason = Season::getViewSeason(); $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, 'jackpot' => $template['jackpot'] ?? Season::DEFAULT_JACKPOT, '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(); $activeSeason = Season::getCurrent(); $viewSeason = Season::getViewSeason(); $seasonId = (int)($_GET['season_id'] ?? ($viewSeason ? (int)$viewSeason['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(); $currentSeason = Season::getViewSeason(); $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, $currentSeason ? (int)$currentSeason['id'] : 0); } $_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']); $excludeReminders = ($_GET['hide_reminders'] ?? '') === '1'; if ($compose) { $currentSeason = Season::getViewSeason(); $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($excludeReminders); $totalPages = max(1, (int)ceil($totalMails / $perPage)); $currentPage = min(max(1, (int)($_GET['p'] ?? 1)), $totalPages); $mails = Roundmail::getPage($perPage, ($currentPage - 1) * $perPage, $excludeReminders); } require __DIR__ . '/../src/Views/admin/roundmails.php'; } elseif ($page === 'admin_users') { Auth::requireLogin(); Auth::requireAdmin(); $currentSeason = Season::getViewSeason(); $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 === 'update' && $userId) { // Passwort nur ändern, wenn die Änderung ausdrücklich per // Checkbox aktiviert wurde. Sonst kann ein vom Browser // automatisch ausgefülltes Passwortfeld das Passwort // unbeabsichtigt überschreiben. $changePassword = ($_POST['change_password'] ?? '') === '1'; if ($changePassword && trim((string)($_POST['password'] ?? '')) === '') { throw new \Exception('Bitte ein neues Passwort eingeben oder die Passwortänderung abwählen.'); } $data = [ 'firstname' => $_POST['firstname'], 'lastname' => $_POST['lastname'], 'email' => $_POST['email'], 'password' => $changePassword ? ($_POST['password'] ?? '') : '', 'iban' => Iban::normalize(trim($_POST['iban'] ?? '')), 'paypal' => trim($_POST['paypal'] ?? ''), 'mobile' => trim($_POST['mobile'] ?? ''), 'admin' => isset($_POST['admin']) ? 1 : 0, ]; if ($data['iban'] !== '' && !Iban::isValid($data['iban'])) { throw new \Exception('Bitte eine gültige IBAN angeben.'); } 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']); if ($editUser) { // IBAN liegt verschlüsselt in der DB und wird nur für das Formular entschlüsselt. try { $editUser['iban'] = \App\Core\Crypto::decrypt($editUser['iban']); } catch (\Throwable $e) { $editUser['iban'] = ''; $error = 'Die hinterlegte IBAN konnte nicht entschlüsselt werden.'; } } } 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 "
Fehler: " . htmlspecialchars($e->getMessage()) . "
"; } } elseif ($page === 'ranking') { Auth::requireLogin(); try { $currentSeason = Season::getViewSeason(); if (!$currentSeason) { throw new \Exception("Keine aktuelle Saison gefunden."); } // Auswählbar sind nur gesperrte Runden (erstes Spiel angepfiffen), // Standard ist die zuletzt gesperrte Runde (Legacy Round::getLastLockedRoundId). // Nicht die letzte Runde mit Ergebnis: Bei laufender Runde ohne Ergebnis // würde sonst die vorherige, bereits abgeschlossene Runde erscheinen. $allRounds = []; foreach (Round::getBySeason($currentSeason['id']) as $round) { $roundGames = Game::getGamesByRound($round['id']); if (empty($roundGames) || !Game::isLocked($roundGames[0]['kickoff'])) { continue; } $allRounds[] = $round; } $selectedRound = !empty($allRounds) ? $allRounds[count($allRounds) - 1] : null; if (isset($_GET['round_id'])) { foreach ($allRounds as $round) { if ((int)$round['id'] === (int)$_GET['round_id']) { $selectedRound = $round; } } } $ranking = []; $games = []; $teamLogos = []; $roundCompleted = false; $isFinalRound = false; $roundHasJackpot = false; if ($selectedRound) { $result = Ranking::compute($currentSeason['id'], $selectedRound['id']); $ranking = Ranking::roundTable($result); $games = $result['rounds'][$selectedRound['id']]['games'] ?? []; $roundCompleted = (bool)($result['rounds'][$selectedRound['id']]['completed'] ?? false); $isFinalRound = (bool)$result['is_final']; $roundEntries = $result['rounds'][$selectedRound['id']]['entries'] ?? []; foreach ($roundEntries as $entry) { if (($entry['jackpot_payout'] ?? 0) > 0) { $roundHasJackpot = true; break; } } $teamIds = []; foreach ($games as $game) { if (!empty($game['team1_id'])) $teamIds[] = (int)$game['team1_id']; if (!empty($game['team2_id'])) $teamIds[] = (int)$game['team2_id']; } if (!empty($teamIds)) { $teamLogos = Team::logoMap($teamIds); } } require __DIR__ . '/../src/Views/ranking.php'; } catch (Throwable $e) { http_response_code(500); echo "Fehler: " . htmlspecialchars($e->getMessage()) . "
"; } } elseif ($page === 'questions') { // Fragen an die Admins (Legacy: kein direkter Vorgänger, neu für 2027) Auth::requireLogin(); $user = Auth::user(); $isAdmin = (bool)$user['admin']; $message = $_SESSION['questions_message'] ?? null; $error = $_SESSION['questions_error'] ?? null; unset($_SESSION['questions_message'], $_SESSION['questions_error']); if ($_SERVER['REQUEST_METHOD'] === 'POST') { $action = $_POST['action'] ?? ''; $redirect = '/index.php?page=questions'; if ($action === 'ask') { $questionText = trim($_POST['question'] ?? ''); if ($questionText === '') { $_SESSION['questions_error'] = 'Bitte gib eine Frage ein.'; } else { Question::create((int)$user['id'], $questionText); $_SESSION['questions_message'] = 'Deine Frage wurde an die Admins gesendet.'; } } elseif ($action === 'answer') { if (!$isAdmin) { header('Location: /'); exit; } $questionId = (int)($_POST['id'] ?? 0); $answerText = trim($_POST['answer'] ?? ''); $question = Question::findById($questionId); if (!$question) { $_SESSION['questions_error'] = 'Frage nicht gefunden.'; } elseif ($question['answer'] !== null) { $_SESSION['questions_error'] = 'Die Frage wurde bereits beantwortet.'; } elseif ($answerText === '') { $_SESSION['questions_error'] = 'Bitte gib eine Antwort ein.'; $redirect .= '&answer_id=' . $questionId; } else { Question::answer($questionId, $answerText, (int)$user['id']); $_SESSION['questions_message'] = 'Antwort wurde gespeichert.'; } } header('Location: ' . $redirect); exit; } // Beim Ansehen werden die eigenen Antworten (und für Admins auch die // offenen Fragen) als gesehen markiert. Question::markAnswersSeen((int)$user['id']); if ($isAdmin) { Question::markQuestionsSeen(); } $questions = $isAdmin ? Question::findAllForAdmin() : Question::findByUser((int)$user['id']); $answerQuestion = null; if ($isAdmin && isset($_GET['answer_id'])) { $answerQuestion = Question::findById((int)$_GET['answer_id']); if (!$answerQuestion || $answerQuestion['answer'] !== null) { $answerQuestion = null; } } require __DIR__ . '/../src/Views/questions.php'; } elseif ($page === 'home') { Auth::requireLogin(); try { $currentSeason = Season::getViewSeason(); $message = Setting::getMessage(); // Profil-Warnungen gelten immer, nicht nur im Zeitfenster vor dem Lock. $profileWarnings = User::getProfileWarnings((int)Auth::id()); $lockWarning = $currentSeason ? Round::getLockWarning((int)$currentSeason['id'], (int)Auth::id()) : null; $rounds = []; $roundSummaries = []; if ($currentSeason) { foreach (Round::getBySeason($currentSeason['id']) as $round) { if (Round::isCompleted(Game::getGamesByRound($round['id']))) { $rounds[] = $round; } } $rounds = array_reverse($rounds); // Gewinne und Besonderheiten je Runde automatisch aus der Wertung if (!empty($rounds)) { $result = Ranking::compute($currentSeason['id'], (int)$rounds[0]['id']); $roundSummaries = Ranking::roundSummary($result); } } require __DIR__ . '/../src/Views/home.php'; } catch (Throwable $e) { echo "Fehler: " . $e->getMessage() . "
"; } } 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"; }