<?php
namespace App\Controller\SejourHotel;
use App\Service\Generale;
use App\Service\WSCMS;
use App\Service\WSEspaceAffilie;
use App\Service\WSSejourHotel;
use App\Service\ExceptionService;
use APY\BreadcrumbTrailBundle\BreadcrumbTrail\Trail;
use SebastianBergmann\CodeCoverage\RuntimeException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface as Session;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\String\Slugger\SluggerInterface;
/**
* @Route("/hotel")
*/
class IndexController extends AbstractController
{
public function __construct(Generale $service, WSCMS $cms, WSSejourHotel $sejourHotel, ExceptionService $exceptionService)
{
$this->service = $service;
$this->cms = $cms;
$this->sejourHotel = $sejourHotel;
$this->exceptionService = $exceptionService;
}
/**
* @Route("/source-typeahead-ville-hotel", name="source_typeahead_ville_hotel")
* @Route("/search-ville-hotel", name="search_ville_hotel")
*/
public function sourceTypeaheadVilleHotel(WSSejourHotel $sejourHotel, Request $request): Response
{
$listCityHotel = $sejourHotel->ListCityHotel([
'Keywords' => $_GET['Keywords'],
'maxItem' => $_GET['maxItem'],
'onlySearchCity' => $_GET['onlySearchCity']
]);
if ($request->get('_route') == 'search_ville_hotel')
return new JsonResponse($listCityHotel);
return new JsonResponse($listCityHotel['ListCityHotel']);
}
/**
* @Route("/all-hotel/{ville}/{hotel}",
* options={"expose"=true},
* name="all_hotel",defaults={"ville":"tous","hotel":"tous"})
*/
public function getAllHotel($ville, $hotel, WSCMS $WSCMS): Response
{
$hotels = $WSCMS->Hotel()['Hotels'];
$etiquettes = $WSCMS->HotelEtiquette()['Etiquettes'];
$hotels = array_map(function ($hotel) use ($etiquettes) {
$hotel['etiquettes'] = isset($etiquettes['etiquettes'][$hotel['id']]) ? $etiquettes['etiquettes'][$hotel['id']] : [];
$hotel['etiquettesSaison'] = isset($etiquettes['etiquettesSaison'][$hotel['id']]) ? $etiquettes['etiquettesSaison'][$hotel['id']] : [];
$hotel['etiquettesEmplacement'] = isset($etiquettes['etiquettesEmplacement'][$hotel['id']]) ? $etiquettes['etiquettesEmplacement'][$hotel['id']] : [];
return $hotel;
}, $hotels);
if ($ville != 'tous')
$hotels = array_filter($hotels, function ($h) use ($ville) {
return $h['ville'] == $ville;
});
if ($hotel != 'tous')
$hotels = array_filter($hotels, function ($h) use ($hotel) {
return ($h['hotel'] == $hotel or in_array($h['id'], explode('-', $hotel)));
});
return new JsonResponse(array_values($hotels));
}
/**
* @Route("/ajax-availability",
* name="sejour_hotel_ajax_availability")
*/
public function availabilityHotel(WSSejourHotel $sejourHotel): Response
{
$searchParams = json_decode(base64_decode($_GET['HotelSearch']), true);
if (file_exists('../var/site-en-maintenance.php') and ($nbr_iteration = (include '../var/site-en-maintenance.php')['nbrIterationSearchHotel']) > 0)
return new JsonResponse($sejourHotel->MultipleHotelSearch($searchParams, $nbr_iteration));
return new JsonResponse($sejourHotel->HotelSearch($searchParams));
}
/**
* @Route("/tarifs-hotel-journalier/{hotel}",
* options={"expose"=true},
* name="tarifs_hotel_journalier")
*/
public function TarifsHotelJournalier($hotel, WSSejourHotel $sejourHotel, WSCMS $WSCMS): Response
{
$tarif = $sejourHotel->TarifsHotelJournalier($hotel);
if (isset($tarif['HotelSearch'][0]['Price'])) {
$tarif = $tarif['HotelSearch'][0];
return new JsonResponse([
'min_arrangement' => $tarif['min_arrangement'],
'etiquettes' => isset($tarif['etiquettes']) ? $tarif['etiquettes'] : [],
'etiquettesSaison' => isset($tarif['etiquettesSaison']) ? $tarif['etiquettesSaison'] : []
]);
}
$etiquettes = $WSCMS->HotelEtiquette()['Etiquettes'];
return new JsonResponse([
'min_arrangement' => null,
'etiquettes' => $etiquettes['etiquettes'][$hotel] ?? [],
'etiquettesSaison' => $etiquettes['etiquettesSaison'][$hotel] ?? []
]);
}
/**
* @Route("/calendrier/{hotel}/{fromDate}/{toDate}",
* name="calendrier")
*/
public function calendrier(WSSejourHotel $WSSejourHotel, $hotel, $fromDate, $toDate): Response
{
$calendrier = $WSSejourHotel->HotelCalendar([
"Hotel" => intval($hotel),
"FromDate" => $fromDate,
"ToDate" => $toDate,
"Stock" => true,
"StopSale" => true,
"MinStay" => true,
"Retrocession" => true,
])['Calendar'];
return new JsonResponse($calendrier);
}
public function tarifDispo(WSSejourHotel $sejourHotel, WSEspaceAffilie $affilie, $product, WSCMS $WSCMS, Trail $trail, Session $session, Request $request, SluggerInterface $slugger): Response
{
$Request = json_decode(base64_decode($_POST['BookingCreation']), true);
if (isset($Request['Request']))
$Request = $Request['Request'];
if ($request->files->get('fichier') != null) {
$uniqid = sha1(uniqid(mt_rand(), TRUE));
foreach ($request->files->get('fichier') as $i => $file)
$_POST['file-passeport'][] = [
'nom' => "$i-$uniqid.{$file->guessExtension()}",
'ordre' => 0,
'base64' => [
'contents' => base64_encode(file_get_contents($file->getPathName())),
'originalName' => $file->getClientOriginalName(),
'size' => $file->getSize(),
'mimeType' => $file->getMimeType()
],
'nomOrigine' => $file->getClientOriginalName(),
'taille' => '',
'width' => getimagesize($file)[0],
'height' => getimagesize($file)[1]
];
}
if (isset($_POST['file-passeport']))
$Request['HotelBooking']['file-passeport'] = $_POST['file-passeport'];
/*if (!$Request['HotelBooking']['PreBooking'])
foreach ($Request['HotelBooking']['Rooms'] as &$room)
foreach ($room['Pax'] as &$pax)
foreach ($pax as &$p)
if ($p['Name'] == '')
$p['Name'] = $Request['HotelBooking']['Client']['Name'];*/
if (isset($_POST['montant-cote-client'])) {
$montantCoteClient = $_POST['montant-cote-client'];
$devise = $session->get('devise');
$deviseAgence = $session->get('devise-agence');
if ($devise['code'] != $deviseAgence['code'])
$montantCoteClient = ($devise['tndToDevise'] ? $montantCoteClient / $devise['montant'] : $montantCoteClient * $devise['montant']);
$Request['HotelBooking']['ClientAmount'] = $montantCoteClient;
}
if (isset($_POST['solde-points-de-fidelite']))
$Request['HotelBooking']['PointsDeFidelite'] = $affilie->SoldePointsdeFideliteAgence()["Solde"];
$BookingCreation = $sejourHotel->BookingCreation($Request);
if (isset($BookingCreation['Erreur'])) {
$BookingCreation['Error'] = $BookingCreation['Erreur'];
unset($BookingCreation['Erreur']);
}
if ($session->get('devise')['code'] != $session->get('devise-agence')['code'])
$Request['HotelBooking']['Currency'] = $session->get('devise')['code'];
if ($WSCMS->ConfigFrontOffice()['ConfigFrontOffice']['HOTEL']['EDIT_PAY_AT_HOTEL'] == 'oui')
$Request['HotelBooking']['PayAtHotel'] = !isset($BookingCreation['Error']) ? $BookingCreation['BookingCreation']['PayAtHotel'] : 0;
$trail->add($product == "hotel" ? 'Liste Hôtels' : 'Liste Appartements', $product == "hotel" ? 'sejour_hotel_availability' : 'sejour_appartement_availability', $session->get('last_route_params.sejour_hotel_availability', []));
if (isset($Request['name_hotel']))
$trail->add($Request['name_hotel'], $product == "hotel" ? 'details_hotel' : 'details_appartement', $Request['params_route_details_hotel']);
elseif (!isset($BookingCreation['Error']))
$trail->add($BookingCreation['BookingCreation']['Hotel']['Name'], 'details_hotel', [
'id' => $BookingCreation['BookingCreation']['Hotel']['Id'],
'slug' => $slugger->slug($BookingCreation['BookingCreation']['Hotel']['Name'])->lower(),
'checkin' => $BookingCreation['BookingCreation']['CheckIn'],
'nuitees' => (new \DateTime($BookingCreation['BookingCreation']['CheckIn']))->diff(new \DateTime($BookingCreation['BookingCreation']['CheckOut']))->d,
'city' => $BookingCreation['BookingCreation']['Hotel']['City']['Id'],
'source' => $BookingCreation['BookingCreation']['Source'],
]);
if ($Request['HotelBooking']['PreBooking'] and isset($BookingCreation['BookingCreation']['Token'])) {
$Request['HotelBooking']['Token'] = $BookingCreation['BookingCreation']['Token'];
}
if (!$Request['HotelBooking']['PreBooking'] and !isset($BookingCreation['Error'])) {
$paymentOnline = $BookingCreation['BookingCreation']['PaymentOnline'];
$idbook = $BookingCreation['BookingCreation']['Id'];
$route_confir = $this->generateUrl($product == "hotel" ? 'confirmation_sejour' : 'confirmation_appartement', ['Paiement' => $paymentOnline ? 'EnLigne' : 'Agence', 'id' => $idbook,], 0);
$url_echec = $this->generateUrl('echec_sejour', [], 0);
if (isset($Request['name_hotel'])) {
$BookingCreation['params_route_details_hotel'] = $Request['params_route_details_hotel'];
$BookingCreation['name_hotel'] = $Request['name_hotel'];
}
$session->set('BookingDetails#' . $idbook, $BookingCreation);
if ($paymentOnline)
return $this->redirect("{$this->service->domaineBack()}/payment-electronique/2/{$idbook}/SHT?url_succes=$route_confir&url_echec=$url_echec&configPayement={$Request['HotelBooking']['ConfigurationPayement']}");
return $this->redirect($route_confir);
}
$BookingCreation['ConfigurationPayement'] = $WSCMS->ConfigurationPayement()['ConfigurationPayement'];
$BookingCreation['Request'] = $Request;
$Solde = $affilie->SoldePointsdeFideliteAgence()["Solde"];
$BookingCreation['Solde'] = $Solde;
$BookingCreation['BookingCreation']['Solde'] = $Solde;
if ($request->isXmlHttpRequest())
return new JsonResponse($BookingCreation);
if (isset($BookingCreation['Error'])) {
// Créer une exception et l'enregistrer
$errorException = new \Exception($BookingCreation['Error']);
$recordedException = $this->exceptionService->recordException($errorException);
return $this->render('bundles/TwigBundle/Exception/error.html.twig', [
'title' => "Une erreur est survenue lors du traitement de votre demande",
'message' => $BookingCreation['Error'],
'recordedException' => $recordedException
]);
}
return $this->render($this->service->checkCustomTemplate('SejourHotel/tarif-dispo.html.twig'), $BookingCreation);
}
public function confirmation($id, WSSejourHotel $sejourHotel, Trail $trail, $product, Session $session, SluggerInterface $slugger, Request $request): Response
{
if ($request->get('_route') != "confirmation_sejour_custom")
try {
return $this->redirect($this->generateUrl('confirmation_sejour_custom', array_merge($request->get('_route_params'), $_GET)));
} catch (\Exception $exception) {
}
if ($request->get('_route') != "confirmation_appartement_custom")
try {
return $this->redirect($this->generateUrl('confirmation_appartement_custom', array_merge($request->get('_route_params'), $_GET)));
} catch (\Exception $exception) {
}
if (isset($_GET['id']))
$id = $_GET['id'];
$BookingDetails = $sejourHotel->BookingDetails(["Booking" => $id, "dev" => false, "DisableClientVerification" => true]);
$BookingDetails['BookingCreation'] = $BookingDetails['Booking'];
unset($BookingDetails['Booking']);
if (isset($BookingDetails['BookingCreation']['DetailsPayement']['Success'])) {
$this->addFlash('success', $BookingDetails['BookingCreation']['DetailsPayement']['Success']);
unset($BookingDetails['BookingCreation']['DetailsPayement']['Success']);
} elseif (isset($BookingDetails['BookingCreation']['DetailsPayement']['Echec']))
return $this->redirectToRoute('echec_sejour', [
'detailsPayement' => base64_encode(json_encode($BookingDetails['BookingCreation']['DetailsPayement']))
]);
$trail->add($product == "hotel" ? 'sejour_hotel_availability' : 'Liste Appartements', $product == "hotel" ? 'sejour_hotel_availability' : 'sejour_appartement_availability', $session->get('last_route_params.sejour_hotel_availability', []));
$trail->add($BookingDetails['BookingCreation']['Hotel']['Name'], 'details_hotel', [
'id' => $BookingDetails['BookingCreation']['Hotel']['Id'],
'slug' => $slugger->slug($BookingDetails['BookingCreation']['Hotel']['Name'])->lower(),
'checkin' => $BookingDetails['BookingCreation']['CheckIn'],
'nuitees' => (new \DateTime($BookingDetails['BookingCreation']['CheckIn']))->diff(new \DateTime($BookingDetails['BookingCreation']['CheckOut']))->d,
'city' => $BookingDetails['BookingCreation']['Hotel']['City']['Id'],
'source' => $BookingDetails['BookingCreation']['Source'],
]);
return $this->render($this->service->checkCustomTemplate('SejourHotel/confirmation.html.twig'), $BookingDetails);
}
public function echec($detailsPayement): Response
{
if ($detailsPayement) {
$detailsPayement = json_decode(base64_decode($detailsPayement), true);
$this->addFlash('danger', $detailsPayement['Echec']);
unset($detailsPayement['Echec']);
} else
$detailsPayement = [];
return $this->render($this->service->checkCustomTemplate('SejourHotel/echec.html.twig'), [
'detailsPayement' => $detailsPayement
]);
}
public function detailsHotel($id, $source, $city, $checkin, $product, WSSejourHotel $sejourHotel, Trail $trail, Session $session, Request $request): Response
{
if (new \DateTime("$checkin 23:59:59") < new \DateTime())
return $this->redirectToRoute('details_hotel', array_merge($request->get('_route_params'), $request->query->all(), ['checkin' => date('Y-m-d')]));
$hotels = $this->cms->Hotel($product == 'appartement', false)['Hotels'];
$hotelsBySlug = array_column($hotels, null, 'hotel');
$_route_params = $request->get('_route_params');
if ($request->get('_route') != "details_hotel_custom") {
try {
$villesById = array_column($this->cms->Ville()['Villes'], null, 'id');
$hotelsById = array_column($hotels, null, 'id');
$nameCity = "~";
if (isset($villesById[$_route_params['city']]))
$nameCity = $villesById[$_route_params['city']]['ville'];
if (isset($hotelsById[$_route_params['id']]))
$nameCity = $hotelsById[$_route_params['id']]['ville'];
if (isset($hotelsBySlug[$_route_params['slug']]))
$nameCity = $hotelsBySlug[$_route_params['slug']]['ville'];
$customUrl = $this->generateUrl('details_hotel_custom', array_merge($_route_params, ['nameCity' => $nameCity]));
return $this->redirect($customUrl, 301);
} catch (\Exception $exception) {
}
}
if (isset($_GET['id']))
$id = $_GET['id'];
if ($id == '~') {
$id = $hotelsBySlug[$_route_params['slug']]['id'];
//$city = $hotelsBySlug[$_route_params['slug']]['ville_id'];
}
$trail->add($product == "hotel" ? 'Liste Hôtels' : 'Liste Appartements', $product == "hotel" ? 'sejour_hotel_availability' : 'sejour_appartement_availability', $session->get('last_route_params.sejour_hotel_availability', []));
$prm = ["Hotel" => $id, "Source" => $source == "~" ? "all" : $source];
if ($source != '~' && $city != '~')
$prm['XMLCity'] = $city;
$HotelDetail = $sejourHotel->HotelDetail($prm);
$params['HotelDetail'] = $HotelDetail['HotelDetail'];
$params['_destination'] = 'h-' . $HotelDetail['HotelDetail']['Id'];
$params['product'] = $product;
$params['id'] = $id;
if (isset($_POST['BookingCreation'])) {
$params['BookingDetails'] = json_decode(base64_decode($_POST['BookingCreation']), true);
$params['Request'] = $_POST['BookingCreation'];
}
return $this->render($this->service->checkCustomTemplate('SejourHotel/details-hotel.html.twig'), $params);
}
public function tarfJourFromFormulaireReservation($hotel, $product, Request $request, WSSejourHotel $sejourHotel)
{
$date = $request->get('date');
$begin = new \DateTime($date);
date_modify($begin, "first day of this month");
$end = new \DateTime($date);
date_modify($end, "first day of next month");
$session = $this->get('session');
$params = array(
'hotel' => $hotel,
'client' => null,
'dateDebut' => $begin->format('Y-m-d'),
'dateFin' => $end->format('Y-m-d'),
"product" => $product,
'devise' => $session->get('devise')['montant'],
"scale" => $session->get('devise')['scale']
);
$tarifJourFromformulaire = $sejourHotel->CalendrieHotel($params);
function getChambredouble($array)
{
$min = null;
foreach ($array as $k => $a) {
if (!is_null($min)) {
if ($a['accepte-double'] and $a['minPrix'] < $min['minPrix']) {
$min = $a;
}
} else {
$min = $a['accepte-double'] ? $a : null;
}
}
return $min;
}
$result = array();
foreach ($tarifJourFromformulaire['tarifbydays']['tarifs'] as $tarifbyday) {
$tarifs = isset($tarifbyday['promo']['minArrangement']) ? $tarifbyday['promo'] : $tarifbyday['standard'];
if (!is_null($tarifbyday['standard'])) {
$stopSales = $tarifbyday['stopSales']['standard'];
if (isset($tarifbyday['stopSales']['promo']))
$stopSales = array_merge($stopSales, $tarifbyday['stopSales']['promo']);
if (!empty($stopSales)) {
$arrinstopSales = [];
foreach ($stopSales as $stopSale) {
if ($stopSale['_end'] == $tarifbyday['dateDebut'])
$arrinstopSales = array_merge($arrinstopSales, $stopSale['arrangements']);
}
if (count($arrinstopSales) != 0) {
foreach ($tarifs['tab'] as $tab) {
if (!in_array($tab['id'], $arrinstopSales)) {
$minArr = ['id' => $tab['id'], 'code' => $tab['code']];
}
}
}
}
$item = [];
$id = getChambredouble($tarifs['tab_ch']);
if (is_null($id))
$id = current($tarifs['tab_ch'])['idChambre'];
$id = $id['idChambre'];
$tab_ch = $tarifs['tab_ch'][$id];
$minPrix = $tab_ch['minPrix'];
$minArr = $tab_ch['minArr'];
$isRetrocession = in_array($tarifbyday['dateDebut'], $tarifJourFromformulaire['tarifbydays']['delayRetrocessionDates']);
$item['arran'] = $minArr['id'];
$item['codeArr'] = $minArr['code'];
$item['jour'] = $tarifbyday['dateDebut'];
$item['stopSales'] = $tab_ch['stopSales'];
$item['surDemande'] = $tab_ch['surDemande'] or $tab_ch['minStay'] or $tab_ch['allotement'] <= 0 or $isRetrocession;
$item['tarifMin'] = number_format($minPrix, $session->get('devise')['scale']);
$item['isRetrocession'] = $isRetrocession;
$item['isStopSales'] = ($minPrix == 0);
$result[] = $item;
}
}
return new JsonResponse(array('tarifjour' => $result, 'stopsales' => []));
}
public function searchHotel($ville, $hotel, $product, $hotelMonde, Request $request): Response
{
if (!$this->service->hasModule('sejour')) {
$this->addFlash('danger', 'Produit sans licence');
return $this->render('bundles/TwigBundle/Exception/error404.html.twig');
}
if (isset($_SERVER['ROUTE_ACCUEIL']) and $_SERVER['ROUTE_ACCUEIL'] == 'details_hotel')
return $this->redirectToRoute('details_hotel', array_merge(json_decode($_SERVER['PARAMS_ROUTE_ACCUEIL'], true), [
'source' => $request->get('source'),
'city' => $request->get('ville'),
'checkin' => $request->get('checkin'),
'nuitees' => $request->get('nuitees'),
'rooms' => $request->get('rooms')
]));
if (($destination = $request->get('destination', 'all')) === "all") {
if (!$hotelMonde)
$villes = $this->cms->Ville()['Villes'];
else
$villes = $this->sejourHotel->ListCityHotel([
'Keywords' => $ville,
'onlySearchCity' => true
])['ListCityHotel'];
if ($idVille = $request->get('idVille'))
$ville = array_column($villes, null, 'id')[$idVille]['ville'];
$search_recommended = explode('###', $this->cms->ConfigFrontOffice()['ConfigFrontOffice']['HOTEL']['SEARCH_RECOMMENDED']);
$search_recommended = (count($search_recommended) > 1 ? $search_recommended[1] : $search_recommended[0]);
if ($ville == "all") {
if (($key = array_search($search_recommended, array_column($villes, 'name'))) !== false)
$destination = 'v-' . $villes[$key]['id'];
} else {
$villes = array_filter($villes, function ($item) use ($ville) {
return $item['ville'] == $ville;
});
if (!empty($villes))
$destination = 'v-' . current($villes)['id'];
}
if (!isset($destination) and $hotel == 'tous')
$hotel = $search_recommended;
if ($hotel != 'tous') {
if (!$hotelMonde)
$hotels = $this->cms->Hotel($product == 'appartement')['Hotels'];
else
$hotels = $this->sejourHotel->ListCityHotel([
'Keywords' => $hotel,
'onlySearchCity' => false
])['ListCityHotel'];
$hotels = array_filter($hotels, function ($item) use ($hotel) {
return $item['hotel'] == $hotel;
});
if (!empty($hotels))
$destination = 'h-' . current($hotels)['id'];
elseif (($key = array_search($search_recommended, array_column($hotels, 'name'))) !== false)
$destination = 'h-' . $hotels[$key]['id'];
}
}
return $this->render($this->service->checkCustomTemplate("SejourHotel/availability/availability.html.twig"), [
'_destination' => $destination !== "all" ? $destination : 'v-',
'product' => $product,
'hotelSearchOnlyDetails' => $_SERVER['HOTEL_SEARCH_ONLY_DETAILS']
]);
}
}