motorradig2027/motorradig/src/Controllers/TourController.php

635 lines
20 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Controllers;
use App\Core\Auth;
use App\Core\Image;
use App\Models\Booking;
use App\Models\Tour;
use App\Models\TourRoom;
use App\Models\User;
class TourController
{
public function index(): void
{
$tours = Tour::upcoming();
$participantCount = [];
$toursByYear = [];
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;
}
$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;
}
}
$visibleYears = $selectedYear === null ? $years : [$selectedYear];
view('tour.index', [
'toursByYear' => $toursByYear,
'years' => $years,
'visibleYears' => $visibleYears,
'selectedYear' => $selectedYear,
'participantCount' => $participantCount,
]);
}
public function indexOld(): void
{
$tours = Tour::past();
$participantCount = [];
$imagecountPerTour = [];
$toursByYear = [];
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;
}
$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);
$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;
}
}
$visibleYears = $selectedYear === null ? $years : [$selectedYear];
view('tour.index_old', [
'toursByYear' => $toursByYear,
'years' => $years,
'visibleYears' => $visibleYears,
'selectedYear' => $selectedYear,
'participantCount' => $participantCount,
'imagecountPerTour' => $imagecountPerTour,
]);
}
public function create(): void
{
$tour = new Tour();
$tour->name = 'neue Tour';
$tour->beschreibung = 'Tour Beschreibung';
$tour->tour_guide_id = Auth::id();
view('tour.create', ['tour' => $tour]);
}
public function store(): void
{
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,
]);
validate([
'name' => 'required|min:3',
'beschreibung' => 'required',
'start' => 'required',
'deadline' => 'required',
'tour_guide_id' => 'required',
]);
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,
]);
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');
}
}
redirect('/tour');
}
public function show(string $id): void
{
$tour = Tour::find((int) $id);
if ($tour === null) {
redirect('/tour');
}
$guide = User::find((int) $tour->tour_guide_id);
$canManage = $this->canManageTour($tour);
$tourImages = $this->tourImages((int) $tour->id);
$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,
]);
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,
]);
}
public function edit(string $id): void
{
$tour = Tour::find((int) $id);
if ($tour === null || !$this->canManageTour($tour)) {
redirect('/tour');
}
$current = Auth::user();
$guides = $current->isAdmin() ? User::selectableGuides() : [];
$tourGuide = User::find((int) $tour->tour_guide_id);
$tourImages = $this->tourImages((int) $tour->id);
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,
]);
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,
]);
}
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)) {
redirect('/tour');
}
$current = Auth::user();
validate([
'tour_id' => 'required',
'name' => 'required|min:3',
]);
// Nur Admins dürfen den Tour Guide ändern.
if ($current->isAdmin()) {
$guide = User::find((int) input('tour_guide_id'));
if ($guide === null || $guide->role === 'GUEST') {
flash_set('error', 'Der gewählte Tour Guide ist ungültig.');
redirect('/tour/' . $tourId . '/edit');
}
$tour->tour_guide_id = (int) $guide->id;
}
$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();
redirect('/tour/' . $tourId . '/edit');
}
public function destroy(string $id): void
{
// Im Original ohne Funktion.
}
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;
}
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);
redirect('/tour/' . $tour_id);
}
public function joinRoom4user(string $tour_id, string $room_id): void
{
$tour = Tour::find((int) $tour_id);
if (!$this->canManageTour($tour)) {
redirect('/tour');
}
$userId = (int) input('user_id', 0);
if ($userId > 0) {
Booking::joinRoom((int) $tour->id, $userId, (int) $room_id);
}
redirect('/tour/' . $tour_id . '/edit');
}
public function cancelBooking(string $tour_id): void
{
if (!$this->canManageTour(Tour::find((int) $tour_id))) {
redirect('/tour');
}
Booking::deleteForUser((int) $tour_id, (int) Auth::id());
redirect('/tour');
}
public function cancelBookingAdmin(string $tour_id, string $user_id): void
{
if (!$this->canManageTour(Tour::find((int) $tour_id))) {
redirect('/tour/' . $tour_id);
}
Booking::deleteForUser((int) $tour_id, (int) $user_id);
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);
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');
}
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]);
redirect('/tour/' . $tour_id . '/edit');
}
private function canManageTour(?Tour $tour): bool
{
$user = Auth::user();
return $user !== null
&& $tour !== null
&& ($user->isAdmin() || (int) $user->id === (int) $tour->tour_guide_id);
}
}