motorradig2027/motorradig/src/Controllers/TourController.php

889 lines
29 KiB
PHP
Raw Normal View History

2026-10-09 09:07:18 +02:00
<?php
declare(strict_types=1);
namespace App\Controllers;
use App\Core\Auth;
use App\Core\Image;
use App\Models\Booking;
use App\Models\PushSubscription;
2026-10-09 09:07:18 +02:00
use App\Models\Tour;
use App\Models\TourRoom;
use App\Models\TourMessage;
2026-10-09 09:07:18 +02:00
use App\Models\User;
class TourController
{
public function index(): void
{
$tours = Tour::upcoming();
$participantCount = [];
$toursByYear = [];
2026-10-09 09:07:18 +02:00
foreach ($tours as $tour) {
$participantCount[$tour->id] = Booking::countForTour((int) $tour->id);
// Jahr vor der Formatierung aus dem DB-Datum (YYYY-MM-DD) lesen.
$year = (int) substr((string) $tour->start, 0, 4);
if ($year < 1900) {
$year = 0;
}
2026-10-09 09:07:18 +02:00
$tour->start = german_date($tour->start);
$tour->deadline = german_date($tour->deadline);
$toursByYear[$year][] = $tour;
}
krsort($toursByYear, SORT_NUMERIC);
$years = array_keys($toursByYear);
// Ohne Auswahl werden alle Jahre gruppiert angezeigt. ?jahr=2026 filtert.
$requestedYear = input('jahr');
$selectedYear = null;
if (is_string($requestedYear) && ctype_digit($requestedYear)) {
$candidate = (int) $requestedYear;
if (isset($toursByYear[$candidate])) {
$selectedYear = $candidate;
}
2026-10-09 09:07:18 +02:00
}
$visibleYears = $selectedYear === null ? $years : [$selectedYear];
view('tour.index', [
'toursByYear' => $toursByYear,
'years' => $years,
'visibleYears' => $visibleYears,
'selectedYear' => $selectedYear,
'participantCount' => $participantCount,
]);
2026-10-09 09:07:18 +02:00
}
public function indexOld(): void
{
$tours = Tour::past();
$participantCount = [];
$imagecountPerTour = [];
2026-11-08 17:02:51 +01:00
$toursByYear = [];
2026-10-09 09:07:18 +02:00
foreach ($tours as $tour) {
$participantCount[$tour->id] = Booking::countForTour((int) $tour->id);
2026-11-08 17:02:51 +01:00
// Jahr vor der Formatierung aus dem DB-Datum (YYYY-MM-DD) lesen.
$year = (int) substr((string) $tour->start, 0, 4);
if ($year < 1900) {
$year = 0;
}
2026-10-09 09:07:18 +02:00
$tour->start = german_date($tour->start);
$tour->deadline = german_date($tour->deadline);
$files = glob(storage_path('img_storage/tour-' . $tour->id) . '/*') ?: [];
$imagecountPerTour[$tour->id] = (int) (count($files) / 2);
2026-11-08 17:02:51 +01:00
$toursByYear[$year][] = $tour;
}
krsort($toursByYear, SORT_NUMERIC);
$years = array_keys($toursByYear);
// Ohne Auswahl werden alle Jahre gruppiert angezeigt. ?jahr=2025 filtert.
$requestedYear = input('jahr');
$selectedYear = null;
if (is_string($requestedYear) && ctype_digit($requestedYear)) {
$candidate = (int) $requestedYear;
if (isset($toursByYear[$candidate])) {
$selectedYear = $candidate;
}
2026-10-09 09:07:18 +02:00
}
2026-11-08 17:02:51 +01:00
$visibleYears = $selectedYear === null ? $years : [$selectedYear];
2026-10-09 09:07:18 +02:00
view('tour.index_old', [
2026-11-08 17:02:51 +01:00
'toursByYear' => $toursByYear,
'years' => $years,
'visibleYears' => $visibleYears,
'selectedYear' => $selectedYear,
2026-10-09 09:07:18 +02:00
'participantCount' => $participantCount,
'imagecountPerTour' => $imagecountPerTour,
]);
}
public function create(): void
{
2026-11-08 18:07:28 +01:00
$current = Auth::user();
if ($current === null || !$current->canCreateTours()) {
app_log('warning', 'Tour create denied', [
'role' => $current?->role,
]);
redirect('/tour');
}
2026-10-09 09:07:18 +02:00
$tour = new Tour();
$tour->name = 'neue Tour';
$tour->beschreibung = 'Tour Beschreibung';
$tour->tour_guide_id = Auth::id();
2026-10-09 09:07:18 +02:00
view('tour.create', ['tour' => $tour]);
}
public function store(): void
{
2026-11-08 18:07:28 +01:00
$current = Auth::user();
if ($current === null || !$current->canCreateTours()) {
app_log('warning', 'Tour create denied', [
'role' => $current?->role,
]);
redirect('/tour');
}
app_log('info', 'Tour create attempt', [
'name' => input('name'),
'start' => input('start'),
'deadline' => input('deadline'),
'max_participants' => input('max_participants'),
'is_cancelled' => input('is_cancelled'),
'tour_guide_id' => input('tour_guide_id'),
'has_image' => !empty($_FILES['bild']['name']),
'image_name' => $_FILES['bild']['name'] ?? null,
'image_size' => $_FILES['bild']['size'] ?? null,
]);
2026-10-09 09:07:18 +02:00
validate([
'name' => 'required|min:3',
'beschreibung' => 'required',
'start' => 'required|date',
'deadline' => 'required|date',
'tour_guide_id' => 'required',
2026-10-09 09:07:18 +02:00
]);
try {
$tour = Tour::create([
'name' => (string) input('name'),
'tour_guide_id' => (int) input('tour_guide_id'),
'beschreibung' => (string) input('beschreibung'),
'start' => db_date(input('start')),
'deadline' => db_date(input('deadline')),
'max_participants' => (int) (input('max_participants') ?: 5),
'is_cancelled' => (bool) input('is_cancelled', false),
'bericht' => null,
'created_at' => now(),
'updated_at' => now(),
]);
} catch (\Throwable $e) {
app_log('error', 'Tour create failed', [
'exception' => $e::class,
'error' => $e->getMessage(),
'name' => input('name'),
'start' => input('start'),
'deadline' => input('deadline'),
]);
$_SESSION['_old'] = $_POST;
flash_set('error', 'Die Tour konnte nicht gespeichert werden. Bitte den Administrator informieren.');
redirect('/tour/create');
}
app_log('info', 'Tour created', [
'tour_id' => $tour->id,
'name' => $tour->name,
'start' => $tour->start,
'tour_guide_id' => $tour->tour_guide_id,
2026-10-09 09:07:18 +02:00
]);
if (!empty($_FILES['bild']['name'])) {
try {
Image::storePublic($_FILES['bild'], 'img/tour', (string) $tour->id);
} catch (\Throwable $e) {
if (!$e instanceof \RuntimeException) {
error_log('Tourbild-Upload: ' . $e);
}
app_log('error', 'Tour image upload failed', [
'tour_id' => $tour->id,
'exception' => $e::class,
'error' => $e->getMessage(),
'image_name' => $_FILES['bild']['name'] ?? null,
'image_size' => $_FILES['bild']['size'] ?? null,
]);
flash_set('error', $e instanceof \RuntimeException
? $e->getMessage()
: 'Das Bild konnte nicht verarbeitet werden.');
redirect('/tour/' . $tour->id . '/edit');
}
}
$this->notifyEvent($tour, false);
$this->postChatSystem((int) $tour->id, 'Die Tour wurde angelegt. Hier könnt ihr euch austauschen.');
2026-10-09 09:07:18 +02:00
redirect('/tour');
}
/** Informiert alle Push-Abos über eine neue oder abgesagte Tour. */
private function notifyEvent(Tour $tour, bool $cancelled): void
{
try {
PushSubscription::sendToAll($cancelled
? [
'title' => 'Tour abgesagt: ' . $tour->name,
'body' => 'Der Termin am ' . german_date($tour->start) . ' fällt aus.',
'url' => '/tour/' . $tour->id,
'tag' => 'tour-' . $tour->id . '-cancelled',
]
: [
'title' => 'Neue Tour: ' . $tour->name,
'body' => german_date($tour->start) . ' – jetzt im Tourenplan ansehen.',
'url' => '/tour/' . $tour->id,
'tag' => 'tour-' . $tour->id,
]);
} catch (\Throwable $e) {
app_log('error', 'Push-Benachrichtigung zur Tour fehlgeschlagen', [
'tour_id' => (int) $tour->id,
'cancelled' => $cancelled,
'exception' => $e::class,
'error' => $e->getMessage(),
]);
}
}
/**
* Informiert den Tour Guide über eine An- oder Abmeldung in seiner Tour.
*
* Empfänger ist ausschließlich der eingetragene Guide (alle seine Geräte
* mit aktivierter App-Benachrichtigung). Löst der Guide die Änderung selbst
* aus, wird nichts versendet.
*/
private function notifyGuideBooking(Tour $tour, string $participantName, bool $joined): void
{
$guideId = (int) $tour->tour_guide_id;
if ($guideId <= 0 || $guideId === Auth::id() || $participantName === '') {
return;
}
try {
PushSubscription::sendToUsers([$guideId], [
'title' => ($joined ? 'Neue Anmeldung: ' : 'Abmeldung: ') . $tour->name,
'body' => $participantName . ($joined ? ' hat sich angemeldet.' : ' hat sich abgemeldet.'),
'url' => '/tour/' . (int) $tour->id,
// Bewusst ohne "tag": mehrere An-/Abmeldungen sollen sich in der
// Statusleiste nicht gegenseitig ersetzen.
]);
} catch (\Throwable $e) {
app_log('error', 'Push-Benachrichtigung zum Buchungsstatus fehlgeschlagen', [
'tour_id' => (int) $tour->id,
'guide_id' => $guideId,
'joined' => $joined,
'exception' => $e::class,
'error' => $e->getMessage(),
]);
}
}
2026-10-09 09:07:18 +02:00
public function show(string $id): void
{
$tour = Tour::find((int) $id);
if ($tour === null) {
redirect('/tour');
}
$current = Auth::user();
$guide = User::find((int) $tour->tour_guide_id);
$canManage = $this->canManageTour($tour);
$tourImages = $this->tourImages((int) $tour->id);
$canChat = $current !== null
&& TourMessage::isAvailable()
&& Booking::canAccessTour((int) $tour->id, $current);
$chatUnread = $canChat
? TourMessage::unreadCount((int) $tour->id, (int) $current->id)
: 0;
2026-10-09 09:07:18 +02:00
$users = [];
foreach (Booking::forTour((int) $tour->id) as $booking) {
$user = User::find((int) $booking->user_id);
if ($user !== null) {
$users[] = $user;
}
}
// Vergangene Tour
if ($tour->start < today()) {
$tour->start = german_date($tour->start);
$tour->deadline = german_date($tour->deadline);
view('tour.show_old', [
'tour' => $tour,
'users' => $users,
'guide' => $guide,
'tourImages' => $tourImages,
'canManage' => $canManage,
'canChat' => $canChat,
'chatUnread' => $chatUnread,
2026-10-09 09:07:18 +02:00
]);
return;
}
$rooms = array_map(fn(array $row) => (object) $row, TourRoom::fetchRooms((int) $tour->id));
$tour->start = german_date($tour->start);
$tour->deadline = german_date($tour->deadline);
view('tour.show', [
'tour' => $tour,
'users' => $users,
'guide' => $guide,
'tourImages' => $tourImages,
'rooms' => $rooms,
'canManage' => $canManage,
'canChat' => $canChat,
'chatUnread' => $chatUnread,
2026-10-09 09:07:18 +02:00
]);
}
public function edit(string $id): void
{
$tour = Tour::find((int) $id);
if ($tour === null || !$this->canManageTour($tour)) {
2026-10-09 09:07:18 +02:00
redirect('/tour');
}
$current = Auth::user();
$guides = $current->isAdmin() ? User::selectableGuides() : [];
$tourGuide = User::find((int) $tour->tour_guide_id);
$tourImages = $this->tourImages((int) $tour->id);
2026-10-09 09:07:18 +02:00
if ($tour->start < today()) {
$tour->start = german_date($tour->start);
$tour->deadline = german_date($tour->deadline);
view('tour.edit_old', [
'tour' => $tour,
'guides' => $guides,
'tourGuide' => $tourGuide,
'tourImages' => $tourImages,
]);
2026-10-09 09:07:18 +02:00
return;
}
$rooms = array_map(fn(array $row) => (object) $row, TourRoom::fetchRooms((int) $tour->id));
$tour->start = german_date($tour->start);
$tour->deadline = german_date($tour->deadline);
view('tour.edit', [
'tour' => $tour,
'rooms' => $rooms,
'guides' => $guides,
'tourGuide' => $tourGuide,
'tourImages' => $tourImages,
]);
2026-10-09 09:07:18 +02:00
}
public function update(string $id): void
{
$tourId = (int) input('tour_id', $id);
$tour = Tour::find($tourId);
if ($tour === null) {
redirect('/tour');
}
if (!$this->canManageTour($tour)) {
2026-10-23 13:14:31 +02:00
redirect('/tour');
}
$current = Auth::user();
$wasCancelled = (bool) $tour->is_cancelled;
2026-10-09 09:07:18 +02:00
validate([
'tour_id' => 'required',
'name' => 'required|min:3',
'start' => 'required|date',
'deadline' => 'date',
2026-10-09 09:07:18 +02:00
]);
// Nur Admins dürfen den Tour Guide ändern.
if ($current->isAdmin()) {
$guide = User::find((int) input('tour_guide_id'));
2026-11-08 18:07:28 +01:00
if ($guide === null || !($guide->isAdmin() || $guide->isTourGuide())) {
flash_set('error', 'Der gewählte Tour Guide ist ungültig.');
redirect('/tour/' . $tourId . '/edit');
}
$tour->tour_guide_id = (int) $guide->id;
2026-10-09 09:07:18 +02:00
}
$tour->name = (string) input('name');
if (input('beschreibung') !== null) {
$tour->beschreibung = (string) input('beschreibung');
}
if (input('start') !== null) {
$tour->start = db_date(input('start'));
}
if (input('deadline') !== null) {
$tour->deadline = db_date(input('deadline'));
}
if (input('max_participants') !== null) {
$tour->max_participants = (int) input('max_participants');
}
if (input('is_cancelled')) {
$tour->is_cancelled = true;
} else {
$tour->is_cancelled = false;
}
if (input('bericht') !== null) {
$tour->bericht = (string) input('bericht');
}
$tour->updated_at = now();
$tour->save();
if ($tour->is_cancelled && !$wasCancelled) {
$this->notifyEvent($tour, true);
$this->postChatSystem($tourId, 'Die Tour wurde abgesagt.');
} elseif (!$tour->is_cancelled && $wasCancelled) {
$this->postChatSystem($tourId, 'Die Tour wurde wieder aktiviert.');
}
redirect('/tour/' . $tourId . '/edit');
2026-10-09 09:07:18 +02:00
}
public function destroy(string $id): void
{
$current = Auth::user();
if ($current === null || !$current->isAdmin()) {
redirect('/tour');
}
$tour = Tour::find((int) $id);
if ($tour === null) {
redirect('/tour');
}
$tourId = (int) $tour->id;
$tourName = (string) $tour->name;
// Abhängige Daten zuerst entfernen.
db()->execute('DELETE FROM `bookings` WHERE tour_id = ?', [$tourId]);
db()->execute('DELETE FROM `tour_rooms` WHERE tour_id = ?', [$tourId]);
TourMessage::deleteForTour($tourId);
db()->execute('DELETE FROM `tours` WHERE id = ?', [$tourId]);
// Galerie und Tourbilder von der Festplatte entfernen.
$this->deleteDirectory(storage_path('img_storage/tour-' . $tourId));
$this->deleteDirectory(storage_path('img_storage/tour-' . $tourId . '-DELETED'));
$this->deleteDirectory(public_path('img/tour/' . $tourId));
foreach ([
public_path('img/tour/' . $tourId . '.jpg'),
public_path('img/tour/' . $tourId . '_gross.jpg'),
] as $file) {
if (is_file($file)) {
@unlink($file);
}
}
app_log('info', 'Tour gelöscht', [
'tour_id' => $tourId,
'name' => $tourName,
'by' => (int) $current->id,
]);
flash_set('status', 'Die Tour "' . $tourName . '" wurde gelöscht.');
redirect('/tour');
}
/** Löscht ein Verzeichnis mit Inhalt (nur für Tour-Dateien verwendet). */
private function deleteDirectory(string $dir): void
{
if (!is_dir($dir)) {
return;
}
$items = scandir($dir) ?: [];
foreach ($items as $item) {
if ($item === '.' || $item === '..') {
continue;
}
$path = $dir . '/' . $item;
if (is_dir($path) && !is_link($path)) {
$this->deleteDirectory($path);
} elseif (is_file($path) || is_link($path)) {
@unlink($path);
}
}
@rmdir($dir);
2026-10-09 09:07:18 +02:00
}
public function uploadGallery(string $tour_id): void
{
redirect('/tour');
}
/** Lädt mehrere Tour-Bilder hoch (Admin oder Tour Guide). */
public function storeImages(string $tour_id): void
{
$tour = Tour::find((int) $tour_id);
if (!$this->canManageTour($tour)) {
redirect('/tour');
}
$files = $_FILES['bilder'] ?? null;
if (!is_array($files) || !isset($files['name'])) {
flash_set('error', 'Bitte mindestens ein Bild auswählen.');
redirect('/tour/' . $tour_id . '/edit');
}
$names = (array) $files['name'];
$tmpNames = (array) ($files['tmp_name'] ?? []);
$errors = (array) ($files['error'] ?? []);
$sizes = (array) ($files['size'] ?? []);
$stored = 0;
$problems = [];
foreach (array_keys($names) as $i) {
$upload = [
'name' => (string) ($names[$i] ?? ''),
'tmp_name' => (string) ($tmpNames[$i] ?? ''),
'error' => (int) ($errors[$i] ?? UPLOAD_ERR_NO_FILE),
'size' => (int) ($sizes[$i] ?? 0),
];
if ($upload['error'] === UPLOAD_ERR_NO_FILE) {
continue;
}
try {
$imageName = $this->uniqueTourImageName((int) $tour->id, $upload['name']);
Image::storePublic($upload, 'img/tour/' . $tour->id, $imageName);
$stored++;
} catch (\Throwable $e) {
if (!$e instanceof \RuntimeException) {
error_log('Tourbild-Upload: ' . $e);
$problems[] = 'Ein Bild konnte nicht verarbeitet werden.';
} else {
$problems[] = $e->getMessage();
}
}
}
if ($stored > 0) {
flash_set('status', $stored === 1 ? 'Bild wurde hinzugefügt.' : $stored . ' Bilder wurden hinzugefügt.');
}
if ($problems !== []) {
flash_set('error', implode(' ', array_unique($problems)));
} elseif ($stored === 0) {
flash_set('error', 'Bitte mindestens ein Bild auswählen.');
}
redirect('/tour/' . $tour_id . '/edit');
}
/** Löscht ein Tour-Bild (Admin oder Tour Guide). */
public function deleteImage(string $tour_id, string $imageName): void
{
$tour = Tour::find((int) $tour_id);
if (!$this->canManageTour($tour)) {
redirect('/tour');
}
$name = basename((string) $imageName);
$name = preg_replace('/(?:_gross)?\.(?:jpe?g)$/i', '', $name) ?? $name;
$deleted = false;
if ($name === (string) $tour->id) {
// Altes Einzelbild (public/img/tour/<id>.jpg)
foreach (['.jpg', '_gross.jpg'] as $suffix) {
$path = public_path('img/tour/' . $name . $suffix);
if (is_file($path) && @unlink($path)) {
$deleted = true;
}
}
} elseif (preg_match('/^[a-z0-9][a-z0-9-]*$/', $name) === 1) {
// Neues Bild im Ordner public/img/tour/<id>/
foreach (['.jpg', '_gross.jpg'] as $suffix) {
$path = public_path('img/tour/' . $tour->id . '/' . $name . $suffix);
if (is_file($path) && @unlink($path)) {
$deleted = true;
}
}
}
flash_set($deleted ? 'status' : 'error', $deleted
? 'Bild wurde gelöscht.'
: 'Das Bild konnte nicht gelöscht werden.');
redirect('/tour/' . $tour_id . '/edit');
}
/**
* Liefert alle Tour-Bilder (altes Einzelbild und neuer Bilderordner),
* neueste zuerst.
*/
private function tourImages(int $tourId): array
{
$images = [];
$legacy = public_path('img/tour/' . $tourId . '.jpg');
if (is_file($legacy)) {
$images[] = [
'name' => (string) $tourId,
'thumb' => '/img/tour/' . $tourId . '.jpg',
'large' => '/img/tour/' . $tourId . '_gross.jpg',
'version' => @filemtime($legacy) ?: 0,
'mtime' => @filemtime($legacy) ?: 0,
];
}
$dir = public_path('img/tour/' . $tourId);
if (is_dir($dir)) {
foreach (glob($dir . '/*.jpg') ?: [] as $file) {
$filename = basename($file);
if (str_ends_with($filename, '_gross.jpg')) {
continue;
}
$name = substr($filename, 0, -4);
$gross = $dir . '/' . $name . '_gross.jpg';
$images[] = [
'name' => $name,
'thumb' => '/img/tour/' . $tourId . '/' . $filename,
'large' => is_file($gross)
? '/img/tour/' . $tourId . '/' . $name . '_gross.jpg'
: '/img/tour/' . $tourId . '/' . $filename,
'version' => @filemtime($file) ?: 0,
'mtime' => @filemtime($file) ?: 0,
];
}
}
usort($images, fn(array $a, array $b) => $b['mtime'] <=> $a['mtime']);
return $images;
}
/** Erzeugt einen Dateinamen, der im Tour-Ordner noch nicht existiert. */
private function uniqueTourImageName(int $tourId, string $originalName): string
{
$dir = public_path('img/tour/' . $tourId);
$base = Image::slug(pathinfo($originalName, PATHINFO_FILENAME));
// Reine Zahlen wären mit dem alten Einzelbild (<id>.jpg) verwechselbar.
if (ctype_digit($base)) {
$base = 'bild-' . $base;
}
$base = substr($base, 0, 60);
$name = $base;
$i = 2;
while (is_file($dir . '/' . $name . '.jpg') || is_file($dir . '/' . $name . '_gross.jpg')) {
$name = $base . '-' . $i;
$i++;
}
return $name;
}
2026-10-09 09:07:18 +02:00
public function joinRoom(string $tour_id, string $room_id): void
{
$tour = Tour::find((int) $tour_id);
$user = Auth::user();
if ($tour === null || $user === null) {
redirect('/tour');
}
$roomId = (int) $room_id;
// Normale Nutzer dürfen sich nur selbst in einen echten, freien Raum
// eintragen. room_id 0 (austragen) und Raumwechsel bleiben Admins
// bzw. dem Tour Guide vorbehalten.
if (Booking::forUser((int) $tour->id, (int) $user->id) !== null
|| !TourRoom::isBookable((int) $tour->id, $roomId)
|| !Tour::hasSpace((int) $tour->id)) {
redirect('/tour/' . $tour_id);
}
Booking::joinRoom((int) $tour->id, (int) $user->id, $roomId);
$this->postChatSystem((int) $tour->id, $user->name . ' hat die Tour gebucht.');
$this->notifyGuideBooking($tour, $user->name, true);
2026-10-09 09:07:18 +02:00
redirect('/tour/' . $tour_id);
}
2026-10-23 13:14:31 +02:00
public function joinRoom4user(string $tour_id, string $room_id): void
2026-10-09 09:07:18 +02:00
{
$tour = Tour::find((int) $tour_id);
if (!$this->canManageTour($tour)) {
redirect('/tour');
}
2026-10-23 13:14:31 +02:00
$userId = (int) input('user_id', 0);
$roomId = (int) $room_id;
2026-10-09 09:07:18 +02:00
2026-10-23 13:14:31 +02:00
if ($userId > 0) {
if ($roomId > 0 && TourRoom::findForTour($roomId, (int) $tour->id) === null) {
redirect('/tour/' . $tour_id . '/edit');
}
$wasBooked = Booking::forUser((int) $tour->id, $userId) !== null;
Booking::joinRoom((int) $tour->id, $userId, $roomId);
$participant = User::find($userId);
if ($participant !== null) {
if (!$wasBooked) {
// Nur eine echte Neuaufnahme, kein reiner Zimmerwechsel.
$this->notifyGuideBooking($tour, $participant->name, true);
}
if ($roomId > 0) {
$room = TourRoom::findForTour($roomId, (int) $tour->id);
$roomName = $room !== null ? (string) $room['name'] : '';
$roomLabel = $roomName !== ''
? 'dem ' . $roomName . ' (ID ' . $roomId . ')'
: 'einem Zimmer';
$this->postChatSystem(
(int) $tour->id,
$participant->name . ' wurde ' . $roomLabel . ' zugeordnet.'
);
} else {
$this->postChatSystem(
(int) $tour->id,
'Die Zimmerzuordnung von ' . $participant->name . ' wurde entfernt.'
);
}
}
2026-10-23 13:14:31 +02:00
}
2026-10-09 09:07:18 +02:00
2026-10-23 13:14:31 +02:00
redirect('/tour/' . $tour_id . '/edit');
2026-10-09 09:07:18 +02:00
}
public function cancelBooking(string $tour_id): void
{
$tour = Tour::find((int) $tour_id);
$user = Auth::user();
if (!$this->canManageTour($tour)) {
2026-10-23 13:14:31 +02:00
redirect('/tour');
}
if ($tour !== null && $user !== null
&& Booking::forUser((int) $tour->id, (int) $user->id) !== null) {
Booking::deleteForUser((int) $tour->id, (int) $user->id);
$this->notifyGuideBooking($tour, $user->name, false);
}
2026-10-09 09:07:18 +02:00
redirect('/tour');
}
public function cancelBookingAdmin(string $tour_id, string $user_id): void
{
$tour = Tour::find((int) $tour_id);
if (!$this->canManageTour($tour)) {
2026-10-23 13:14:31 +02:00
redirect('/tour/' . $tour_id);
2026-10-09 09:07:18 +02:00
}
$participant = User::find((int) $user_id);
$hadBooking = Booking::forUser((int) $tour_id, (int) $user_id) !== null;
2026-10-23 13:14:31 +02:00
Booking::deleteForUser((int) $tour_id, (int) $user_id);
if ($participant !== null) {
$this->postChatSystem((int) $tour_id, $participant->name . ' wurde aus der Tour entfernt.');
if ($hadBooking && $tour !== null) {
$this->notifyGuideBooking($tour, $participant->name, false);
}
}
2026-10-09 09:07:18 +02:00
redirect('/tour/' . $tour_id);
}
public function createRoom(string $tour_id, string $capacity): void
{
$tour = Tour::find((int) $tour_id);
if (!$this->canManageTour($tour)) {
redirect('/tour');
}
Tour::createRoom((int) $tour->id, (int) $capacity);
$this->postChatSystem(
(int) $tour->id,
(int) $capacity === 1 ? 'Ein Einzelzimmer wurde erstellt.' : 'Ein Doppelzimmer wurde erstellt.'
);
2026-10-09 09:07:18 +02:00
redirect('/tour/' . $tour_id . '/edit');
}
public function deleteRoom(string $tour_id, string $room_id): void
{
$tour = Tour::find((int) $tour_id);
if (!$this->canManageTour($tour)) {
redirect('/tour');
}
$room = TourRoom::findForTour((int) $room_id, (int) $tour->id);
2026-10-09 09:07:18 +02:00
db()->execute('UPDATE `bookings` SET room_id = NULL WHERE room_id = ?', [(int) $room_id]);
db()->execute('DELETE FROM `tour_rooms` WHERE tour_id = ? AND id = ?', [(int) $tour->id, (int) $room_id]);
2026-10-09 09:07:18 +02:00
$roomName = $room !== null ? (string) $room['name'] : '';
$this->postChatSystem(
(int) $tour->id,
$roomName !== ''
? 'Das ' . $roomName . ' (ID ' . (int) $room_id . ') wurde gelöscht.'
: 'Ein Zimmer wurde gelöscht.'
);
2026-10-09 09:07:18 +02:00
redirect('/tour/' . $tour_id . '/edit');
}
2026-10-23 13:14:31 +02:00
private function canManageTour(?Tour $tour): bool
2026-10-23 13:14:31 +02:00
{
return $tour !== null && Tour::canManage((int) $tour->id, Auth::user());
}
2026-10-23 13:14:31 +02:00
/** Schreibt eine Systemnachricht in den Tour-Chat, ohne Buchungen zu blockieren. */
private function postChatSystem(int $tourId, string $body): void
{
try {
TourMessage::postSystem($tourId, $body);
} catch (\Throwable $e) {
app_log('error', 'Tour-Chat Systemnachricht fehlgeschlagen', [
'tour_id' => $tourId,
'error' => $e->getMessage(),
]);
}
2026-10-23 13:14:31 +02:00
}
2026-10-09 09:07:18 +02:00
}