<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use App\Service\Booking\BookingService;
use App\Service\Housekeeping\HousekeepingManager;
use App\Entity\Booking;
use App\Entity\Referer;
use App\Entity\Hotel;
use App\Entity\Housekeeper;
use App\Entity\Season;
use App\Entity\Room;
use App\Entity\Financial;
use App\Entity\Guest;
use App\Repository\HousekeeperRepository;
class DefaultController extends AbstractController
{
private $booking_repository;
public function __construct(
private EntityManagerInterface $entityManager,
private HousekeepingManager $housekeepingManager,
private HousekeeperRepository $housekeeperRepository,
private BookingService $bookingService,
) {
$this->booking_repository = $entityManager->getRepository(Booking::class);
$this->roomRepository = $entityManager->getRepository(Room::class);
}
public function index(): Response
{
$user = $this->getUser();
// Check for a valid user and necessary methods
if (!$user || !method_exists($user, 'getHotelUsers') || !method_exists($user, 'getRoomUsers')) {
// Handle this error case as you see fit, for example:
throw new \RuntimeException('Invalid user or missing methods.');
}
$properties = [
'admin' => [],
'hotel' => [],
'owner' => [],
'cleaning' => [],
];
foreach ($user->getHotelUsers() as $hotel_user) {
$this->assignPropertiesByRole($hotel_user, $properties, 'getHotel');
}
foreach ($user->getRoomUsers() as $room_user) {
$this->assignPropertiesByRole($room_user, $properties, 'getRoom');
}
return $this->render('default/index.html.twig', [
'properties' => $properties,
]);
}
public function search(Request $request){
$term = $request->get('term');
$user = $this->isGranted('ROLE_ADMIN') ? null : $this->getUser();
// Supposons que votre méthode searchByTerm renvoie un tableau de résultats
$bookings = $this->booking_repository->searchByTermAndUser($term, $user);
// Construire la réponse au format JSON
$response = [];
foreach ($bookings as $booking) {
$response[] = [
'id' => $booking->getId(), // Supposons que l'ID soit dans la propriété id
'date' => $booking->getArrival()->format('D d M Y'), // Formatage de la date selon vos besoins
'name' => (string) $booking->getGuest(), // Supposons que le nom soit dans la propriété name
];
}
return new JsonResponse($response);
}
public function hotelMenu($route): Response
{
$user = $this->getUser();
$hotels = $this->entityManager->getRepository(Hotel::class)->findByUser($user);
return $this->render('default/hotel_menu.html.twig', [
'hotels' => $hotels,
'route' => $route,
]);
}
public function myBooking(): Response
{
$user_id = $this->isGranted('ROLE_ADMIN') ? null : $this->getUser()->getId();
$arrival_list = $this->booking_repository->findByType('arrival', 'hotel', $user_id);
$departure_list = $this->booking_repository->findByType('departure', 'hotel', $user_id);
$in_progress_list = $this->booking_repository->findByType('in-progress', 'hotel', $user_id);
$next_list = $this->booking_repository->findByType('next', 'hotel', $user_id);
return $this->render('default/my_booking.html.twig', [
'arrival_list' => $arrival_list,
'departure_list' => $departure_list,
'in_progress_list' => $in_progress_list,
'next_list' => $next_list,
]);
}
public function cleaning(): Response
{
$user_id = $this->getUser()->getId();
$housekeepers = $this->housekeeperRepository->findMyHousekeeper($user_id);
return $this->render('default/cleaning.html.twig', [
'housekeepers' => $housekeepers,
]);
}
public function lastBooking(): Response
{
$user_id = $this->isGranted('ROLE_ADMIN') ? null : $this->getUser()->getId();
$last_bookings = $this->booking_repository->findMyLastBookings($user_id);
return $this->render('default/last_booking.html.twig', [
'last_bookings' => $last_bookings,
]);
}
public function owner(): Response
{
$user_id = $this->getUser()->getId();
$holidays = $this->booking_repository->findMyHolidays($user_id);
return $this->render('default/my_holiday.html.twig', [
'holidays' => $holidays,
]);
}
public function fetchDailyAndNextCleanings(): Response
{
$dailyCleanings = $this->booking_repository->findDailyCleanings($this->getUser());
$nextCleanings = $this->booking_repository->findNextCleanings($this->getUser());
return $this->render('default/daily_and_next_cleanings.html.twig', [
'dailyCleanings' => $dailyCleanings,
'nextCleanings' => $nextCleanings,
]);
}
public function termsConditions(): Response
{
return $this->render('default/terms_conditions.html.twig');
}
public function validateTermsConditions(): Response
{
return $this->render('default/validate_terms_conditions.html.twig');
}
public function blockNights(): Response
{
$userIsAvailable = $this->getUser()->getHotelUsers()->isEmpty() ? false : true;
return $this->render('default/_block-nights.html.twig', [
'userIsAvailable' => $userIsAvailable,
]);
}
public function blockNightsModal(Request $request): Response
{
if($this->isGranted('ROLE_ADMIN')){
$rooms = $this->roomRepository->findAll();
}else{
$rooms = $this->roomRepository->findByUser($this->getUser());
}
$form = $this->createFormBuilder()
->setAction($this->generateUrl('admin_block_nights_modal'))
->add('rooms', EntityType::class, [ 'label' => 'Chambre à bloquer', 'class' => Room::class, 'choice_label' => 'name', 'choices' => $rooms])
->add('arrival', null, [ 'label' => "Date d'arrivée" ])
->add('departure', null, [ 'label' => "Date de départ" ])
->add('save', SubmitType::class, [ 'label' => 'Bloquer' ])
->getForm();
$isCleaningAvailable = $this->isCleaningAvailable($rooms);
if($isCleaningAvailable){
$form->add('cleaning', ChoiceType::class, [
'label' => "Le service de ménage doit-il passer pour ce blocage?",
'choices' => [
'Oui' => true,
'Non' => false,
],
'expanded' => true, // Affiche les choix sous forme de boutons radio
'multiple' => false, // Assure qu'un seul choix peut être sélectionné
'data' => true,
]);
}
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$form_data = $form->getData();
$result = $this->bookingService->createBooking($form_data);
if($result){
$this->addFlash('success', "Vous avez correctement bloqué les nuits");
}else{
$this->addFlash('error', "Les dates sélectionnées ne sont pas disponible.");
}
return $this->redirectToRoute('admin_calendar_index');
}
return $this->render('default/_block-nights-modal.html.twig', [
'form' => $form->createView(),
'isCleaningAvailable' => $isCleaningAvailable,
]);
}
public function modify(HousekeepingManager $housekeepingManager){
$housekeepersOfTheDay = $this->housekeeperRepository->findAllDailyHousekeepers();
// On crée un tableau pour stocker les IDs des utilisateurs (User) déjà traités
$uniqueUsers = [];
$filteredHousekeepers = [];
foreach ($housekeepersOfTheDay as $housekeeper) {
$userId = $housekeeper->getCleaning()->getId(); // récupère l'ID de l'utilisateur (User)
if (!in_array($userId, $uniqueUsers)) {
$uniqueUsers[] = $userId; // Ajoute l'ID utilisateur au tableau des IDs uniques
$filteredHousekeepers[] = $housekeeper; // Ajoute le résultat filtré à la liste
}
}
foreach($filteredHousekeepers as $housekeeper){
$this->housekeepingManager->sendReminderToHousekeeper($housekeeper);
}
return new Response('ok');
}
private function assignPropertiesByRole($user, array &$properties, string $method): void
{
$roleMapping = [
'ROLE_ADMIN' => 'admin',
'ROLE_HOTEL' => 'hotel',
'ROLE_OWNER' => 'owner',
'ROLE_CLEANING' => 'cleaning',
];
foreach ($roleMapping as $role => $key) {
if (method_exists($user, 'hasRole') && $user->hasRole($role) && method_exists($user, $method)) {
$properties[$key][] = $user->$method();
}
}
}
private function getReferer(Booking $booking){
$referer_list = $booking->getHotel()->getReferers();
foreach($referer_list as $referer){
if(str_contains($booking->getOrigin(), $referer->getKeyword())){
return $referer;
}
}
return $this->entityManager->getRepository(Referer::class)->find(10);
}
private function isCleaningAvailable(array $rooms){
foreach($rooms as $room){
if(!$room->getRoomUsers()->isEmpty()){return true;}
}
return false;
}
}