Files
myep/src/Controller/Booking/Create/IndexController.php
T

170 lines
6.7 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Controller\Booking\Create;
use App\BusProNet\XmlLoader\AgencyLoader;
use App\Exception\HotelNotFoundException;
use App\Exception\HotelNotInTravelException;
use App\Exception\NoRoomsAvailableException;
use App\Exception\TravelNotFoundException;
use App\Htmx\HxTrait;
use App\Service\BookingService;
use App\Service\BookingSummaryDataService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
/**
* Handles the initialization of new booking sessions.
*
* This controller provides a clean entry point for starting new booking flows
* without requiring random UID parameters. It creates fresh booking sessions
* and redirects to the first step of the booking process.
*/
class IndexController extends AbstractController
{
use HxTrait;
public function __construct(
private readonly BookingService $bookingService,
private readonly AgencyLoader $agencyLoader,
private readonly BookingSummaryDataService $summaryDataService,
) {
}
/**
* Initializes a fresh booking session and redirects to the login page.
*
* This endpoint provides a clean way to start the booking flow with just
* dateId and hotelId parameters. It clears any existing booking session,
* creates a fresh BookingDto, and redirects to the login page where users
* can authenticate (for prepopulation) or continue as guest.
*
* Optionally accepts an agency code parameter. If provided and valid, the
* corresponding agency ID is stored in the booking. If not provided or invalid,
* defaults to agency code '0001'.
*/
#[Route(
path: '/bookings/create/{dateId}/{hotelId}',
name: 'app_booking_create_init',
requirements: ['dateId' => '\d+', 'hotelId' => '\d+']
)]
public function init(Request $request, int $dateId, int $hotelId): Response
{
try {
// Clear any existing booking session to ensure fresh start
$this->bookingService->clearBookingSession($request);
// Determine agency ID from optional query parameter
$agencyId = $this->resolveAgencyId($request->query->get('agency'));
// Store optional return URL in session (defaults to main EP site)
$this->bookingService->storeReturnUrl($request, $request->query->get('r'));
// Create fresh booking session with the provided parameters
$bookingDto = $this->bookingService->startFreshBooking($request, $dateId, $hotelId, $agencyId);
// Warm the CMS cache early so data is available on the login page
$this->summaryDataService->getCmsDataForProduct(
$bookingDto->travel->productCode,
$bookingDto->travel->hotel?->code
);
// Redirect to login page (optional authentication before Step 1)
return $this->redirectToRoute('app_login');
} catch (TravelNotFoundException) {
throw $this->createNotFoundException(sprintf('Travel not found for date ID %d', $dateId));
} catch (HotelNotFoundException) {
throw $this->createNotFoundException(sprintf('Hotel not found for hotel ID %d', $hotelId));
} catch (HotelNotInTravelException) {
throw $this->createNotFoundException(sprintf('Hotel ID %d is not available for travel ID %d', $hotelId, $dateId));
} catch (NoRoomsAvailableException) {
throw $this->createNotFoundException('No rooms available for this travel.');
}
}
/**
* Resolves the agency ID from the provided agency code.
*
* If the code is null or the agency is not found, returns the default agency ID.
*
* @param string|null $agencyCode The agency code from the request parameter
*
* @return int|null The agency ID, or null if default agency not found
*/
private function resolveAgencyId(?string $agencyCode): ?int
{
// Use default agency if no code provided
if (null === $agencyCode || '' === trim($agencyCode)) {
$defaultAgency = $this->agencyLoader->loadDefault();
return $defaultAgency?->id;
}
// Try to find agency by provided code
$agency = $this->agencyLoader->loadByCode($agencyCode);
// Fall back to default agency if code not found
if (null === $agency) {
$defaultAgency = $this->agencyLoader->loadDefault();
return $defaultAgency?->id;
}
return $agency->id;
}
/**
* Cancels the active booking session and returns to the appropriate page.
*
* This endpoint allows users to exit the booking flow at any time by
* clearing the booking session data and redirecting them appropriately:
* - Logged-in users: redirected to account dashboard
* - Guest users: redirected to the return URL (stored during booking init)
*/
#[Route('/bookings/cancel', name: 'app_booking_cancel')]
public function cancel(Request $request): Response
{
if (Request::METHOD_POST === $request->getMethod()) {
// Get return URL before clearing session (for guest users)
$returnUrl = $this->bookingService->getReturnUrl($request);
// Clear the booking session
$this->bookingService->clearBookingSession($request);
// Clear the security target path to prevent redirect loop after login
// Without this, logging in after cancel would redirect back to a stale booking URL
$request->getSession()->remove('_security.main.target_path');
// Redirect to account dashboard if logged in, otherwise to return URL
if (null !== $this->getUser()) {
$this->addFlash('info', 'Buchung abgebrochen.');
return $this->redirectToRoute('app_account');
}
// Use htmxRedirect for cross-origin safety (returnUrl may be external)
return $this->htmxRedirect($request, $returnUrl);
}
return $this->render('booking/create/modal_cancel.html.twig');
}
/**
* Displays user-friendly error messages for booking initialization failures.
*
* This endpoint provides a centralized location for displaying booking errors
* with appropriate error messages and guidance for users.
*/
#[Route('/bookings/create/error', name: 'app_booking_create_error')]
public function error(Request $request): Response
{
return $this->render('booking/create/error.html.twig', [
'returnUrl' => $this->bookingService->getReturnUrl($request),
]);
}
}