1021 lines
34 KiB
PHP
1021 lines
34 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\PushSubscription;
|
||
use App\Models\Tour;
|
||
use App\Models\TourRoom;
|
||
use App\Models\TourMessage;
|
||
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,
|
||
]);
|
||
}
|
||
|
||
/** Jahreskalender, in dem alle Touren farblich markiert sind. */
|
||
public function calendar(): void
|
||
{
|
||
$currentYear = (int) date('Y');
|
||
$tourYears = Tour::years();
|
||
|
||
$firstYear = min(array_merge([$currentYear - 1], $tourYears));
|
||
$lastYear = max(array_merge([$currentYear + 1], $tourYears));
|
||
|
||
$requestedYear = input('jahr');
|
||
$selectedYear = $currentYear;
|
||
|
||
if (is_string($requestedYear) && ctype_digit($requestedYear)) {
|
||
$selectedYear = (int) $requestedYear;
|
||
}
|
||
|
||
$selectedYear = max($firstYear, min($lastYear, $selectedYear));
|
||
|
||
$toursByDay = [];
|
||
$tourCount = 0;
|
||
|
||
foreach (Tour::forYear($selectedYear) as $tour) {
|
||
$tourCount++;
|
||
|
||
// Mehrtägige Touren erscheinen an jedem Tag ihres Zeitraums.
|
||
foreach ($tour->days() as $date) {
|
||
$toursByDay[$date][] = $tour;
|
||
}
|
||
}
|
||
|
||
view('tour.calendar', [
|
||
'selectedYear' => $selectedYear,
|
||
'years' => range($firstYear, $lastYear),
|
||
'months' => $this->buildCalendarMonths($selectedYear, $toursByDay),
|
||
'todayDate' => today(),
|
||
'tourCount' => $tourCount,
|
||
]);
|
||
}
|
||
|
||
/** Enddatum aus dem Formular; null, wenn nichts angegeben wurde. */
|
||
private function endDateFromInput(): ?string
|
||
{
|
||
$value = trim((string) input('end_date'));
|
||
|
||
return $value === '' ? null : db_date($value);
|
||
}
|
||
|
||
/** Das Enddatum darf nicht vor dem Startdatum liegen. */
|
||
private function assertEndDate(): void
|
||
{
|
||
$start = trim((string) input('start'));
|
||
$end = trim((string) input('end_date'));
|
||
|
||
if ($start === '' || $end === '' || db_date($end) >= db_date($start)) {
|
||
return;
|
||
}
|
||
|
||
$_SESSION['_errors']['end_date'][] = 'Das Enddatum darf nicht vor dem Startdatum liegen.';
|
||
$_SESSION['_old'] = $_POST;
|
||
back();
|
||
}
|
||
|
||
/**
|
||
* Baut das Monatsraster (Montag als erster Wochentag) für den Jahreskalender.
|
||
*
|
||
* @param array<string, array<int, Tour>> $toursByDay
|
||
*/
|
||
private function buildCalendarMonths(int $year, array $toursByDay): array
|
||
{
|
||
$labels = ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli',
|
||
'August', 'September', 'Oktober', 'November', 'Dezember'];
|
||
|
||
$months = [];
|
||
|
||
foreach ($labels as $index => $label) {
|
||
$month = $index + 1;
|
||
$first = new \DateTimeImmutable(sprintf('%04d-%02d-01', $year, $month));
|
||
$daysInMonth = (int) $first->format('t');
|
||
$leadingBlanks = (int) $first->format('N') - 1;
|
||
|
||
$weeks = [];
|
||
$week = array_fill(0, $leadingBlanks, null);
|
||
|
||
for ($day = 1; $day <= $daysInMonth; $day++) {
|
||
$date = $first->setDate($year, $month, $day)->format('Y-m-d');
|
||
|
||
$week[] = [
|
||
'day' => $day,
|
||
'date' => $date,
|
||
'tours' => $toursByDay[$date] ?? [],
|
||
];
|
||
|
||
if (count($week) === 7) {
|
||
$weeks[] = $week;
|
||
$week = [];
|
||
}
|
||
}
|
||
|
||
if ($week !== []) {
|
||
$weeks[] = array_pad($week, 7, null);
|
||
}
|
||
|
||
$months[] = [
|
||
'label' => $label,
|
||
'weeks' => $weeks,
|
||
];
|
||
}
|
||
|
||
return $months;
|
||
}
|
||
|
||
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
|
||
{
|
||
$current = Auth::user();
|
||
|
||
if ($current === null || !$current->canCreateTours()) {
|
||
app_log('warning', 'Tour create denied', [
|
||
'role' => $current?->role,
|
||
]);
|
||
redirect('/tour');
|
||
}
|
||
|
||
$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
|
||
{
|
||
$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'),
|
||
'end_date' => input('end_date'),
|
||
'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|date',
|
||
'end_date' => 'date',
|
||
'deadline' => 'required|date',
|
||
'tour_guide_id' => 'required',
|
||
]);
|
||
|
||
$this->assertEndDate();
|
||
|
||
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')),
|
||
'end_date' => $this->endDateFromInput(),
|
||
'deadline' => db_date(input('deadline')),
|
||
'max_participants' => (int) (input('max_participants') ?: 5),
|
||
'is_cancelled' => (int) (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');
|
||
}
|
||
}
|
||
|
||
$this->notifyEvent($tour, false);
|
||
$this->postChatSystem((int) $tour->id, 'Die Tour wurde angelegt. Hier könnt ihr euch austauschen.');
|
||
|
||
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(),
|
||
]);
|
||
}
|
||
}
|
||
|
||
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;
|
||
|
||
$users = [];
|
||
foreach (Booking::forTour((int) $tour->id) as $booking) {
|
||
$user = User::find((int) $booking->user_id);
|
||
if ($user !== null) {
|
||
$users[] = $user;
|
||
}
|
||
}
|
||
|
||
$tourDays = $tour->durationDays();
|
||
$tourEnd = $tour->endDate();
|
||
|
||
// Vergangene Tour
|
||
if ($tourEnd !== null && $tourEnd < today()) {
|
||
$tour->start = german_date($tour->start);
|
||
$tour->end_date = $tour->isMultiDay() ? german_date((string) $tourEnd) : '';
|
||
$tour->deadline = german_date($tour->deadline);
|
||
|
||
view('tour.show_old', [
|
||
'tour' => $tour,
|
||
'days' => $tourDays,
|
||
'users' => $users,
|
||
'guide' => $guide,
|
||
'tourImages' => $tourImages,
|
||
'canManage' => $canManage,
|
||
'canChat' => $canChat,
|
||
'chatUnread' => $chatUnread,
|
||
]);
|
||
|
||
return;
|
||
}
|
||
|
||
$rooms = array_map(fn(array $row) => (object) $row, TourRoom::fetchRooms((int) $tour->id));
|
||
|
||
$tour->start = german_date($tour->start);
|
||
$tour->end_date = $tour->isMultiDay() ? german_date((string) $tourEnd) : '';
|
||
$tour->deadline = german_date($tour->deadline);
|
||
|
||
view('tour.show', [
|
||
'tour' => $tour,
|
||
'days' => $tourDays,
|
||
'users' => $users,
|
||
'guide' => $guide,
|
||
'tourImages' => $tourImages,
|
||
'rooms' => $rooms,
|
||
'canManage' => $canManage,
|
||
'canChat' => $canChat,
|
||
'chatUnread' => $chatUnread,
|
||
]);
|
||
}
|
||
|
||
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);
|
||
|
||
$tourEnd = $tour->endDate();
|
||
|
||
if ($tourEnd !== null && $tourEnd < today()) {
|
||
$tour->start = german_date($tour->start);
|
||
$tour->end_date = $tour->isMultiDay() ? german_date($tourEnd) : '';
|
||
$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->end_date = $tour->isMultiDay() ? german_date($tourEnd) : '';
|
||
$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();
|
||
$wasCancelled = (bool) $tour->is_cancelled;
|
||
|
||
validate([
|
||
'tour_id' => 'required',
|
||
'name' => 'required|min:3',
|
||
'start' => 'required|date',
|
||
'end_date' => 'date',
|
||
'deadline' => 'date',
|
||
]);
|
||
|
||
$this->assertEndDate();
|
||
|
||
// Nur Admins dürfen den Tour Guide ändern.
|
||
if ($current->isAdmin()) {
|
||
$guide = User::find((int) input('tour_guide_id'));
|
||
|
||
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;
|
||
}
|
||
|
||
$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('end_date') !== null) {
|
||
$tour->end_date = $this->endDateFromInput();
|
||
}
|
||
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 = 1;
|
||
} else {
|
||
$tour->is_cancelled = 0;
|
||
}
|
||
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');
|
||
}
|
||
|
||
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);
|
||
}
|
||
|
||
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);
|
||
$this->postChatSystem((int) $tour->id, $user->name . ' hat die Tour gebucht.');
|
||
$this->notifyGuideBooking($tour, $user->name, true);
|
||
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);
|
||
$roomId = (int) $room_id;
|
||
|
||
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.'
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
redirect('/tour/' . $tour_id . '/edit');
|
||
}
|
||
|
||
public function cancelBooking(string $tour_id): void
|
||
{
|
||
$tour = Tour::find((int) $tour_id);
|
||
$user = Auth::user();
|
||
|
||
if (!$this->canManageTour($tour)) {
|
||
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);
|
||
}
|
||
|
||
redirect('/tour');
|
||
}
|
||
|
||
public function cancelBookingAdmin(string $tour_id, string $user_id): void
|
||
{
|
||
$tour = Tour::find((int) $tour_id);
|
||
|
||
if (!$this->canManageTour($tour)) {
|
||
redirect('/tour/' . $tour_id);
|
||
}
|
||
|
||
$participant = User::find((int) $user_id);
|
||
$hadBooking = Booking::forUser((int) $tour_id, (int) $user_id) !== null;
|
||
|
||
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);
|
||
}
|
||
}
|
||
|
||
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.'
|
||
);
|
||
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);
|
||
|
||
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]);
|
||
|
||
$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.'
|
||
);
|
||
|
||
redirect('/tour/' . $tour_id . '/edit');
|
||
}
|
||
|
||
private function canManageTour(?Tour $tour): bool
|
||
{
|
||
return $tour !== null && Tour::canManage((int) $tour->id, Auth::user());
|
||
}
|
||
|
||
/** 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(),
|
||
]);
|
||
}
|
||
}
|
||
}
|