<?php
namespace App\Controller;
use App\Entity\ProduitThalasso;
use App\Entity\TypeBar;
use App\Entity\Chambre;
use App\Entity\Tag;
use App\Entity\CategorieThalasso;
use App\Entity\Regime;
use App\Entity\Supplement;
use App\Entity\CmsPage;
use App\Entity\CmsPageBlockComposantItems;
use App\Entity\Reservation;
use App\Entity\ReservationCadeau;
use App\Model\Axepta;
use App\Entity\ReservationChambre;
use App\Entity\ReservationSupplement;
use App\Entity\ReservationSoins;
use App\Entity\Curiste;
use App\Entity\ReservationCure;
use App\Entity\ReservationEnfant;
use App\Entity\ReservationParticipant;
use App\Entity\TypeLit;
use App\Entity\TypeArrangement;
use App\Entity\Pays;
use App\Entity\Programme;
use App\Entity\ReservationCodePromo;
use App\Entity\DispoChambre;
use App\Entity\DispoSupplement;
use App\Entity\DispoProduit;
use App\Entity\CodePromo;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Service\FrontService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Knp\Bundle\SnappyBundle\Snappy\Response\PdfResponse;
use Knp\Snappy\Pdf;
use Symfony\Component\HttpKernel\KernelInterface;
use Swift_Attachment;
use App\Service\BookingService;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mailer\Transport;
use Symfony\Component\DependencyInjection\ParameterBag\ContainerBagInterface;
class BookingApiController extends AbstractController
{
private $frontService;
private $em;
private $params;
private $translator;
public $Your_HMAC = "G]a8!5FyBq3?f6_KRp7(*Mw4Pb9=[Hx2";
public $Your_CRYPTKEY = "r*7R=Db2w6Y_)z8W";
public $Your_MERCHANTID = "BNP_MIRAMAR_ECOM_FR_EUR_t";
public $TEST_PAYMODE = false;
public $mode3dsv2 = false;
private $session;
private $requestStack;
public function __construct(FrontService $frontService, SessionInterface $session, EntityManagerInterface $em, TranslatorInterface $translator, RequestStack $requestStack, ContainerBagInterface $params)
{
$this->frontService = $frontService;
$this->em = $em;
$this->translator = $translator;
$this->session = $session;
$this->requestStack = $requestStack;
$this->params = $params;
//get test mode from parameters
if ($this->params->get('TEST_PAYMODE') == "true")
$this->TEST_PAYMODE = true;
if (isset($_SERVER['SERVER_NAME']) && str_contains($_SERVER['SERVER_NAME'], 'digitz.dev'))
$this->TEST_PAYMODE = true;
if (!$this->TEST_PAYMODE) {
$this->Your_HMAC = "6z(JD9t_7r=R]3NaEc4)8!qGoC*5Z[2j";
$this->Your_CRYPTKEY = "c(4MZ9o)_L8yw!Y2";
$this->Your_MERCHANTID = "BNP_MIRAMAR_ECOM_FR_EUR";
$this->mode3dsv2 = true;
} else {
//Environnement de Test 3DSV2 miramar
$this->Your_HMAC = "G]a8!5FyBq3?f6_KRp7(*Mw4Pb9=[Hx2";
$this->Your_CRYPTKEY = "r*7R=Db2w6Y_)z8W";
$this->Your_MERCHANTID = "BNP_MIRAMAR_ECOM_FR_EUR_t";
//Environnement de Test 3DSV2 demo BNP
/*$this->Your_HMAC = "4n!BmF3_?9oJ2Q*z(iD7q6[RSb5)a]A8";
$this->Your_CRYPTKEY = "Tc5*2D_xs7B[6E?w";
$this->Your_MERCHANTID = "BNP_DEMO_AXEPTA";
$this->mode3dsv2 = true;*/
}
}
/**
* @Route("/bookapi/api-search-params/{lang}")
*/
public function getSearchParams($lang = 'fr', $selected_params = [])
{
// $selected_params = [
// "type_bar" => "2",
// "date_start" => "01/06/2021",
// "adults" => "1",
// "children" => "1",
// "duration" => "1",
// "pageSize" => 10,
// "page" => 1
// ];
$mode_residence = $this->frontService->getResidenceMode();
$selected_params = $this->session->get('search_params');
if (empty($selected_params) and $this->session->get('search_params')) {
$selected_params = $this->session->get('search_params');
}
$setsitems = [];
# get type bars with there items
$type_bars = $this->em->getRepository(TypeBar::class)->getTypeBar($lang);
$selected = [];
foreach ($type_bars as $tb_key => $type_bar) {
$set_val = [];
$to_show = false;
if ($type_bar['id'] == $this->getParameter('thalasso_avec_hebergement_id')) {
$set_val = ["calendar", "nights", "program"];
$to_show = true;
} elseif ($type_bar['id'] == $this->getParameter('thalasso_sans_hebergement_id')) {
$type_bar['nom_type_bar'] = "Thalasso & SPA";
$set_val = ["calendar", "persons", "type"];
$to_show = true;
} elseif ($type_bar['id'] == $this->getParameter('hotel_seul_id')) {
$set_val = ["calendar", "adults", "children", "duration"];
$to_show = true;
}
if ($to_show == true) {
if ($type_bar['id'] == 2 && $this->frontService->getResidenceMode())
$selected[] = ['id' => $type_bar['id'], 'label' => $this->translator->trans("filtre_bar.titre"), 'set' => $set_val];
else
$selected[] = ['id' => $type_bar['id'], 'label' => $type_bar['nom_type_bar'], 'set' => $set_val];
}
}
$selected[] = ['id' => "Idées cadeaux", 'label' => $this->translator->trans("filtre_bar.cadeau"), 'set' => ["persons", "cures", "price-steps"]];
# calendar
if (isset($selected_params['date_start'])) {
$selected_calendar = $selected_params['date_start'];
} else {
$selected_calendar = date("Y-m-d");
}
$setsitems[] = ['item' => 'calendar', 'icon' => "calendar", 'text' => $this->translator->trans("filtre_bar.arrivee"), 'value' => $selected_calendar];
#
# adults
if (isset($selected_params['adults'])) {
$selected_adulte = ['id' => $selected_params['adults'], "text" => $selected_params['adults']];
} else {
$selected_adulte = ['id' => "1", "text" => "1"];
}
//$selected_adulte=$selected_adulte["id"];
$setsitems[] = [
'item' => 'adults', 'text' => $this->translator->trans("filtre_bar.adults"), 'icon' => "adult", 'value' => $selected_adulte,
'values' => [
['id' => "1", "text" => "1"],
['id' => "2", "text" => "2"],
['id' => "3", "text" => "3"],
['id' => "4", "text" => "4"],
['id' => "5", "text" => "5"],
['id' => "6", "text" => "6"],
]
];
# children
if (isset($selected_params['children'])) {
$selected_child = ['id' => $selected_params['children'], "text" => $selected_params['children']];
} else {
$selected_child = ['id' => "0", "text" => "0"];
}
$setsitems[] = [
'item' => 'children', 'icon' => "child", 'text' => $this->translator->trans("filtre_bar.children"), 'value' => $selected_child,
'values' => [
['id' => "0", "text" => "0"],
['id' => "1", "text" => "1"],
['id' => "2", "text" => "2"],
['id' => "3", "text" => "3"],
]
];
# person
if (isset($selected_params['persons'])) {
$selected_persons = ['id' => $selected_params['persons'], "text" => $selected_params['persons']];
} else {
$selected_persons = ['id' => "1", "text" => "1"];
}
$setsitems[] = [
'item' => 'persons', 'icon' => "adult", 'text' => $this->translator->trans("filtre_bar.nbrpersonnes"), 'value' => $selected_persons,
'values' => [
['id' => "1", "text" => "1"],
['id' => "2", "text" => "2"],
]
];
# duration hôtel
if (!$mode_residence) {
$duration_values = [
['id' => "1", "text" => "1 " . $this->translator->trans("filtre_bar.night")],
['id' => "2", "text" => "2 " . $this->translator->trans("filtre_bar.nights")], ['id' => "3", "text" => "3 " . $this->translator->trans("filtre_bar.nights")],
['id' => "4", "text" => "4 " . $this->translator->trans("filtre_bar.nights")], ['id' => "5", "text" => "5 " . $this->translator->trans("filtre_bar.nights")],
['id' => "6", "text" => "6 " . $this->translator->trans("filtre_bar.nights")],
['id' => "7", "text" => "7 " . $this->translator->trans("filtre_bar.nights")], ['id' => "8", "text" => "8 " . $this->translator->trans("filtre_bar.nights")],
['id' => "9", "text" => "9 " . $this->translator->trans("filtre_bar.nights")], ['id' => "10", "text" => "10 " . $this->translator->trans("filtre_bar.nights")],
['id' => "11", "text" => "11 " . $this->translator->trans("filtre_bar.nights")], ['id' => "12", "text" => "12 " . $this->translator->trans("filtre_bar.nights")],
['id' => "13", "text" => "13 " . $this->translator->trans("filtre_bar.nights")], ['id' => "14", "text" => "14 " . $this->translator->trans("filtre_bar.nights")],
['id' => "15", "text" => "15 " . $this->translator->trans("filtre_bar.nights")],
];
$selected_duration = ['id' => "1", "text" => "1 " . $this->translator->trans("filtre_bar.night")];
} else {
$duration_values = [
['id' => "2", "text" => "2 " . $this->translator->trans("filtre_bar.nights")], ['id' => "3", "text" => "3 " . $this->translator->trans("filtre_bar.nights")],
['id' => "4", "text" => "4 " . $this->translator->trans("filtre_bar.nights")], ['id' => "5", "text" => "5 " . $this->translator->trans("filtre_bar.nights")],
['id' => "6", "text" => "6 " . $this->translator->trans("filtre_bar.nights")],
['id' => "7", "text" => "7 " . $this->translator->trans("filtre_bar.nights")], ['id' => "8", "text" => "8 " . $this->translator->trans("filtre_bar.nights")],
['id' => "9", "text" => "9 " . $this->translator->trans("filtre_bar.nights")], ['id' => "10", "text" => "10 " . $this->translator->trans("filtre_bar.nights")],
['id' => "11", "text" => "11 " . $this->translator->trans("filtre_bar.nights")], ['id' => "12", "text" => "12 " . $this->translator->trans("filtre_bar.nights")],
['id' => "13", "text" => "13 " . $this->translator->trans("filtre_bar.nights")], ['id' => "14", "text" => "14 " . $this->translator->trans("filtre_bar.nights")],
['id' => "15", "text" => "15 " . $this->translator->trans("filtre_bar.nights")],
];
$selected_duration = ['id' => "2", "text" => "2 " . $this->translator->trans("filtre_bar.nights")];
}
if (isset($selected_params['duration'])) {
$selected_duration = [];
foreach ($duration_values as $duration_val) {
if ($duration_val['id'] == $selected_params['duration']) {
//$selected_duration = ['id' => $selected_params['duration'], "text" => $selected_params['duration'] . " " . $this->translator->trans("filtre_bar.nights")];
$selected_duration = ['id' => $selected_params['duration'], "text" => $this->translator->trans("filtre_bar.night.selected", ['%count%' => $selected_params['duration']])];
break;
}
}
}
$setsitems[] = ['item' => 'duration', 'icon' => "moon", 'text' => $this->translator->trans("filtre_bar.stay"), 'value' => $selected_duration, 'values' => $duration_values];
# nigths
$nigths_values = [
['id' => "6", "text" => $this->translator->trans("filtre_bar.longsejoursix")],
['id' => "4", "text" => $this->translator->trans("filtre_bar.longsejourquatre")],
['id' => "3", "text" => $this->translator->trans("filtre_bar.courtsejour")],
];
$selected_nigths = ['id' => "1", "text" => $this->translator->trans("filtre_bar.courtsejour")];
if (isset($selected_params['nigths'])) {
$selected_nigths = [];
foreach ($nigths_values as $nigth_vals) {
if ($nigth_vals['id'] == $selected_params['nigths']) {
$selected_nigths = ['id' => $selected_params['nigths'], "text" => $nigth_vals['text']];
break;
}
}
}
$setsitems[] = ['item' => 'nights', 'icon' => "moon", 'text' => $this->translator->trans("filtre_bar.stay"), 'value' => $selected_nigths, 'values' => $nigths_values];
# nigths cadeau
$duration_cadeau_values = [
['id' => "1", "text" => "1 " . $this->translator->trans("filtre_bar.night")],
['id' => "2", "text" => "2 " . $this->translator->trans("filtre_bar.nights")], ['id' => "3", "text" => "3 " . $this->translator->trans("filtre_bar.nights")],
['id' => "4", "text" => "4 " . $this->translator->trans("filtre_bar.nights")], ['id' => "5", "text" => "5 " . $this->translator->trans("filtre_bar.nights")],
['id' => "6", "text" => "6 " . $this->translator->trans("filtre_bar.nights")],
['id' => "7", "text" => "7 " . $this->translator->trans("filtre_bar.nights")], ['id' => "8", "text" => "8 " . $this->translator->trans("filtre_bar.nights")],
['id' => "9", "text" => "9 " . $this->translator->trans("filtre_bar.nights")], ['id' => "10", "text" => "10 " . $this->translator->trans("filtre_bar.nights")],
['id' => "11", "text" => "11 " . $this->translator->trans("filtre_bar.nights")], ['id' => "12", "text" => "12 " . $this->translator->trans("filtre_bar.nights")],
['id' => "13", "text" => "13 " . $this->translator->trans("filtre_bar.nights")], ['id' => "14", "text" => "14 " . $this->translator->trans("filtre_bar.nights")],
['id' => "15", "text" => "15 " . $this->translator->trans("filtre_bar.nights")],
];
$selected_duration_cadeau = ['id' => "1", "text" => "1 " . $this->translator->trans("filtre_bar.night")];
if (isset($selected_params['duration-cadeau'])) {
$selected_duration_cadeau = [];
foreach ($duration_cadeau_values as $duration_val) {
if ($duration_val['id'] == $selected_params['duration-cadeau']) {
$selected_duration_cadeau = ['id' => $selected_params['duration-cadeau'], "text" => $selected_params['duration-cadeau'] . " " . $this->translator->trans("filtre_bar.nights")];
break;
}
}
}
$setsitems[] = ['item' => 'duration-cadeau', 'icon' => "moon", 'text' => "Nuits", 'value' => $selected_duration_cadeau, 'values' => $duration_cadeau_values];
# cures
$cures = $this->em->getRepository(Tag::class)->getTags($id = false, $lang, 2);
foreach ($cures as $tg_key => $cure) {
$cures_vals[] = ['id' => 'tag-' . $cure['id'], 'text' => $cure['label']];
}
$cure_selected_val = $cures_vals[0];
if (isset($selected_params['cures'])) {
foreach ($cures_vals as $cure) {
if ($selected_params['cures'] == $cure['id']) {
$cure_selected_val = ['id' => $cure['id'], 'text' => $cure['text']];
break;
}
}
}
$setsitems[] = ['item' => 'cures', 'text' => $this->translator->trans("filtre_bar.objectifs"), 'icon' => "pool-stairs", 'value' => $cure_selected_val, 'values' => $cures_vals];
# price-steps
$price_steps_vals = [
['id' => 1, "text" => $this->translator->trans("filtre_bar.budget.nondefini")],
['id' => 2, "text" => $this->translator->trans("filtre_bar.budget.entre0et150")],
['id' => 3, "text" => $this->translator->trans("filtre_bar.budget.entre150et300")],
['id' => 4, "text" => $this->translator->trans("filtre_bar.budget.plus300")],
];
$price_steps_selected_val = $price_steps_vals[0];
if (isset($selected_params['price-steps'])) {
foreach ($price_steps_vals as $price_step) {
if ($selected_params['price-steps'] == $price_step['id']) {
$price_steps_selected_val = ['id' => $price_step['id'], 'text' => $price_step['text']];
break;
}
}
}
$setsitems[] = [
'item' => 'price-steps', 'text' => $this->translator->trans("filtre_bar.prix"), 'icon' => "euro", 'value' => $price_steps_selected_val,
'values' => $price_steps_vals
];
# get tags
$tags = $this->em->getRepository(Tag::class)->getTags($id = false, $lang, 9);
$tag_holder = [];
$tag_holder['item'] = 'program';
$tag_holder['icon'] = 'pool-stairs';
$tag_holder['text'] = $this->translator->trans("filtre_bar.objectifs");
$tag_holder['value'] = ['id' => "tous", "text" => $this->translator->trans("filtre_bar.tous")];
$tag_holder['values'][] = ['id' => "tous", "text" => $this->translator->trans("filtre_bar.tous")];
foreach ($tags as $tg_key => $tag) {
if (isset($selected_params['program']) and $tag['id'] == $selected_params['program']) {
$tag_holder['value'] = ['id' => $tag['id'], "text" => $tag['label']];
}
$tag_holder['values'][] = ['id' => $tag['id'], "text" => $tag['label']];
}
$setsitems[] = $tag_holder;
unset($tags);
unset($tag_holder);
# get categorie thalasso
$tags = $this->em->getRepository(Tag::class)->getTags($id = false, $lang, 2);
foreach ($tags as $tg_key => $tag) {
$type_sejour_vals[] = ['id' => 'tag-' . $tag['id'], 'text' => $tag['label']];
}
$type_sejour_selected_val = $type_sejour_vals[0];
if (isset($selected_params['type'])) {
foreach ($type_sejour_vals as $type_sejour) {
if ($selected_params['type'] == $type_sejour['id']) {
$type_sejour_selected_val = ['id' => $type_sejour['id'], 'text' => $type_sejour['text']];
break;
}
}
}
$categ_prod_holder = [];
$categ_prod_holder['item'] = 'type';
$categ_prod_holder['icon'] = 'pool-stairs';
$categ_prod_holder['text'] = $this->translator->trans("filtre_bar.categories");
$categ_prod_holder['value'] = $type_sejour_selected_val;
$categ_prod_holder['values'] = $type_sejour_vals;
$setsitems[] = $categ_prod_holder;
#
return new JsonResponse(['selected' => $selected, 'setsitems' => $setsitems]);
}
/**
* @Route("/api-recherche", name="api_search")
*
*/
public function getSearchResult($searchParams = [], $lang = 'fr')
{
// if(isset($_POST)){
// dump($_POST);exit;
// }
# init
$params = $searchParams;
// reformat date
if (isset($params['date_start'])) {
$params['date_start'] = date("Y-m-d", strtotime(str_replace('/', '-', $params['date_start'])));
}
# verify type_bar
if (!empty($params)) {
if (in_array($params['type_bar'], [$this->getParameter('thalasso_avec_hebergement_id'), $this->getParameter('thalasso_sans_hebergement_id')])) {
# prepare params that need to be sent to get the data
# extract date_arrivee_exigee from date_start
# Arrivée le même jour' => '0',
if ($params['date_start'] == date("Y-m-d")) {
$params['date_arrivee_exigee'] = "0";
}
# Arrivée la veille' => '-1',
else {
$params['date_arrivee_exigee'] = "-1";
}
#
if ($params['type_bar'] == $this->getParameter('thalasso_avec_hebergement_id')) {
# type tarif
$params['tbl_tarif'] = 'tarifProduitThalassoChambres';
# type hebergement
$params['hebergement'] = "'avec', 'avec_sans_hebergement'";
} else {
# type tarif
$params['tbl_tarif'] = 'tarifProduitThalassos';
# type hebergement
$params['hebergement'] = "'sans'";
}
# get date end from range between (nights) and date start
if (isset($params['nights']) and intval($params['nights']) != 0) {
$nbr_nights = intval($params['nights']);
}
if (isset($params['duration']) and intval($params['duration']) != 0) {
$nbr_nights = intval($params['duration']);
}
if (isset($nbr_nights)) {
# nbr nuit to jours
$nbr_jours = intval($nbr_nights);
# date end val
$date_end = new \DateTime($params['date_start']);
$date_end->modify('+' . $nbr_jours . ' days');
$params['date_end'] = $date_end->format("Y-m-d");
} else {
$nbr_nights = 1;
}
if ($params['type_bar'] == $this->getParameter('thalasso_sans_hebergement_id')) {
$date_end = new \DateTime($params['date_start']);
$date_end->modify('+1 days');
$params['date_end'] = $date_end->format("Y-m-d");
$nbr_nights = 1;
}
# get nbr days between start and end
$params['nbr_duration'] = $nbr_nights;
#
# count data
/*$data_count = $this->em->getRepository(ProduitThalasso::class)->getApiSearchProducts($params, $lang, $count_data = true);
$max_page = ceil($data_count / $params['pageSize']);*/
$max_page = 10;
# get data
if (false or intval($params['page']) > $max_page) {
$jsn_res = ['response' => ['type_bar' => $this->getParameter('thalasso_avec_hebergement'), 'id_type_bar' => $params['type_bar'], 'type_result' => 'produit', 'msg' => "La page numéro '" . $params['page'] . "' n'existe pas. Le numéro de page maximal est '" . $max_page . "'"], 'status' => 204];
} else {
$result = $this->em->getRepository(ProduitThalasso::class)->getApiSearchProducts($params, $lang, $count_data = false, $params['pageSize'], $params['page']);
// return new JsonResponse($result);
# integrate media to the result
$result = $this->integrateMedia($result, 'ProduitThalasso', 'id_produit', $lang);
# type bar
if ($params['type_bar'] == $this->getParameter('thalasso_avec_hebergement_id')) {
$type_bar = $this->getParameter('thalasso_avec_hebergement');
} elseif ($params['type_bar'] == $this->getParameter('thalasso_sans_hebergement_id')) {
$type_bar = $this->getParameter('thalasso_spa');
}
#
$jsn_res = [
'response' => [
'arrival' => date("d-m-Y", strtotime($params['date_start'])),
'departure' => date("d-m-Y", strtotime($params['date_end'])),
'type_bar' => $type_bar,
'id_type_bar' => $params['type_bar'],
'type_result' => 'produit',
'results' => $result
],
'status' => 200
];
}
#
} elseif ($params['type_bar'] == $this->getParameter('hotel_seul_id')) {
# prepare params that need to be sent to get the data
# get date end from range between (nights) and date start
if (isset($params['nights']) and intval($params['nights']) != 0) {
$nbr_nights = intval($params['nights']);
}
if (isset($params['duration']) and intval($params['duration']) != 0) {
$nbr_nights = intval($params['duration']);
}
if (isset($nbr_nights) and intval($nbr_nights) != 0) {
# nbr nuit to jours
$nbr_jours = intval($nbr_nights);
# date end val
$date_end = new \DateTime($params['date_start']);
$date_end->modify('+' . $nbr_jours . ' days');
$params['date_end'] = $date_end->format("Y-m-d");
} else {
$nbr_nights = 1;
}
# get nbr days between start and end
$params['nbr_duration'] = $nbr_nights;
#
# count data
$mode_residence = $this->frontService->getResidenceMode();
/*$data_count = $this->em->getRepository(Chambre::class)->getApiSearchChambres($params, $lang, $count_data = true, 10, 1, $mode_residence);
# get data for group if data_count = 0
// if($data_count == 0){
// # remove children and adultes capisity from the params
// unset($params['children']);
// unset($params['adults']);
// # check availability
// $data_count = $this->em->getRepository(Chambre::class)->getApiSearchChambres($params, $lang, $count_data = true);
// # change type results to chambres_group
// $type_results = 'chambres_group';
// #
// }else{
// $type_results = 'chambre';
// }
# get data
$max_page = ceil($data_count / $params['pageSize']);*/
$max_page = 10;
if (false or intval($params['page']) > $max_page) {
$jsn_res = ['response' => ['type_bar' => $this->getParameter('hotel_seul'), 'id_type_bar' => $params['type_bar'], 'type_result' => 'chambre', 'msg' => "La page numéro '" . $params['page'] . "' n'existe pas. Le numéro de page maximal est '" . $max_page . "'"], 'status' => 204];
} else {
$result = $this->em->getRepository(Chambre::class)->getApiSearchChambres($params, $lang, $count_data = false, $params['pageSize'], $params['page'], $mode_residence);
# integrate media to the result
$result = $this->integrateMedia($result, 'Chambre', 'id', $lang);
#
$jsn_res = [
'response' => [
'arrival' => date("d-m-Y", strtotime($params['date_start'])),
'departure' => date("d-m-Y", strtotime($params['date_end'])),
'type_bar' => $this->getParameter('hotel_seul'),
'id_type_bar' => $params['type_bar'],
'type_result' => 'chambre',
'results' => $result
],
'status' => 200
];
}
#
} elseif ($params['type_bar'] == "Idées cadeaux") {
# type tarif
$params['tbl_tarif'] = 'tarifProduitThalassos';
# type hebergement
$params['hebergement'] = "'sans'";
# init date start date end
$params['date_start'] = date("Y-m-d");
$date_end = new \DateTime($params['date_start']);
$date_end->modify('+1 days');
$params['date_end'] = $date_end->format("Y-m-d");
# init type bar
$type_bar = $params['type_bar'];
# init type bar
$params['type'] = $params['cures'];
$result = $this->em->getRepository(ProduitThalasso::class)->getApiSearchCadeau($params, $lang, $count_data = false, $params['pageSize'], $params['page']);
// return new JsonResponse($result);
# integrate media to the result
$result = $this->integrateMedia($result, 'ProduitThalasso', 'id_produit', $lang);
# type bar
if ($params['type_bar'] == $this->getParameter('thalasso_avec_hebergement_id')) {
$type_bar = $this->getParameter('thalasso_avec_hebergement');
} elseif ($params['type_bar'] == $this->getParameter('thalasso_sans_hebergement_id')) {
$type_bar = $this->getParameter('thalasso_spa');
}
#
//unset results not in rangeprice
$min = 0;
$max = 10000000;
if ($params['price-steps'] == 2) {
$min = 0;
$max = 150;
}
if ($params['price-steps'] == 3) {
$min = 150;
$max = 300;
}
if ($params['price-steps'] == 4) {
$min = 300;
$max = 10000000;
}
foreach ($result as $key => $res) {
if (!(intval($res["price"]) >= $min && intval($res["price"]) <= $max))
unset($result[$key]);
}
$jsn_res = [
'response' => [
'arrival' => date("d-m-Y", strtotime($params['date_start'])),
'departure' => date("d-m-Y", strtotime($params['date_end'])),
'type_bar' => $type_bar,
'id_type_bar' => $params['type_bar'],
'type_result' => 'produit',
'results' => $result
],
'status' => 200
];
} else {
$jsn_res = ['response' => ['msg' => 'in dev phase'], 'status' => 501];
}
} else {
$jsn_res = ['response' => ['msg' => 'redirect'], 'status' => 404];
}
return new JsonResponse(array_merge($jsn_res, ['params' => $params]));
#
}
public function integrateMedia($data, $class_name, $id_name, $lang, $media_format = 'search')
{
$result = $data;
/*echo "<pre>";
var_dump($result);
echo "</pre>";
die;*/
# loop through result
foreach ($result as $item_key => $item) {
# get item-object by id
$item_obj = $this->em->getRepository('App\Entity\\' . $class_name)->findOneById($item[$id_name]);
# get item-media loop througth the media
$cover_exist = false;
$media_data = null;
$getter_name = 'get' . $class_name . 'Photos';
$nbr_media = $item_obj->$getter_name()->count() - 1;
foreach ($item_obj->$getter_name() as $media_key => $media) {
# get cover if not exist get last media image
if ($media->getCover()) {
$media_obj = $media;
} elseif ($nbr_media == $media_key and !$cover_exist) {
$cover_exist = true;
$media_obj = $media;
} else {
$media_obj = false;
}
# get media url
if ($media_obj) {
$media_data = $this->frontService->getMediaPublicUrl($media->getSonataImage(), $media_format, $media->getTranslation('alt_img', $lang));
unset($media_data['placement']);
break;
}
#
}
$result[$item_key]['image'] = $media_data;
# rform duration if exist
if (isset($item['duration']) && isset($item['duree_jours']) && isset($item['duree_nuitee'])) {
$result[$item_key]['duration'] = (intval($item['duree_jours'])) . " " . $this->translator->trans("result.hotelSeul.jours") . " " . intval($item['duree_nuitee']) . " " . $this->translator->trans("result.hotelSeul.nuits");
} else
$result[$item_key]['duration'] = "";
# rform price if exist
if (isset($item['tarif_ids']) and $item['tarif_ids'] != null) {
// split tarif
$nbr_tarif = count(explode(',', $result[$item_key]['tarif_ids']));
$prix_total = 0;
// loop through tarif hoolder and store prices
foreach (explode(',', $result[$item_key]['tarif_ids']) as $trf_prix) {
$prix_total = intval(explode('|', $trf_prix)[1]) + $prix_total;
}
$result[$item_key]['price'];
//
$result[$item_key]['price'] = $prix_total . "€";
$result[$item_key]['realPrice'] = ($prix_total / $nbr_tarif) . "€";
//fix for supplement and soin
if ($media_format == "soinsreservation")
$result[$item_key]['price'] = $result[$item_key]['realPrice'];
}
# this is for products
// list:'<ul><li>prix par personne, base 2 curiste(s) en chambre "Passerelle"</li><li>demi pension</li></ul>',
$list_holder = "";
if (isset($item['id_produit'])) {
if (isset($item['chambre_data']) and isset($item['regime_data'])) {
$list_holder .= '<ul data-chambres = "' . $item['chambre_data'] . '" data-regime = "' . $item['regime_data'] . '" >';
# get chambre data [id, label, icon]
if ($item['chambre_data'] != null) {
$chambre_data = [];
if ($item['chambre_data'] != null) {
$chambr_trf_holder = [];
$chmbr_label_holder = []; // prevent duplicated chambre name
foreach (explode(',', $item['chambre_data']) as $index => $chambre) {
# get min produitChambre price
foreach (explode(',', $item['tarif_ids']) as $key => $tarif_id) {
// (($chambre[0], $tarif_id[0]) tarif_id) and (chambre[1] is chmbr-id ) and ( $tarif_id is prix id)
if (explode('|', $chambre)[0] == explode('|', $tarif_id)[0]) {
if (!isset($chambr_trf_holder['chmbr-' . explode('|', $chambre)[1]])) {
$chambr_trf_holder['chmbr-' . explode('|', $chambre)[1]] = 0;
}
$chambr_trf_holder['chmbr-' . explode('|', $chambre)[1]] += floatval(number_format(explode('|', $tarif_id)[1], 2));
}
}
# get chambre label (explode('|', $chambre)[2] ==> chambre label)
/* if(in_array(explode('|', $chambre)[2], $chmbr_label_holder)){
continue;
}else{
$chmbr_label_holder[] = explode('|', $chambre)[2];
}
$chmbr_label = explode('|', $chambre)[2];
$chmbr_id = explode('|', $chambre)[1];
$list_holder .= "<li >";
$list_holder .= "static[prix par personne, base 2 curiste(s) en chambre] ";
$list_holder .= '"'.$chmbr_label.'"';
$list_holder .= "</li>";*/
#
}
# get min tarif price
$result[$item_key]['price'] = min(array_values($chambr_trf_holder)) . "€";
}
}
# get regime data
if ($item['regime_data'] != null) {
$regime_names = [];
$list_holder .= "<li >";
if ($item['regime_data'] != null)
foreach (explode(',', $item['regime_data']) as $regimekey => $regime) {
$regime_names[] = explode('|', $regime)[1];
}
$list_holder .= implode(', ', $regime_names) . "</li>";
}
#
$list_holder .= "</ul>";
# generate link url
# get page slug by product id
$page_route_item = $this->em->getRepository(CmsPageBlockComposantItems::class)->GetSlugByProduct($item['id_produit'], $lang);
$page_route_cmspage = $this->em->getRepository(CmsPage::class)->GetSlugByProduct($item['id_produit'], $lang);
$page_route_signature = $this->generateUrl('process_choice_signature', ['idp' => $item['id_produit']]);
$page_route_signature_gift = $this->generateUrl('process_choice_signature_gift', ['idp' => $item['id_produit'], "g" => 1]);
# case page by category
$page_route = "";
if (array_key_exists('id_cat', $item)) {
if (in_array($item['id_cat'], [3, 4, 5]))
$page_route = $page_route_signature;
if (in_array($item['id_cat'], [1]))
$page_route = $this->generateUrl('render_mlc_pages', ['_locale' => $lang, 'slug' => $page_route_item['content'], 'hostname' => $_SERVER['HTTP_HOST']]);
if (in_array($item['id_cat'], [2]))
$page_route = $this->generateUrl('render_mlc_pages', ['_locale' => $lang, 'slug' => $page_route_cmspage['content'], 'hostname' => $_SERVER['HTTP_HOST']]);
}
# generate link
if ($page_route != null) {
$result[$item_key]['link'] = ['title' => 'Réserver', 'to' => $page_route, 'togift' => $page_route_signature_gift];
} else {
$result[$item_key]['link'] = ['title' => 'Réserver', 'to' => $this->generateUrl('render_mlc_pages', ['slug' => "miramar-la-cigale", 'hostname' => $_SERVER['HTTP_HOST']])];
}
#
#
} else {
# generate link url
# get page slug by product id
$page_route_item = $this->em->getRepository(CmsPageBlockComposantItems::class)->GetSlugByProduct($item['id_produit'], $lang);
$page_route_cmspage = $this->em->getRepository(CmsPage::class)->GetSlugByProduct($item['id_produit'], $lang);
$page_route_signature = $this->generateUrl('process_choice_signature', ['idp' => $item['id_produit']]);
$page_route_signature_gift = $this->generateUrl('process_choice_signature_gift', ['idp' => $item['id_produit'], "g" => 1]);
# case page by category
$page_route = "";
if (array_key_exists('id_cat', $item)) {
if (in_array($item['id_cat'], [3, 4, 5]))
$page_route = $page_route_signature;
if (in_array($item['id_cat'], [1]))
$page_route = $this->generateUrl('render_mlc_pages', ['_locale' => $lang, 'slug' => $page_route_item['content'], 'hostname' => $_SERVER['HTTP_HOST']]);
if (in_array($item['id_cat'], [2]))
$page_route = $this->generateUrl('render_mlc_pages', ['_locale' => $lang, 'slug' => $page_route_cmspage['content'], 'hostname' => $_SERVER['HTTP_HOST']]);
}
# generate link
if ($page_route != null) {
$result[$item_key]['link'] = ['title' => 'Réserver', 'to' => $page_route, 'togift' => $page_route_signature_gift];
} else {
$result[$item_key]['link'] = ['title' => 'Réserver', 'to' => $this->generateUrl('render_mlc_pages', ['lang' => $lang, 'slug' => "miramar-la-cigale", 'hostname' => $_SERVER['HTTP_HOST']])];
}
#
#
}
# get duration data [label, icon]
$result[$item_key]['list'] = $list_holder;
# add details
$result[$item_key]['details'] = [
'title' => '',
'list' => '',
'description' => '',
'button' => [
'text' => '',
'to' => $this->generateUrl('render_mlc_recherche', ['lang' => $lang]),
]
];
}
# this is for chambre
if (isset($item['type_chmbr_id'])) {
# regime
$regime_names = [];
if (isset($item['regime_data'])) {
foreach (explode(',', $item['regime_data']) as $regimekey => $regime) {
$regime_names[] = ['id' => explode('|', $regime)[0], 'label' => explode('|', $regime)[1], 'value' => explode('|', $regime)[1]];
}
}
#nbr person options
$numoptions = ['adultes', 'enfants'];
$numoptions_holder = [];
foreach ($numoptions as $type_opts) {
$numoptions_holder[$type_opts] = [
'result' => intval($item['nbr_' . $type_opts]),
'min' => intval($item['min_' . $type_opts]),
'max' => intval($item['max_' . $type_opts])
];
}
// static
$item['stock_dispo'] = isset($item['stock_dispo']) ? $item['stock_dispo'] : 1;
$numoptions_holder['chambres'] = ['result' => 1, 'min' => 1, 'max' => min(explode(',', $item['stock_dispo']))];
//
# person
$result[$item_key]['person'] = $result[$item_key]['person'];
# form
$result[$item_key]['form'] = [
'action' => $this->generateUrl('render_mlc_reservation', ['_locale' => $lang]),
'numoptions' => $numoptions_holder,
'board' => $regime_names,
];
# generate link
$prices_val = ['realPrice' => $result[$item_key]['realPrice'], 'price' => $result[$item_key]['price']];
$result[$item_key]['chambre_data'] = array_merge($result[$item_key]['form'], $prices_val);
$result[$item_key]['link'] = ['text' => 'Réserver', 'to' => $this->generateUrl('render_mlc_reservation', ['_locale' => $lang])];
}
#
}
#
return $result;
}
public function getPensions()
{
// get pension base on
$regimes = $this->em->getRepository(Regime::class)->getRegime(null, $this->requestStack->getCurrentRequest()->getLocale());
return new JsonResponse($regimes);
}
public function getSuplementsForResrvation($date_start, $date_end, $chmbr_val = false)
{
// get supplement
$supps = $this->em->getRepository(Supplement::class)->getSupplementResrvation(['date_start' => $date_start, 'date_end' => $date_end], $this->requestStack->getCurrentRequest()->getLocale(), $count_data = false, $pageSize = 100, $page = 1, $chmbr_val);
if ($supps) {
$result = $this->integrateMedia($supps, 'Supplement', 'id', $this->requestStack->getCurrentRequest()->getLocale(), 'soinsreservation');
} else {
$result = [];
}
return new JsonResponse($result);
}
/**
* @Route("/api-get_cure_prods", name="get_products_ers")
*
*/
public function getProductsForResrvation($date_start, $date_end, $type = 'cures', $chmbr_val = false, $prod_val = false, $litemode = false)
{
// get pension base on
if ($type == 'soins') {
$context = "soinsreservation";
$params = ['hebergement' => "'sans'", 'type' => $this->getParameter('soins_id'), 'noCMS' => 1];
$params['tbl_tarif'] = 'tarifProduitThalassos';
} elseif ($type == 'soinsrituels') {
$context = "soinsreservation";
$params = ['hebergement' => "'sans'", 'type' => [$this->getParameter('soins_id'), $this->getParameter('rituel')], 'noCMS' => 1];
$params['tbl_tarif'] = 'tarifProduitThalassos';
} elseif ($type == 'cures') {
$type_cure = [$this->getParameter('cure_court_sejour'), $this->getParameter('cure_long_sejour')];
$context = "curesreservation";
$params = ['hebergement' => "'avec_sans_hebergement', 'avec'", 'type' => $type_cure];
$params['tbl_tarif'] = 'tarifProduitThalassoChambres';
} elseif ($type == 'soinsall') {
$context = "soinsreservation";
$params['tbl_tarif'] = 'tarifProduitThalassos';
}
elseif ($type == 'caresallgift') {
$context = "search";
$params = ['type' => array(3, 4, 5), 'noCMS' => 1, 'noDISPO' => 1, 'isgiftcare' => 1];
$params['tbl_tarif'] = 'tarifProduitThalassos';
}
elseif ($type == 'caresall') {
$context = "search";
$params = ['type' => array(3, 4, 5), 'noCMS' => 1, 'noDISPO' => 1];
$params['tbl_tarif'] = 'tarifProduitThalassos';
} else {
$params = ['type' => []];
$context = "curesreservation";
}
$date1 = new \DateTime($date_start);
$date2 = new \DateTime($date_end);
$nbr_duration = $date2->diff($date1)->format("%a");
if ($litemode)
$products = $this->em->getRepository(ProduitThalasso::class)->getApiSearchProductsLite(array_merge($params, ['nbr_duration' => $nbr_duration, 'date_start' => $date_start, 'date_end' => $date_end, 'chambre_val' => $chmbr_val, 'prod_val' => $prod_val]), $this->requestStack->getCurrentRequest()->getLocale());
else
$products = $this->em->getRepository(ProduitThalasso::class)->getApiSearchProducts(array_merge($params, ['nbr_duration' => $nbr_duration, 'date_start' => $date_start, 'date_end' => $date_end, 'chambre_val' => $chmbr_val, 'prod_val' => $prod_val]), $this->requestStack->getCurrentRequest()->getLocale());
$result = $this->integrateMedia($products, 'ProduitThalasso', 'id_produit', $this->requestStack->getCurrentRequest()->getLocale(), $context);
return new JsonResponse($result);
}
public function getRoomsForResrvation($adults, $children, $date_start, $date_end, $mode_residence = false, $mode_restrict_dispo = true)
{
$date1 = new \DateTime($date_start);
$date2 = new \DateTime($date_end);
$params['type_bar'] = $this->getParameter('hotel_seul_id');
$params['nbr_duration'] = $date2->diff($date1)->format("%a");
$params['date_end'] = $date_end;
$params['date_start'] = $date_start;
$params['adults'] = $adults;
$params['children'] = $children;
$chambres = $this->em->getRepository(Chambre::class)->getApiSearchChambres($params, $this->requestStack->getCurrentRequest()->getLocale(), false, 20, 1, $mode_residence, $mode_restrict_dispo);
$result = $this->integrateMedia($chambres, 'Chambre', 'id', $this->requestStack->getCurrentRequest()->getLocale(), $media_format = 'search');
return new JsonResponse($result);
}
/**
* @Route("/{_locale}/reservation/insertion", defaults={"_locale": "fr"}, name="new_reservation")
*
*/
public function newReservation($_locale, Request $req)
{
//verif session and redirect to homepage if lost
if ($this->verifRedirectSession())
return $this->verifRedirectSession();
# begin pages versions
#fr
$page_versions[] = array(
"to" => "/fr",
"value" => "fr",
"active" => ($_locale == "fr") ? true : false
);
#en
$page_versions[] = array(
"to" => "/en",
"value" => "en",
"active" => ($_locale == "en") ? true : false
);
# end pages versions
//get nrr
$pourcentage_nrr = 0;
$TotalTtcNrr = 0;
$arrhes_100 = 0;
$pourcentage_nrr = $this->session->get('nrr_toapply');
//Verify if user is logged else redirect to login
if ($this->isGranted('ROLE_USER') == true) {
//Get vars from session
$search_params = $this->session->get('search_params');
$selected_search = $this->session->get('selected_search');
$booking_cart = $this->session->get('booking_cart');
if (isset($booking_cart["tab_cures"])) {
$prd_id = $booking_cart["tab_cures"][0]["cure_id"];
} else {
$prd_id = 0;
}
// echo "<pre>";
// var_dump($prd_id);
// echo "</pre>";
// die;
//Detect envoi postal
$mt_envoi_postal = 0;
if ($booking_cart && array_key_exists("tab_curistes", $booking_cart)) {
foreach ($booking_cart["tab_curistes"] as $key => $curiste) {
if ($curiste["postal"] == 1)
$mt_envoi_postal += 10;
}
}
$this->session->set('mt_envoi_postal', $mt_envoi_postal);
//Get amounts
if (array_key_exists("isGiftCard", $booking_cart) && $booking_cart["isGiftCard"] == 1) {
$TotalSoins = $booking_cart["price"];
$TotalSejour = $booking_cart["price"];
$TotalSupplements = 0;
$TotalTtc = $booking_cart["price"] + $mt_envoi_postal;
$AccomptePourcentage = 30;
$TotalAccompte = $TotalTtc * $AccomptePourcentage / 100;
$AccomptePourcentage = 30;
$TotalAccompte_30 = $TotalTtc * $AccomptePourcentage / 100;
$AccomptePourcentage = 100;
$TotalAccompte_100 = $TotalTtc * $AccomptePourcentage / 100;
} else {
$produit_test = $this->em->getRepository(ProduitThalasso::class)->findOneById($prd_id);
if($produit_test && $produit_test->getArrhes100())
$arrhes_100 = $produit_test->getArrhes100();
$TotalSoins = $booking_cart["TotalSoins"];
$TotalSejour = $booking_cart["TotalSejour"];
$TotalSupplements = $booking_cart["TotalSupplements"];
$TotalTtc = $booking_cart["TotalTtc"] + $mt_envoi_postal;
$TotalAccompte = $TotalTtc;
$AccomptePourcentage = 30;
$TotalAccompte_30 = $TotalTtc * $AccomptePourcentage / 100;
$AccomptePourcentage = 100;
$TotalAccompte_100 = $TotalTtc * $AccomptePourcentage / 100;
}
# change arrhes_100 if promotion
$promotions_list = $this->session->get('promotions_list');
if ($promotions_list && is_object($promotions_list)) {
$promotions_list = get_object_vars($promotions_list);
if ($promotions_list && array_key_exists("message", $promotions_list) && $promotions_list["message"] != "" && $promotions_list["arrhes_100"] !== false) {
$arrhes_100 = $promotions_list["arrhes_100"];
}
}
if ($pourcentage_nrr > 0) {
$TotalTtcNrr = $TotalTtc * (1 - (intval($pourcentage_nrr) / 100));
} else {
$TotalTtcNrr = $TotalTtc;
}
}
//round amounts
$TotalTtc = round($TotalTtc, 0);
$TotalTtcNrr = round($TotalTtcNrr, 0);
$TotalAccompte = round($TotalAccompte, 0);
$TotalAccompte_30 = round($TotalAccompte_30, 0);
$TotalAccompte_100 = round($TotalAccompte_100, 0);
return $this->render(
'pages/akaru/reservations/paiement.html.twig',
array(
"_locale" => $_locale,
"TotalTtc" => $TotalTtc,
"TotalTtcNrr" => $TotalTtcNrr,
"TotalAccompte" => $TotalAccompte,
"TotalAccompte_30" => $TotalAccompte_30,
"TotalAccompte_100" => $TotalAccompte_100,
"product_id" => $prd_id,
"page_versions" => $page_versions,
"arrhes_100" => $arrhes_100
)
);
}
/**
* @Route("/{_locale}/api-pay-step1", name="api_pay_step1", defaults={"_locale": "fr"}, requirements={"_locale": "en|fr|de"})
*
*/
public function initPay(Request $request, MailerInterface $mailer, $_locale)
{
//verif session and redirect to homepage if lost
if ($this->verifRedirectSession())
return $this->verifRedirectSession();
//get posted data
$dataChoice = $request->request->all();
//detect envoi postal
$mt_envoi_postal = $this->session->get('mt_envoi_postal');
//Verify if user is logged else redirect to login
if ($this->isGranted('ROLE_USER') == true) {
//Get vars from session
$search_params = $this->session->get('search_params');
$selected_search = $this->session->get('selected_search');
$booking_cart = $this->session->get('booking_cart');
$id_res_cadeau = false;
$reservationCadeau = null;
if (array_key_exists("isGiftCard", $booking_cart) && $booking_cart["isGiftCard"] == 1) {
//Get amounts
$TotalSoins = $booking_cart["price"];
$TotalSejour = $booking_cart["price"];
$TotalSupplements = 0;
$TotalTtc = $booking_cart["price"] + $mt_envoi_postal;
$search_params["date_start"] = "Now";
$search_params["date_end"] = "Now";
$search_params["duration"] = 1;
$selected_search["total_adults"] = 1;
$selected_search["total_children"] = 0;
//insert reservation cadeau
$reservationCadeau = new ReservationCadeau();
/* echo "<pre>";
var_dump($booking_cart['tab_curistes']);
echo "</pre>";*/
$TokenCadeau = rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '=');
$reservationCadeau->setRefCadeau(""); //????
$reservationCadeau->setCiviliteBeneficiaire($booking_cart['tab_curistes'][0]['civilite_curiste']);
$reservationCadeau->setNomBeneficiaire($booking_cart['tab_curistes'][0]['nom_curiste']);
$reservationCadeau->setPrenomBeneficiaire($booking_cart['tab_curistes'][0]['prenom_curiste']);
$reservationCadeau->setDateNaissanceBeneficiaireText($booking_cart['tab_curistes'][0]['date_naissance_curiste']);
$reservationCadeau->setAdresse($booking_cart['tab_curistes'][0]['adresse']);
$reservationCadeau->setCompAdresse($booking_cart['tab_curistes'][0]['comp_adresse']);
$reservationCadeau->setCp($booking_cart['tab_curistes'][0]['cp']);
$reservationCadeau->setVille($booking_cart['tab_curistes'][0]['ville']);
$pay = $this->em->getRepository(Pays::class)->findOneById((int)$booking_cart['tab_curistes'][0]['pays_curiste']);
if ($pay)
$reservationCadeau->setPays($pay);
$reservationCadeau->setEmailBeneficiaire($booking_cart['tab_curistes'][0]['email_curiste']);
$reservationCadeau->setTelBeneficiaire($booking_cart['tab_curistes'][0]['tel1_curiste']);
$reservationCadeau->setNewsletterClient(1);
$reservationCadeau->setDestinataireEnvoi((int)$booking_cart['tab_curistes'][0]['beneficiaire']);
$reservationCadeau->setTypeEnvoi((int)$booking_cart['tab_curistes'][0]['postal']);
$reservationCadeau->setCommentaire($booking_cart['tab_curistes'][0]['comment_curiste']);
$reservationCadeau->setMessage($booking_cart['tab_curistes'][0]['message_curiste']);
$reservationCadeau->setTokenCadeau($TokenCadeau);
$reservationCadeau->setDateCadeau(new \DateTime("Now"));
$reservationCadeau->setDateFinCadeau(new \DateTime("Now"));
// Persist reservation
$this->em->persist($reservationCadeau);
// Flush reservation
$this->em->flush();
$id_res_cadeau = $reservationCadeau->getId();
//empty tab curiste
$booking_cart['tab_curistes'] = array();
} else {
//Get amounts
$TotalSoins = $booking_cart["TotalSoins"];
$TotalSejour = $booking_cart["TotalSejour"];
$TotalSupplements = $booking_cart["TotalSupplements"];
$TotalTtc = $booking_cart["TotalTtc"] + $mt_envoi_postal;
}
//fix temporaire
if (isset($booking_cart["tab_cures"])) {
$prd_id = $booking_cart["tab_cures"][0]["cure_id"];
} else {
$prd_id = 0;
}
$pourcentage_nrr = 0;
if ($dataChoice["accompte30"] == 1) {
$TotalAccompte = $TotalTtc * 30 / 100;
$AccomptePourcentage = 30;
$totalite = 0;
}
elseif ($dataChoice["accompte30"] == 2){
$TotalAccompte = $TotalTtc;
$AccomptePourcentage = 100;
$totalite = 1;
}
else {
$TotalAccompte = $TotalTtc;
$AccomptePourcentage = 100;
$totalite = 1;
//get nrr
$pourcentage_nrr = $this->session->get('nrr_toapply');
$TotalAccompte = $TotalAccompte * (1 - $pourcentage_nrr / 100);
}
//Get current user Id
$user_id = $this->getUser()->getId();
//Get Client / id
$client = $this->em->getRepository('App\Entity\Client')->findOneByUser($user_id);
//round amounts
$TotalTtc = round($TotalTtc, 0);
$TotalAccompte = round($TotalAccompte, 0);
// Create reservation
//Generate token
$token = rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '=');
//$ref resa
$ref = "BK-" . date("Ymd");
/*echo "<pre>";
var_dump($search_params);
echo "</pre>";
echo "<pre>";
var_dump($selected_search);
echo "</pre>";*/
$reservation = new Reservation();
$reservation->setTokenReservation($token);
$reservation->setClient($client);
$reservation->setRefReservation($ref);
$date_start = new \DateTime($search_params["date_start"]);
$reservation->setDateReservation($date_start);
$date_end = new \DateTime($search_params["date_end"]);
$reservation->setDateDepart($date_end);
$reservation->setDureeSejour($search_params["duration"]);
$reservation->setNbrParticipants($selected_search["total_adults"]);
$reservation->setNbrEnfants($selected_search["total_children"]);
$reservation->setTotalSoins($TotalSoins);
$reservation->setTotalSejour($TotalSejour);
$reservation->setTotalSupplements($TotalSupplements);
$reservation->setAccomptePourcentage($AccomptePourcentage);
$reservation->setTotalAccompte($TotalAccompte);
$reservation->setTotalTtc($TotalTtc);
$reservation->setTotalite($totalite);
$reservation->setValide(0);
$reservation->setPaye(0);
if (array_key_exists('comments', $booking_cart))
$reservation->setComment($booking_cart['comments']);
$reservation->setTauxNrr($pourcentage_nrr);
//verifier si reservation est offerte
$offert = $this->session->get('sisGift');
if ($offert == "true")
$offert = 1;
else
$offert = 0;
$reservation->setOffert($offert);
//verifier si une resevation avec accompagnant
if (array_key_exists('curiste-number', $booking_cart) && $booking_cart['curiste-number'] == "3")
$reservation->setAccompagnant(1);
$modecare = 0;
if (array_key_exists('numcares', $booking_cart) && array_key_exists('tab_participants', $booking_cart) && (count($booking_cart['tab_participants']) > 0 || (array_key_exists('tab_curistes', $booking_cart) && count($booking_cart['tab_curistes']) > 0)))
$modecare = 1;
$reservation->setCare($modecare);
//set part gift
if ($id_res_cadeau) {
$reservation->setChequecadeau(1);
$reservation->setReservationCadeau($reservationCadeau);
} else {
$reservation->setChequecadeau(0);
$reservation->setReservationCadeau(null);
}
// send mail when reservation is created_at
// Persist reservation
$this->em->persist($reservation);
// Flush reservation
$this->em->flush();
//get reservation id
$id_reservation = $reservation->getId();
// persisting multiple translations, assume default locale is EN
$repository = $this->em->getRepository('Gedmo\\Translatable\\Entity\\Translation');
//create linked objects
//1- rooms
if (array_key_exists('tab_rooms', $booking_cart))
foreach ($booking_cart['tab_rooms'] as $key => $room) {
//get objects
$chambre = $this->em->getRepository('App\Entity\Chambre')->findOneById($room["chambre_id"]);
$typelit = $this->em->getRepository('App\Entity\TypeLit')->findOneById($room["type_lit_id"]);
$regime = $this->em->getRepository('App\Entity\Regime')->findOneById($room["regime_id"]);
$typearrangement = $this->em->getRepository('App\Entity\TypeArrangement')->findOneById($room["type_arrangement_id"]);
$reservationChambre = new ReservationChambre();
$reservationChambre->setQteChambre($room["qte_chambre"]);
$reservationChambre->setMtChambreUnite($room["mt_chambre_unite"]);
$reservationChambre->setMtChambreTotal($room["mt_chambre_total"]);
$reservationChambre->setNomTypeLit("debug translation");
$reservationChambre->setNomTypeArrangement("debug translation");
$reservationChambre->setNomChambre("debug translation");
$reservationChambre->setNbrAdultes((int)$room["total_adults"]);
$reservationChambre->setNbrEnfants((int)$room["total_children"]);
$reservationChambre->setChambre($chambre);
$reservationChambre->setTypeLit($typelit);
$reservationChambre->setReservation($reservation);
$reservationChambre->setTypeArrangement($typearrangement);
$reservationChambre->setRegime($regime);
$reservation->addReservationChambre($reservationChambre);
$this->em->persist($reservationChambre);
$this->em->persist($reservation);
$this->em->flush();
//translate
/*$repository
->translate($reservationChambre, 'nom_type_lit', 'en', 'debug en')
->translate($reservationChambre, 'nom_type_arrangement', 'en', 'debug en');*/
}
//2- addons
if (array_key_exists('tab_addons', $booking_cart))
foreach ($booking_cart['tab_addons'] as $key => $addon) {
//get objects
$supplement = $this->em->getRepository('App\Entity\Supplement')->findOneById($addon["supplement_id"]);
$reservationsup = new ReservationSupplement();
$reservationsup->setNomSupplement("debug translation");
$reservationsup->setQteSupplement($addon["qte_supplement"]);
$reservationsup->setMtSupplementUnite($addon["mt_supplement_unite"]);
$reservationsup->setMtSupplementTotal($addon["mt_supplement_total"]);
$reservationsup->setReservation($reservation);
$reservationsup->setSupplement($supplement);
$this->em->persist($reservationsup);
$this->em->flush();
//translate
/*$repository
->translate($reservationsup, 'nom_supplement', 'en', 'debug en');*/
}
//3- cares
if (array_key_exists('tab_cares', $booking_cart))
foreach ($booking_cart['tab_cares'] as $key => $care) {
//get objects
$produit = $this->em->getRepository('App\Entity\ProduitThalasso')->findOneById($care["produit_thalasso_id"]);
//get beneficiaire en fonction des tab_participants ou tab_curistes
$beneficiaire = $client->getNomClient() . " " . $client->getPrenomClient();
$keybeneficiare = intval($care["beneficiaire_soin"]) - 1;
if (count($booking_cart['tab_participants']) > 0) {
if (array_key_exists($keybeneficiare, $booking_cart['tab_participants']))
$beneficiaire = $booking_cart['tab_participants'][$keybeneficiare]["nom_participant"] . " " . $booking_cart['tab_participants'][$keybeneficiare]["prenom_participant"];
}
if (count($booking_cart['tab_curistes']) > 0) {
$keybeneficiare = intval($care["beneficiaire_soin"]) - 1;
if (array_key_exists($keybeneficiare, $booking_cart['tab_curistes']))
$beneficiaire = $booking_cart['tab_curistes'][$keybeneficiare]["nom_curiste"] . " " . $booking_cart['tab_curistes'][$keybeneficiare]["prenom_curiste"];
}
$reservationsoin = new ReservationSoins();
$reservationsoin->setBeneficiaireSoin($beneficiaire);
$reservationsoin->setNomSoin("debug translation");
$reservationsoin->setQteSoin($care["qte_soin"]);
$reservationsoin->setMtSoinUnite($care["mt_soin_unite"]);
$reservationsoin->setMtSoinTotal($care["mt_soin_total"]);
$reservationsoin->setReservation($reservation);
$reservationsoin->setProduitThalasso($produit);
$this->em->persist($reservationsoin);
$this->em->flush();
//translate
/*$repository
->translate($reservationsup, 'nom_supplement', 'en', 'debug en');*/
}
//3- cares only case
if (array_key_exists('numcares', $booking_cart) && array_key_exists('tab_participants', $booking_cart) && count($booking_cart['tab_participants']) > 0)
foreach ($booking_cart['tab_cures'] as $key => $cure) {
//get objects
$produit = $this->em->getRepository('App\Entity\ProduitThalasso')->findOneById($cure["cure_id"]);
$prixunitsoin = $TotalTtc / (int)$booking_cart["numcares"];
$reservationsoin = new ReservationSoins();
$reservationsoin->setBeneficiaireSoin($booking_cart['tab_participants'][$key]["nom_participant"] . " " . $booking_cart['tab_participants'][$key]["prenom_participant"]);
$reservationsoin->setNomSoin("debug translation");
$reservationsoin->setQteSoin(1);
$reservationsoin->setMtSoinUnite($prixunitsoin);
$reservationsoin->setMtSoinTotal($prixunitsoin);
$reservationsoin->setReservation($reservation);
$reservationsoin->setProduitThalasso($produit);
$reservation->addReservationSoin($reservationsoin);
$this->em->persist($reservationsoin);
$this->em->persist($reservation);
$this->em->flush();
//translate
/*$repository
->translate($reservationsup, 'nom_supplement', 'en', 'debug en');*/
}
//4-0- curistes
$tab_curistes_insert = array();
if (array_key_exists('tab_curistes', $booking_cart))
foreach ($booking_cart['tab_curistes'] as $key => $curiste) {
$reservationcuriste = new Curiste();
$reservationcuriste->setCiviliteCuriste($curiste["civilite_curiste"]);
$reservationcuriste->setNomCuriste($curiste["nom_curiste"]);
$reservationcuriste->setPrenomCuriste($curiste["prenom_curiste"]);
$reservationcuriste->setAdresse($curiste["adresse"]);
$reservationcuriste->setCompAdresse($curiste["comp_adresse"]);
$reservationcuriste->setCp($curiste["cp"]);
$reservationcuriste->setVille($curiste["ville"]);
$pay = $this->em->getRepository(Pays::class)->findOneById((int)$curiste["pays_curiste"]);
if ($pay)
$reservationcuriste->setPays($pay);
$reservationcuriste->setEmailCuriste($curiste["email_curiste"]);
$reservationcuriste->setTel1Curiste($curiste["tel1_curiste"]);
$reservationcuriste->setTel2Curiste($curiste["tel2_curiste"]);
$reservationcuriste->setBeneficiaire($curiste["beneficiaire"]);
$reservationcuriste->setPostal($curiste["postal"]);
$reservationcuriste->setComment($curiste["comment_curiste"]);
$reservationcuriste->setMessage($curiste["message_curiste"]);
//var_dump($curiste["date_naissance_curiste"]); die;
//$reservationcuriste->setDateNaissanceCuriste(date("Y-m-d", strtotime(str_replace('/', '-',$curiste["date_naissance_curiste"]))));
$reservationcuriste->setDateNaissanceCuriste(null);
$reservationcuriste->setDateNaissanceCuristeText($curiste["date_naissance_curiste"]);
$this->em->persist($reservationcuriste);
$this->em->flush();
$tab_curistes_insert[$key] = $reservationcuriste->getId();
}
//4- cures
if (array_key_exists('tab_cures', $booking_cart) && count($tab_curistes_insert) > 0)
foreach ($booking_cart['tab_cures'] as $key => $cure) {
//get objects
$produit = $this->em->getRepository('App\Entity\ProduitThalasso')->findOneById($cure["cure_id"]);
$programme = $this->em->getRepository('App\Entity\Programme')->findOneById($cure["programme"]);
$regime = $this->em->getRepository('App\Entity\Regime')->findOneById($cure["regime_id"]);
if (array_key_exists($key, $tab_curistes_insert))
$curiste = $this->em->getRepository('App\Entity\Curiste')->findOneById($tab_curistes_insert[$key]);
$reservationcure = new ReservationCure();
$reservationcure->setBeneficiaireCure($curiste->getNomCuriste() . " " . $curiste->getPrenomCuriste());
$reservationcure->setNomCure("debug translation");
$reservationcure->setProgramme($programme);
$reservationcure->setRegime($regime);
$reservationcure->setQteCure(1);
$reservationcure->setMtCureUnite(0);
$reservationcure->setMtCureTotal(0);
$reservationcure->setReservation($reservation);
$reservationcure->setProduitThalasso($produit);
$reservationcure->setCuriste($curiste);
$reservation->addReservationCure($reservationcure);
$this->em->persist($reservationcure);
$this->em->persist($reservation);
$this->em->flush();
//translate
/*$repository
->translate($reservationsup, 'nom_supplement', 'en', 'debug en');*/
}
//4- ages enfants
if (array_key_exists('tab_ages', $booking_cart))
foreach ($booking_cart['tab_ages'] as $key => $age) {
$reservationenfant = new ReservationEnfant();
$reservationenfant->setAgeEnfant($age["age_enfant"]);
$reservationenfant->setReservation($reservation);
$this->em->persist($reservationenfant);
$this->em->flush();
}
//5- participants
if (array_key_exists('tab_participants', $booking_cart))
foreach ($booking_cart['tab_participants'] as $key => $participant) {
$reservationparticipant = new ReservationParticipant();
$reservationparticipant->setNomParticipant($participant["nom_participant"]);
$reservationparticipant->setPrenomParticipant($participant["prenom_participant"]);
$reservationparticipant->setAdulte($participant["adulte"]);
$reservationparticipant->setReservation($reservation);
$this->em->persist($reservationparticipant);
$this->em->flush();
}
//update ref
$ref = "BK-" . date("Ymd-Hi") . "-" . $id_reservation;
$reservation->setRefReservation($ref);
$this->em->persist($reservation);
$this->em->flush();
/*echo "<pre>";
var_dump($booking_cart);
echo "</pre>";
die;*/
// dump($reservation);
// dump(count($reservation->getReservationChambres()), $reservation->getId());
//ajouter la promo à la réservation (hôtel seul)
if (count($reservation->getReservationCures()) == 0 && count($reservation->getReservationChambres()) >= 1 && ($reservation->getReservationCadeau()) == null && ($reservation->getOffert()) == 0) {
$chambre_promos = [];
$i = 0;
foreach ($reservation->getReservationChambres() as $resChambre) {
foreach ($resChambre->getChambre()->getPromotionChambre() as $promo) {
if ($promo->getActif() == true) {
if (count($promo->getPromotionThalasso()) == 0) {
foreach ($promo->getPromotionValidites() as $promo_validite) {
if (date_create($promo_validite->getDateDebutValidite()->format('d-m-Y')) <= date_create($reservation->getDateReservation()->format('d-m-Y')) && date_create($promo_validite->getDateFinValidite()->format('d-m-Y')) >= date_create($reservation->getDateReservation()->format('d-m-Y'))) {
// dump($promo->getTitrePdf());
$chambre_promos[$i]['chambre'] = $resChambre->getId();
$chambre_promos[$i]['promo'] = $promo->getTitrePdf();
$reservation->setPromotions($chambre_promos);
$this->em->persist($reservation);
$this->em->flush();
}
$i++;
}
}
}
}
}
// dump($reservation->getPromotions());
// dd('hotel seul');
}
//ajouter promo à la réservation (cure avec hébergement)
if (count($reservation->getReservationCures()) > 0 && count($reservation->getReservationChambres()) > 0 && ($reservation->getReservationCadeau()) == null) {
$cure_promos = [];
$i = 0;
foreach ($reservation->getReservationCures() as $res_cure) {
foreach ($res_cure->getProduitThalasso()->getPromotionThalasso() as $promo) {
if ($promo->getActif() == true) {
foreach ($promo->getPromotionValidites() as $promo_validite) {
foreach ($reservation->getReservationChambres() as $res_chambre) {
foreach ($promo->getPromotionChambre() as $promo_chambre) {
if ($promo_chambre == $res_chambre->getChambre()) {
if (date_create($promo_validite->getDateDebutValidite()->format('d-m-Y')) <= date_create($reservation->getDateReservation()->format('d-m-Y')) && date_create($promo_validite->getDateFinValidite()->format('d-m-Y')) >= date_create($reservation->getDateReservation()->format('d-m-Y'))) {
// dump($promo->getTitrePdf());
$cure_promos[$i]['cure'] = $res_cure->getId();
$cure_promos[$i]['promo'] = $promo->getTitrePdf();
$reservation->setPromotions($cure_promos);
$this->em->persist($reservation);
$this->em->flush();
}
}
}
}
$i++;
}
}
}
}
// dump($reservation->getPromotions());
// dd('cure avec heb');
}
//ajouter promo à la réservation (cure sans hébergement)
if (count($reservation->getReservationCures()) > 0 && count($reservation->getReservationChambres()) == 0 && ($reservation->getReservationCadeau()) == null) {
$cure_promos = [];
$i = 0;
foreach ($reservation->getReservationCures() as $res_cure) {
foreach ($res_cure->getProduitThalasso()->getPromotionThalasso() as $promo) {
if ($promo->getActif() == true) {
foreach ($promo->getPromotionValidites() as $promo_validite) {
if (date_create($promo_validite->getDateDebutValidite()->format('d-m-Y')) <= date_create($reservation->getDateReservation()->format('d-m-Y')) && date_create($promo_validite->getDateFinValidite()->format('d-m-Y')) >= date_create($reservation->getDateReservation()->format('d-m-Y'))) {
// dump($promo->getTitrePdf());
$cure_promos[$i]['cure'] = $res_cure->getId();
$cure_promos[$i]['promo'] = $promo->getTitrePdf();
$reservation->setPromotions($cure_promos);
$this->em->persist($reservation);
$this->em->flush();
}
$i++;
}
}
}
}
// dump($reservation->getPromotions());
// dd('cure sans heb');
}
//ajouter promo à la réservation (soin)
if (($reservation->getCare()) == 1) {
$care_promos = [];
foreach ($reservation->getReservationSoins() as $res_care) {
foreach ($res_care->getProduitThalasso()->getPromotionThalasso() as $promo) {
if ($promo->getActif() == true) {
foreach ($promo->getPromotionValidites() as $promo_validite) {
if (date_create($promo_validite->getDateDebutValidite()->format('d-m-Y')) <= date_create($reservation->getDateReservation()->format('d-m-Y')) && date_create($promo_validite->getDateFinValidite()->format('d-m-Y')) >= date_create($reservation->getDateReservation()->format('d-m-Y'))) {
// dump($promo->getTitrePdf());
$cure_promos[0]['care'] = $res_care->getId();
$cure_promos[0]['promo'] = $promo->getTitrePdf();
$reservation->setPromotions($cure_promos);
$this->em->persist($reservation);
$this->em->flush();
}
}
}
}
}
// dump($reservation->getPromotions());
// dd('soin');
}
//ajout code promo à la reservation
$code_promocheck_res = $this->session->get('s_code_promotion_step');
if ($code_promocheck_res && $code_promocheck_res != "") {
$codepromo = $this->em->getRepository('App\Entity\CodePromo')->findOneBy(array("code_promo" => $code_promocheck_res));
if ($codepromo) {
$rcp = new ReservationCodePromo();
$rcp->setNomCodePromo($codepromo->getNomCodePromo());
$rcp->setDescCodePromo($codepromo->getDescCodePromo());
$rcp->setCodePromo($codepromo->getCodePromo());
$rcp->setCodePromoToutSite($codepromo->getCodePromoToutSite());
$rcp->setTypeCodePromo($codepromo->getTypeCodePromo());
$rcp->setPourcentageCodePromo($codepromo->getPourcentageCodePromo());
$rcp->setMontantCodePromo($codepromo->getMontantCodePromo());
$rcp->setQteCodePromo($codepromo->getQteCodePromo());
$rcp->setReservation($reservation);
$this->em->persist($rcp);
$this->em->flush();
}
}
//process payment
if ($id_reservation) {
//Inital Vars
/*
Master MID : BNP_MIRAMAR
Test MID(s) : BNP_MIRAMAR_ECOM_FR_EUR_t
Prod MID(s) : BNP_MIRAMAR_ECOM_FR_EUR
*/
/*
Identifiant commerçant (MID)
BNP_MIRAMAR_ECOM_FR_EUR
Clé de chiffrement Blowfish
c(4MZ9o)_L8yw!Y2
Clé HMAC
6z(JD9t_7r=R]3NaEc4)8!qGoC*5Z[2j
Identifiant commerçant (MID)
BNP_MIRAMAR_ECOM_FR_EUR_t
Clé de chiffrement Blowfish
r*7R=Db2w6Y_)z8W
Clé HMAC
G]a8!5FyBq3?f6_KRp7(*Mw4Pb9=[Hx2
Lorsque vous effectuez vos tests, nous vous recommandons de limiter le montant des transactions de 15 à 99 centimes. La remise en banque (capture) n'est pas activée sur les comptes de test mais sera disponible sur les comptes de production.
*/
$Your_MERCHANTID = $this->Your_MERCHANTID;
$urlPageConfirm = $this->generateUrl('api_pay_confirm', ['_locale' => $_locale], UrlGeneratorInterface::ABSOLUTE_URL);
$urlPageBack = $this->generateUrl('default_hotel_page', ['_locale' => $_locale, 'hostname' => $_SERVER['HTTP_HOST']], UrlGeneratorInterface::ABSOLUTE_URL);
$Your_Payment_id = $token;
$Your_Amount = $TotalAccompte;
$Your_Ref = $id_reservation; //replace with unique database id
$Your_logo_img = "";
$Your_miscelaneous = "";
//Init the class
$paymentRequest = new Axepta($this->Your_HMAC, $this->mode3dsv2);
$paymentRequest->setCryptKey($this->Your_CRYPTKEY);
//Set data payments
$paymentRequest->setUrl(Axepta::PAYSSL);
$paymentRequest->setMerchantID($Your_MERCHANTID);
$paymentRequest->setTransID("PM-" . $id_reservation . "-" . rand(100000, 999999));
$paymentRequest->setAmount((int)($Your_Amount * 100));
$paymentRequest->setCurrency('EUR');
$paymentRequest->setRefNr($Your_Ref);
$paymentRequest->setURLSuccess($urlPageConfirm);
$paymentRequest->setURLFailure($urlPageConfirm);
$paymentRequest->setURLNotify($urlPageConfirm);
$paymentRequest->setURLBack($urlPageBack);
$paymentRequest->setReponse('encrypt');
$paymentRequest->setLanguage('fr');
// Evolution vers le 3DSV2
if ($paymentRequest->getMode3dsv2()) {
$paymentRequest->setMsgVer('2.0');
}
if ($this->TEST_PAYMODE)
$paymentRequest->setOrderDesc('Test:0000');
else
$paymentRequest->setOrderDesc('Your Order description text');
// check your data
$paymentRequest->validate();
// compute
$mac = $paymentRequest->getShaSign(); // run HMAC hash
$data = $paymentRequest->getBfishCrypt(); // run Crypt & retrieve Data
$len = $paymentRequest->getLen(); // retrieve Crypt length
//generate form for payment
$TransID = $paymentRequest->getTransID();
$reservation->setTransid($TransID);
$this->em->persist($reservation);
$this->em->flush();
echo "<html><body>
<form name=\"redirectForm\" method=\"GET\" action=\"" . $paymentRequest->getUrl() . "\">" .
"<input type=\"hidden\" name=\"MerchantID\" value=\"" . $paymentRequest->getMerchantID() . "\">" .
"<input type=\"hidden\" name=\"Len\" value=\"" . $paymentRequest->getLen() . "\">" .
"<input type=\"hidden\" name=\"Data\" value=\"" . $paymentRequest->getBfishCrypt() . "\">" .
"<input type=\"hidden\" name=\"URLBack\" value=\"" . $paymentRequest->getURLBack() . "\">" .
"<input type=\"hidden\" name=\"CustomField1\" value=\"" . $paymentRequest->getAmount() / 100 . "\">" .
"<input type=\"hidden\" name=\"CustomField2\" value=\"" . $TransID . "\">" .
"<input type=\"hidden\" name=\"CustomField3\" value=\"" . $Your_logo_img . "\">" .
"<input type=\"hidden\" name=\"CustomField8\" value=\"" . $Your_miscelaneous . "\">" .
"<noscript><input type=\"submit\" name=\"Go\" value=\"Click to continue\"/></noscript>
</form>" .
"<script type=\"text/javascript\">document.redirectForm.submit(); </script>" .
"</body></html>";
} else
return new JsonResponse("Error creating Booking");
} else
return new JsonResponse(['response' => ['msg' => 'in dev phase'], 'status' => 501]);
// return new JsonResponse(['response' =>['msg' => 'in dev phase'], 'status' => 501]);
}
/**
* @Route("/{_locale}/api-pay-confirm", name="api_pay_confirm", defaults={"_locale": "fr"}, requirements={"_locale": "en|fr|de"})
*
*/
public function confirmPay(MailerInterface $mailer, KernelInterface $app, Request $request, $_locale)
{
# begin pages versions
#fr
$page_versions[] = array(
"to" => "/fr",
"value" => "fr",
"active" => ($_locale == "fr") ? true : false
);
#en
$page_versions[] = array(
"to" => "/en",
"value" => "en",
"active" => ($_locale == "en") ? true : false
);
# end pages versions
$paymentResponse = new Axepta($this->Your_HMAC, $this->mode3dsv2);
$paymentResponse->setCryptKey($this->Your_CRYPTKEY);
// Evolution vers le 3DSV2 change get to request to accept both get and post
$paymentResponse->setResponse($_REQUEST);
//debug 3ds vars
/*echo "<pre>";
var_dump($_GET);
var_dump($_POST); //not working
var_dump($_REQUEST);
var_dump($paymentResponse->getParameters());
var_dump($paymentResponse->isSuccessful());
var_dump($paymentResponse->isValid());
echo "</pre>";
die;*/
$mode_residence = $this->frontService->getResidenceMode();
$token = null;
$reservationmail = null;
if ($paymentResponse->isValid() && $paymentResponse->isSuccessful()) {
$TransID = $paymentResponse->getPayID();
$PCNr = $paymentResponse->getPCNr();
$CCBrand = $paymentResponse->getCCBrand();
$CCExpiry = $paymentResponse->getCCExpiry();
$retour = 1;
/* ------------- Begin send email ------------- */
$reservationmail = $this->em->getRepository('App\Entity\Reservation')->findOneBy([
'transid' => $paymentResponse->getTransID()
]);
$token = $reservationmail->getTokenReservation();
$templatePdf = $this->getBookingPdfTemplate($token);
//join PDF
$myProjectDirectory = $app->getRootDir() . "/..";
$snappy = new Pdf($myProjectDirectory . '/vendor/h4cc/wkhtmltopdf-amd64/bin/wkhtmltopdf-amd64');
if (!$reservationmail->getPaye()) {
// // Envoi confirmation réservation au client
// if (!$mode_residence) {
// $email = (new TemplatedEmail())
// ->from($this->params->get('EMAIL_FROM_MIRAMAR'))
// ->to($reservationmail->getClient()->getEmailClient())
// //->cc('cc@example.com')
// ->bcc('reservation@miramar-lacigale.com')
// //->replyTo('replyTo@example.com')
// //->priority(Email::PRIORITY_HIGH)
// ->subject('CONFIRMATION DE RÉSERVATION')
// //->text('Sending emails is fun again!')
// //->html('<p>See Twig integration for better HTML integration!</p>');
// // path of the Twig template to render
// ->htmlTemplate($templatePdf)
// // pass variables (name => value) to the template
// ->context([
// "res" => $reservationmail
// ]);
// $mailer->send($email);
// }else {
// $email = (new TemplatedEmail())
// ->from($this->params->get('EMAIL_FROM_RESIDENCE'))
// ->to($reservationmail->getClient()->getEmailClient())
// //->cc('cc@example.com')
// ->bcc('reservation@miramar-lacigale.com')
// //->replyTo('replyTo@example.com')
// //->priority(Email::PRIORITY_HIGH)
// ->subject('CONFIRMATION DE RÉSERVATION')
// //->text('Sending emails is fun again!')
// //->html('<p>See Twig integration for better HTML integration!</p>');
// // path of the Twig template to render
// ->htmlTemplate($templatePdf)
// // pass variables (name => value) to the template
// ->context([
// "res" => $reservationmail
// ]);
// $mailer->send($email);
// }
$reservationmail->setPaye(1);
$this->em->persist($reservationmail);
$this->em->flush();
//change stock for current booking
$logstocks = $this->changeBookingStock($token);
$html = $this->renderView(
$templatePdf,
array(
"res" => $reservationmail,
"dir" => $myProjectDirectory
)
);
$attachement = $snappy->getOutputFromHtml($html, [
'encoding' => 'utf-8',
'images' => true
]);
// Envoi confirmation réservation au client
if (!$mode_residence) {
$email = (new TemplatedEmail())
->from($this->params->get('EMAIL_FROM_MIRAMAR'))
->to($reservationmail->getClient()->getEmailClient())
//->cc('cc@example.com')
->bcc('reservation@miramar-lacigale.com')
->addBcc('digital@miramar-lacigale.com')
//->replyTo('replyTo@example.com')
//->priority(Email::PRIORITY_HIGH)
->subject($this->translator->trans("objet.confirmation"))
//->text('Sending emails is fun again!')
//->html('<p>See Twig integration for better HTML integration!</p>');
// path of the Twig template to render
->htmlTemplate($templatePdf)
// pass variables (name => value) to the template
->context([
"res" => $reservationmail
])
->attach($attachement, 'confirmation_de_reservation.pdf');
//add conditionnal fix for pool and lunch 191
$add_custom_mails = false;
foreach ($reservationmail->getReservationSoins() as $res_care) {
if( ($res_care->getProduitThalasso()->getId() == 191) || ($res_care->getProduitThalasso()->getId() == 197) ) {
$add_custom_mails = true;
}
}
if($add_custom_mails)
{
if($res_care->getProduitThalasso()->getId() == 191){
$email->addBcc('f.massot@miramar-lacigale.com')
->addBcc('lechef@miramar-lacigale.com')
->addBcc('chefpatissier@miramar-lacigale.com')
->addBcc('restauration@miramar-lacigale.com')
->addBcc('reception@miramar-lacigale.com')
->addBcc('receptionthalasso@miramar-lacigale.com');
}
elseif($res_care->getProduitThalasso()->getId() == 197){
$email->addBcc('restauration@miramar-lacigale.com')
->addBcc('lechef@miramar-lacigale.com')
->addBcc('chefpatissier@miramar-lacigale.com')
->addBcc('f.massot@miramar-lacigale.com');
}
}
$mailer->send($email);
} else {
$transport = Transport::fromDsn($this->getParameter('app.mailerDsnResidence'));
$mailer = new Mailer($transport);
$email = (new TemplatedEmail())
->from($this->params->get('EMAIL_FROM_RESIDENCE'))
->to($reservationmail->getClient()->getEmailClient())
//->cc('cc@example.com')
->bcc('reservation@miramar-lacigale.com')
->addBcc('digital@miramar-lacigale.com')
//->replyTo('replyTo@example.com')
//->priority(Email::PRIORITY_HIGH)
->subject($this->translator->trans("objet.confirmation"))
//->text('Sending emails is fun again!')
//->html('<p>See Twig integration for better HTML integration!</p>');
// path of the Twig template to render
->html($html)
// pass variables (name => value) to the template
->context([
"res" => $reservationmail
])
->attach($attachement, 'confirmation_de_reservation.pdf');
$mailer->send($email);
}
// Envoi cheque cadeau
if (($reservationmail->getReservationCadeau()) != null) {
$cheque_cadeau = "pdfs/cheque_cadeau.html.twig";
$email_beneficiare = $reservationmail->getReservationCadeau()->getEmailBeneficiaire();
$html = $this->renderView(
$cheque_cadeau,
array(
"res" => $reservationmail,
"dir" => $myProjectDirectory, '_locale' => $_locale
)
);
$filename = 'cheque_cadeau.pdf';
$attachement = $snappy->getOutputFromHtml($html, [
'encoding' => 'utf-8',
'images' => true,
'orientation' => 'Landscape'
]);
if (($reservationmail->getReservationCadeau()->getTypeEnvoi()) == 0) {
if (($reservationmail->getReservationCadeau()->getDestinataireEnvoi()) == 1) {
$email = (new TemplatedEmail())
->from($this->params->get('EMAIL_FROM_MIRAMAR'))
->to($email_beneficiare)
//->cc('cc@example.com')
->bcc('reservation@miramar-lacigale.com')
->addBcc('digital@miramar-lacigale.com')
->addBcc('loubna@alphalab72.com')
//->replyTo('replyTo@example.com')
//->priority(Email::PRIORITY_HIGH)
->subject($this->translator->trans("objet.chequeBeneficiaire"))
//->text('Sending emails is fun again!')
//->html('<p>See Twig integration for better HTML integration!</p>');
// path of the Twig template to render
->htmlTemplate($cheque_cadeau)
// pass variables (name => value) to the template
->context([
"res" => $reservationmail
])
->attach($attachement, $filename)
// ->attach(new \Swift_Attachment($pdf, $filename, 'application/pdf'))
;
$mailer->send($email);
} else {
$email = (new TemplatedEmail())
->from($this->params->get('EMAIL_FROM_MIRAMAR'))
->to($reservationmail->getClient()->getEmailClient())
//->cc('cc@example.com')
->bcc('reservation@miramar-lacigale.com')
->addBcc('digital@miramar-lacigale.com')
->addBcc('loubna@alphalab72.com')
//->replyTo('replyTo@example.com')
//->priority(Email::PRIORITY_HIGH)
->subject($this->translator->trans("objet.chequeVousMeme"))
//->text('Sending emails is fun again!')
//->html('<p>See Twig integration for better HTML integration!</p>');
// path of the Twig template to render
->htmlTemplate($cheque_cadeau)
// pass variables (name => value) to the template
->context([
"res" => $reservationmail
])
->attach($attachement, $filename);
$mailer->send($email);
}
}
} elseif ($reservationmail->getOffert() == 1) {
// Envoi Bon cadeau
$bon_cadeau = "pdfs/bon_cadeau.html.twig";
$email_beneficiare = $reservationmail->getReservationCures()[0]->getCuriste()->getEmailCuriste();
$html = $this->renderView(
$bon_cadeau,
array(
"res" => $reservationmail,
"dir" => $myProjectDirectory, '_locale' => $_locale
)
);
$filename = 'bon_cadeau.pdf';
$attachement = $snappy->getOutputFromHtml($html, [
'encoding' => 'utf-8',
'images' => true,
'orientation' => 'Landscape'
]);
if (($reservationmail->getReservationCures()[0]->getCuriste()->getPostal()) == 0) {
if (($reservationmail->getReservationCures()[0]->getCuriste()->getBeneficiaire()) == 1) {
$email = (new TemplatedEmail())
->from($this->params->get('EMAIL_FROM_MIRAMAR'))
->to($email_beneficiare)
//->cc('cc@example.com')
->bcc('reservation@miramar-lacigale.com')
->addBcc('digital@miramar-lacigale.com')
//->replyTo('replyTo@example.com')
//->priority(Email::PRIORITY_HIGH)
->subject($this->translator->trans("objet.bonBeneficiaire"))
//->text('Sending emails is fun again!')
//->html('<p>See Twig integration for better HTML integration!</p>');
// path of the Twig template to render
->htmlTemplate($bon_cadeau)
// pass variables (name => value) to the template
->context([
"res" => $reservationmail
])
->attach($attachement, $filename);
$mailer->send($email);
} else {
$email = (new TemplatedEmail())
->from($this->params->get('EMAIL_FROM_MIRAMAR'))
->to($reservationmail->getClient()->getEmailClient())
//->cc('cc@example.com')
->bcc('reservation@miramar-lacigale.com')
->addBcc('digital@miramar-lacigale.com')
//->replyTo('replyTo@example.com')
//->priority(Email::PRIORITY_HIGH)
->subject($this->translator->trans("objet.bonVousMeme"))
//->text('Sending emails is fun again!')
//->html('<p>See Twig integration for better HTML integration!</p>');
// path of the Twig template to render
->htmlTemplate($bon_cadeau)
// pass variables (name => value) to the template
->context([
"res" => $reservationmail
])
->attach($attachement, $filename);
$mailer->send($email);
}
}
}
}
//
if ($reservationmail->getPaye()) {
}
/* ------------- End send email ------------- */
} else {
// Fail ....
$retour = 0;
}
return $this->render('pages/akaru/reservations/confirmation.html.twig', array("retour" => $retour, "token" => $token, "res" => $reservationmail, "page_versions" => $page_versions));
}
/**
* @Route("/debug-email-verify/{token_reservation}/{email_to}", name="verifysendemail", defaults={"_locale": "fr"}, requirements={"_locale": "en|fr|de"})
* @return void
*/
public function emailSendVerify(MailerInterface $mailer, KernelInterface $app, Request $request, $_locale, string $token_reservation, string $email_to){
$to = $email_to;
$subject = "Test Email from PHP";
$message = "Hello,\nThis is a test email sent from a PHP script.";
$headers = "From: ".$this->params->get('EMAIL_FROM_MIRAMAR');
if (mail($to, $subject, $message, $headers)) {
echo "Email sent successfully.";
} else {
echo "Failed to send email.";
}
$reservationmail = $this->em->getRepository('App\Entity\Reservation')->findOneBy([
'token_reservation' => $token_reservation
]);
$token = $token_reservation;
$templatePdf = $this->getBookingPdfTemplate($token);
//join PDF
$myProjectDirectory = $app->getRootDir() . "/..";
$snappy = new Pdf($myProjectDirectory . '/vendor/h4cc/wkhtmltopdf-amd64/bin/wkhtmltopdf-amd64');
$html = $this->renderView(
$templatePdf,
array(
"res" => $reservationmail,
"dir" => $myProjectDirectory
)
);
$attachement = $snappy->getOutputFromHtml($html, [
'encoding' => 'utf-8',
'images' => true
]);
$email = (new TemplatedEmail())
->from($this->params->get('EMAIL_FROM_MIRAMAR'))
//->to($reservationmail->getClient()->getEmailClient())
->to($email_to)
//->bcc('reservation@miramar-lacigale.com')
//->addBcc('digital@miramar-lacigale.com')
->subject($this->translator->trans("objet.confirmation"))
// path of the Twig template to render
->htmlTemplate($templatePdf)
// pass variables (name => value) to the template
->context([
"res" => $reservationmail
])
->attach($attachement, 'confirmation_de_reservation.pdf');
$mailer->send($email);
return new Response("verify email");
}
/**
* @Route("/debug-ipn-booking/{token_reservation}", name="debugpaymentIpn", defaults={"_locale": "fr"}, requirements={"_locale": "en|fr|de"})
* @return void
*/
public function paymentdebuger(MailerInterface $mailer, KernelInterface $app, Request $request, $_locale, string $token_reservation){
# begin pages versions
#fr
$page_versions[] = array(
"to" => "/fr",
"value" => "fr",
"active" => ($_locale == "fr") ? true : false
);
#en
$page_versions[] = array(
"to" => "/en",
"value" => "en",
"active" => ($_locale == "en") ? true : false
);
# end pages versions
// $paymentResponse = new Axepta($this->Your_HMAC, $this->mode3dsv2);
// $paymentResponse->setCryptKey($this->Your_CRYPTKEY);
// Evolution vers le 3DSV2 change get to request to accept both get and post
// $paymentResponse->setResponse($_REQUEST);
//debug 3ds vars
/*echo "<pre>";
var_dump($_GET);
var_dump($_POST); //not working
var_dump($_REQUEST);
var_dump($paymentResponse->getParameters());
var_dump($paymentResponse->isSuccessful());
var_dump($paymentResponse->isValid());
echo "</pre>";
die;*/
$mode_residence = $this->frontService->getResidenceMode();
$token = null;
$reservationmail = null;
//if ($paymentResponse->isValid() && $paymentResponse->isSuccessful()) {
//$TransID = $paymentResponse->getPayID();
//$PCNr = $paymentResponse->getPCNr();
//$CCBrand = $paymentResponse->getCCBrand();
//$CCExpiry = $paymentResponse->getCCExpiry();
//$retour = 1;
/* ------------- Begin send email ------------- */
$reservationmail = $this->em->getRepository('App\Entity\Reservation')->findOneBy([
'token_reservation' => $token_reservation
]);
$token = $token_reservation;
$templatePdf = $this->getBookingPdfTemplate($token);
//join PDF
$myProjectDirectory = $app->getRootDir() . "/..";
$snappy = new Pdf($myProjectDirectory . '/vendor/h4cc/wkhtmltopdf-amd64/bin/wkhtmltopdf-amd64');
// if (!$reservationmail->getPaye()) {
// // Envoi confirmation réservation au client
// if (!$mode_residence) {
// $email = (new TemplatedEmail())
// ->from($this->params->get('EMAIL_FROM_MIRAMAR'))
// ->to($reservationmail->getClient()->getEmailClient())
// //->cc('cc@example.com')
// ->bcc('reservation@miramar-lacigale.com')
// //->replyTo('replyTo@example.com')
// //->priority(Email::PRIORITY_HIGH)
// ->subject('CONFIRMATION DE RÉSERVATION')
// //->text('Sending emails is fun again!')
// //->html('<p>See Twig integration for better HTML integration!</p>');
// // path of the Twig template to render
// ->htmlTemplate($templatePdf)
// // pass variables (name => value) to the template
// ->context([
// "res" => $reservationmail
// ]);
// $mailer->send($email);
// }else {
// $email = (new TemplatedEmail())
// ->from($this->params->get('EMAIL_FROM_RESIDENCE'))
// ->to($reservationmail->getClient()->getEmailClient())
// //->cc('cc@example.com')
// ->bcc('reservation@miramar-lacigale.com')
// //->replyTo('replyTo@example.com')
// //->priority(Email::PRIORITY_HIGH)
// ->subject('CONFIRMATION DE RÉSERVATION')
// //->text('Sending emails is fun again!')
// //->html('<p>See Twig integration for better HTML integration!</p>');
// // path of the Twig template to render
// ->htmlTemplate($templatePdf)
// // pass variables (name => value) to the template
// ->context([
// "res" => $reservationmail
// ]);
// $mailer->send($email);
// }
//$reservationmail->setPaye(1);
//$this->em->persist($reservationmail);
//$this->em->flush();
//change stock for current booking
$logstocks = $this->changeBookingStock($token);
$html = $this->renderView(
$templatePdf,
array(
"res" => $reservationmail,
"dir" => $myProjectDirectory
)
);
$attachement = $snappy->getOutputFromHtml($html, [
'encoding' => 'utf-8',
'images' => true
]);
// Envoi confirmation réservation au client
if (!$mode_residence) {
$email = (new TemplatedEmail())
->from($this->params->get('EMAIL_FROM_MIRAMAR'))
->to($reservationmail->getClient()->getEmailClient())
//->cc('cc@example.com')
->bcc('reservation@miramar-lacigale.com')
->addBcc('digital@miramar-lacigale.com')
//->replyTo('replyTo@example.com')
//->priority(Email::PRIORITY_HIGH)
->subject($this->translator->trans("objet.confirmation"))
//->text('Sending emails is fun again!')
//->html('<p>See Twig integration for better HTML integration!</p>');
// path of the Twig template to render
->htmlTemplate($templatePdf)
// pass variables (name => value) to the template
->context([
"res" => $reservationmail
])
->attach($attachement, 'confirmation_de_reservation.pdf');
//add conditionnal fix for pool and lunch 191
$add_custom_mails = false;
foreach ($reservationmail->getReservationSoins() as $res_care) {
if( ($res_care->getProduitThalasso()->getId() == 191) || ($res_care->getProduitThalasso()->getId() == 197) ) {
$add_custom_mails = true;
}
}
if($add_custom_mails)
{
if($res_care->getProduitThalasso()->getId() == 191){
$email->addBcc('f.massot@miramar-lacigale.com')
->addBcc('lechef@miramar-lacigale.com')
->addBcc('chefpatissier@miramar-lacigale.com')
->addBcc('restauration@miramar-lacigale.com')
->addBcc('reception@miramar-lacigale.com')
->addBcc('receptionthalasso@miramar-lacigale.com');
}
elseif($res_care->getProduitThalasso()->getId() == 197){
$email->addBcc('restauration@miramar-lacigale.com')
->addBcc('lechef@miramar-lacigale.com')
->addBcc('chefpatissier@miramar-lacigale.com')
->addBcc('f.massot@miramar-lacigale.com');
}
}
//$mailer->send($email);
} else {
$transport = Transport::fromDsn($this->getParameter('app.mailerDsnResidence'));
$mailer = new Mailer($transport);
$email = (new TemplatedEmail())
->from($this->params->get('EMAIL_FROM_RESIDENCE'))
->to($reservationmail->getClient()->getEmailClient())
//->cc('cc@example.com')
->bcc('reservation@miramar-lacigale.com')
->addBcc('digital@miramar-lacigale.com')
//->replyTo('replyTo@example.com')
//->priority(Email::PRIORITY_HIGH)
->subject($this->translator->trans("objet.confirmation"))
//->text('Sending emails is fun again!')
//->html('<p>See Twig integration for better HTML integration!</p>');
// path of the Twig template to render
->html($html)
// pass variables (name => value) to the template
->context([
"res" => $reservationmail
])
->attach($attachement, 'confirmation_de_reservation.pdf');
// $mailer->send($email);
}
// Envoi cheque cadeau
if (($reservationmail->getReservationCadeau()) != null) {
$cheque_cadeau = "pdfs/cheque_cadeau.html.twig";
$email_beneficiare = $reservationmail->getReservationCadeau()->getEmailBeneficiaire();
$html = $this->renderView(
$cheque_cadeau,
array(
"res" => $reservationmail,
"dir" => $myProjectDirectory, '_locale' => $_locale
)
);
$filename = 'cheque_cadeau.pdf';
echo $html; die;
$attachement = $snappy->getOutputFromHtml($html, [
'encoding' => 'utf-8',
'images' => true,
'orientation' => 'Landscape'
]);
if (($reservationmail->getReservationCadeau()->getTypeEnvoi()) == 0) {
if (($reservationmail->getReservationCadeau()->getDestinataireEnvoi()) == 1) {
$email = (new TemplatedEmail())
->from($this->params->get('EMAIL_FROM_MIRAMAR'))
->to($email_beneficiare)
//->cc('cc@example.com')
->bcc('reservation@miramar-lacigale.com')
->addBcc('digital@miramar-lacigale.com')
->addBcc('loubna@alphalab72.com')
//->replyTo('replyTo@example.com')
//->priority(Email::PRIORITY_HIGH)
->subject($this->translator->trans("objet.chequeBeneficiaire"))
//->text('Sending emails is fun again!')
//->html('<p>See Twig integration for better HTML integration!</p>');
// path of the Twig template to render
->htmlTemplate($cheque_cadeau)
// pass variables (name => value) to the template
->context([
"res" => $reservationmail
])
->attach($attachement, $filename)
// ->attach(new \Swift_Attachment($pdf, $filename, 'application/pdf'))
;
$mailer->send($email);
} else {
$email = (new TemplatedEmail())
->from($this->params->get('EMAIL_FROM_MIRAMAR'))
->to($reservationmail->getClient()->getEmailClient())
//->cc('cc@example.com')
->bcc('reservation@miramar-lacigale.com')
->addBcc('digital@miramar-lacigale.com')
->addBcc('loubna@alphalab72.com')
//->replyTo('replyTo@example.com')
//->priority(Email::PRIORITY_HIGH)
->subject($this->translator->trans("objet.chequeVousMeme"))
//->text('Sending emails is fun again!')
//->html('<p>See Twig integration for better HTML integration!</p>');
// path of the Twig template to render
->htmlTemplate($cheque_cadeau)
// pass variables (name => value) to the template
->context([
"res" => $reservationmail
])
->attach($attachement, $filename);
$mailer->send($email);
}
}
} elseif ($reservationmail->getOffert() == 1) {
// Envoi Bon cadeau
$bon_cadeau = "pdfs/bon_cadeau.html.twig";
$email_beneficiare = $reservationmail->getReservationCures()[0]->getCuriste()->getEmailCuriste();
$html = $this->renderView(
$bon_cadeau,
array(
"res" => $reservationmail,
"dir" => $myProjectDirectory, '_locale' => $_locale
)
);
$filename = 'bon_cadeau.pdf';
$attachement = $snappy->getOutputFromHtml($html, [
'encoding' => 'utf-8',
'images' => true,
'orientation' => 'Landscape'
]);
if (($reservationmail->getReservationCures()[0]->getCuriste()->getPostal()) == 0) {
if (($reservationmail->getReservationCures()[0]->getCuriste()->getBeneficiaire()) == 1) {
$email = (new TemplatedEmail())
->from($this->params->get('EMAIL_FROM_MIRAMAR'))
->to($email_beneficiare)
//->cc('cc@example.com')
->bcc('reservation@miramar-lacigale.com')
->addBcc('digital@miramar-lacigale.com')
//->replyTo('replyTo@example.com')
//->priority(Email::PRIORITY_HIGH)
->subject($this->translator->trans("objet.bonBeneficiaire"))
//->text('Sending emails is fun again!')
//->html('<p>See Twig integration for better HTML integration!</p>');
// path of the Twig template to render
->htmlTemplate($bon_cadeau)
// pass variables (name => value) to the template
->context([
"res" => $reservationmail
])
->attach($attachement, $filename);
$mailer->send($email);
} else {
$email = (new TemplatedEmail())
->from($this->params->get('EMAIL_FROM_MIRAMAR'))
->to($reservationmail->getClient()->getEmailClient())
//->cc('cc@example.com')
->bcc('reservation@miramar-lacigale.com')
->addBcc('digital@miramar-lacigale.com')
//->replyTo('replyTo@example.com')
//->priority(Email::PRIORITY_HIGH)
->subject($this->translator->trans("objet.bonVousMeme"))
//->text('Sending emails is fun again!')
//->html('<p>See Twig integration for better HTML integration!</p>');
// path of the Twig template to render
->htmlTemplate($bon_cadeau)
// pass variables (name => value) to the template
->context([
"res" => $reservationmail
])
->attach($attachement, $filename);
$mailer->send($email);
}
}
}
//}
//
//if ($reservationmail->getPaye()) {
//}
/* ------------- End send email ------------- */
//} else {
// Fail ....
// $retour = 0;
// }
//return $this->render('pages/akaru/reservations/confirmation.html.twig', array("retour" => $retour, "token" => $token, "res" => $reservationmail, "page_versions" => $page_versions));
return new Response("paymentIpn call");
}
// /**
// * @Route("/{_locale}/bon-cadeau-pdf-{token}/{fromBo}", name="bon-pdf", defaults={"fromBo": "", "_locale": "fr"}, requirements={"_locale": "en|fr|de"})
// *
// */
// public function bonCadeauPDF($fromBo, $token = null, KernelInterface $app, $_locale)
// {
// $reservation = $this->em->getRepository('App\Entity\Reservation')->findOneBy([
// 'token_reservation' => $token
// ]);
// $templatePdf = 'pdfs/bon_cadeau.html.twig';
// $myProjectDirectory = $app->getRootDir() . "/..";
// $snappy = new Pdf($myProjectDirectory . '/vendor/h4cc/wkhtmltopdf-amd64/bin/wkhtmltopdf-amd64');
// $html = $this->renderView(
// $templatePdf,
// array("token" => $token, "res" => $reservation, 'dir' => $myProjectDirectory, '_locale' => $_locale)
// );
// if ($fromBo == "") {
// return new PdfResponse(
// $snappy->getOutputFromHtml($html),
// 'confirmation-'. $reservation->getRefReservation().'.pdf'
// );
// } else {
// $response = new Response();
// $response->setContent($snappy->getOutputFromHtml($html));
// $response->headers->set('Content-Type', 'application/pdf');
// //$response->headers->set('Content-Type: application/pdf', 'application/force-download');
// $response->headers->set('Content-disposition', 'filename=test.pdf');
// return $response;
// }
// // return $this->render($templatePdf, array("res" => $reservation, '_locale' => $_locale));
// }
/**
* @Route("/{_locale}/booking-pdf-{token}/{fromBo}", name="booking-pdf", defaults={"fromBo": "", "_locale": "fr"}, requirements={"_locale": "en|fr|de"})
*
*/
public function bookingPdf($fromBo, $token = null, KernelInterface $app, $_locale)
{
$reservation = $this->em->getRepository('App\Entity\Reservation')->findOneBy([
'token_reservation' => $token
]);
$templatePdf = $this->getBookingPdfTemplate($token);
$myProjectDirectory = $app->getRootDir() . "/..";
$snappy = new Pdf($myProjectDirectory . '/vendor/h4cc/wkhtmltopdf-amd64/bin/wkhtmltopdf-amd64');
$html = $this->renderView(
$templatePdf,
array("token" => $token, "res" => $reservation, 'dir' => $myProjectDirectory, '_locale' => $_locale)
);
if ($fromBo == "") {
return new PdfResponse(
$snappy->getOutputFromHtml($html),
'confirmation-' . $reservation->getRefReservation() . '.pdf'
);
} else {
$response = new Response();
$response->setContent($snappy->getOutputFromHtml($html));
$response->headers->set('Content-Type', 'application/pdf');
//$response->headers->set('Content-Type: application/pdf', 'application/force-download');
$response->headers->set('Content-disposition', 'filename=test.pdf');
return $response;
}
// $bookingService->downloadAPdf($html);
// return $this->render($templatePdf, array("res" => $reservation, '_locale' => $_locale));
}
public function getBookingPdfTemplate($token = null)
{
$reservation = $this->em->getRepository('App\Entity\Reservation')->findOneBy([
'token_reservation' => $token
]);
$templatePdf = "pdfs/confirmation.html.twig";
//thalasso avec hebergement
if (count($reservation->getReservationCures()) > 0 && count($reservation->getReservationChambres()) > 0 && ($reservation->getReservationCadeau()) == null)
$templatePdf = "pdfs/confirmation-index.html.twig";
//thalasso sans hebergement
if (count($reservation->getReservationCures()) > 0 && count($reservation->getReservationChambres()) == 0 && ($reservation->getReservationCadeau()) == null)
$templatePdf = "pdfs/confirmation-cure.html.twig";
//hotel seul / residence
if (count($reservation->getReservationCures()) == 0 && count($reservation->getReservationChambres()) == 1 && ($reservation->getReservationCadeau()) == null && ($reservation->getOffert()) == 0) {
$templatePdf = "pdfs/confirmation-room.html.twig";
}
if (count($reservation->getReservationCures()) == 0 && count($reservation->getReservationChambres()) > 1 && ($reservation->getReservationCadeau()) == null)
$templatePdf = "pdfs/confirmation_multi_room.html.twig";
//Cheque cadeau
if (($reservation->getReservationCadeau()) != null && ($reservation->getChequeCadeau()) == 1) {
$templatePdf = "pdfs/confirmation-cheque-cadeau.html.twig";
}
//Bon cadeau
if (($reservation->getOffert()) == 1 && ($reservation->getReservationCadeau()) == null)
$templatePdf = "pdfs/confirmation-cadeau.html.twig";
//Care
if (($reservation->getCare()) == 1)
$templatePdf = "pdfs/confirmation-care.html.twig";
if (($reservation->getCare()) == 1 && ($reservation->getOffert()) == 1)
$templatePdf = "pdfs/confirmation-care-cadeau.html.twig";
return $templatePdf;
}
/**
* @Route("/process-search", name="process_search")
*
*/
public function processSearch()
{
return new Response("process_search");
}
/**
* @Route("/process-choice", name="process_choice")
*
*/
public function processChoice()
{
return new Response("process_choice");
}
/**
* @Route("/process-gift", name="process_choice_gift")
*
*/
public function processChoiceGift(Request $request)
{
//get posted data
$dataChoice = $request->request->all();
//remove old session thalasso
$this->session->remove('selected_thalasso');
//remove old session room
$this->session->remove('selected_room');
$this->session->remove('s_code_promotion_step');
return $this->redirectToRoute('render_mlc_gift');
}
/**
* @Route("/{_locale}/process-choice-thalasso", defaults={"_locale": "fr"}, name="process_choice_thalasso")
*
*/
public function processChoiceThalasso(Request $request, $_locale)
{
//get posted data
$dataChoice = $request->request->all();
/*echo "<pre>";
var_dump($dataChoice);
echo "</pre>";
die;*/
//produit thalasso
$produit = $this->em->getRepository('App\Entity\ProduitThalasso')->findOneById((int)$dataChoice["id"]);
$dataChoice["duree"] = $produit->getDureeJours();
//init program id
$dataChoice["program"] = $dataChoice["program-id"];
//get posted data
$this->session->set('selected_thalasso', $dataChoice);
//remove old session room
$this->session->remove('selected_room');
$this->session->remove('booking_cart');
$this->session->remove('s_code_promotion_step');
if (array_key_exists("isGift", $dataChoice))
$this->session->set('sisGift', $dataChoice["isGift"]);
else
$this->session->set('sisGift', "false");
//$params['date_start'] = date("Y-m-d", strtotime(str_replace('/', '-',$params['date_start'])));
//return new Response("process_choice_thalasso");
return $this->redirectToRoute('render_mlc_reservation', ['_locale' => $_locale]);
}
/**
* @Route("/{_locale}/process-choice-vente-{idp}-g{g}-vp{vp}",defaults={"_locale": "fr"}, name="process_choice_vp_gift", requirements={"idp"="\d+"})
* @Route("/{_locale}/process-choice-signature-{idp}-g{g}",defaults={"_locale": "fr"}, name="process_choice_signature_gift", requirements={"idp"="\d+"})
* @Route("/{_locale}/process-choice-signature-{idp}",defaults={"_locale": "fr"}, name="process_choice_signature", requirements={"idp"="\d+"})
*
*/
public function processChoiceSignature(Request $request, int $idp, $g = 0, $vp = 0, $_locale)
{
#get refere route
$force_today = true;
$referer = $request->headers->get('referer');
if ((strpos($referer, '/recherche') !== false) or (strpos($referer, '/search') !== false)) {
$force_today = false;
}
$selected_params = $this->session->get('search_params');
//get date if selected in cure
if ($request->request->get("departure")) {
$idp = $request->get("id");
$selected_calendar = $request->request->get("departure");
$force_today = false;
}
//get date if selected in search
else if (isset($selected_params['date_start'])) {
$selected_calendar = $selected_params['date_start'];
} else {
$selected_calendar = date("Y-m-d");
}
//if vente privee date now
if ($vp == "1" or $force_today)
$selected_calendar = date("Y-m-d");
$nextday = new \DateTime($selected_calendar . ' 00:00:00');
$nextday->modify('+1 day');
//produit thalasso
$produit = $this->em->getRepository('App\Entity\ProduitThalasso')->findOneById((int)$idp);
if ($g == 1)
$valisGift = "true";
else
$valisGift = "false";
//set data
$dataChoice = array(
"title" => ($produit) ? $produit->getNomProduitThalasso() : "",
"id" => "" . $idp,
"duration" => "1",
"program" => "",
"departure" => "" . $selected_calendar,
"arrival" => "" . $nextday->format('Y-m-d'),
"price" => "0",
"accomodation" => "false",
"isGift" => $valisGift,
"ventePrivee" => $vp,
"soin" => "true",
"duree" => ($produit) ? $produit->getDureeJours() : ""
);
//
//var_dump($dataChoice["departure"]);
//get posted data
$this->session->set('selected_thalasso', $dataChoice);
//remove old session room
$this->session->remove('selected_room');
$this->session->remove('booking_cart');
$this->session->remove('s_code_promotion_step');
if (array_key_exists("isGift", $dataChoice))
$this->session->set('sisGift', $dataChoice["isGift"]);
else
$this->session->set('sisGift', "false");
/* echo "<pre>";
var_dump($g, $dataChoice);
echo "</pre>";
die;*/
//$params['date_start'] = date("Y-m-d", strtotime(str_replace('/', '-',$params['date_start'])));
//return new Response("process_choice_thalasso");
return $this->redirectToRoute('render_mlc_reservation', ['_locale' => $_locale]);
}
/**
* @Route("/{_locale}/process-choice-room", defaults={"_locale": "fr"}, name="process_choice_room")
*
*/
public function processChoiceRoom(Request $request, $_locale)
{
//get posted data
$dataChoice = $request->request->all();
$this->session->set('selected_room', $dataChoice);
//remove old session thalasso
$this->session->remove('selected_thalasso');
$this->session->remove('booking_cart');
$this->session->remove('s_code_promotion_step');
if (array_key_exists("isGift", $dataChoice))
$this->session->set('sisGift', $dataChoice["isGift"]);
else
$this->session->set('sisGift', "false");
/*$epoch = $dataChoice["departure"]/1000;
$date_depart = new \DateTime("@$epoch");
echo $date_depart->format('Y-m-d') . "\n";
$epoch = $dataChoice["arrival"]/1000;
$date_arrival = new \DateTime("@$epoch");
echo $date_arrival->format('Y-m-d') . "\n";*/
/*echo "<pre>";
var_dump($dataChoice);
echo "</pre>";
die;*/
return $this->redirectToRoute('render_mlc_reservation', ['_locale' => $_locale]);
}
/**
* @Route("/{_locale}/process-booking-gift", name="process_booking_gift")
*
*/
public function processBookingGift(Request $request, $_locale)
{
//get posted data
$dataChoice = $request->request->all();
$dataChoice["isGiftCard"] = 1;
# store dataChoice in session
$this->session->set('booking_cart', $dataChoice);
/*echo "<pre>";
var_dump($dataChoice);
echo "</pre>";
die;*/
return $this->redirectToRoute('reservation_login', ["_locale" => $_locale]);
}
/**
* @Route("/{_locale}/process-booking", name="process_booking")
*
*/
public function processBooking(Request $request, $_locale)
{
//default room number
$nbr_rooms = 1;
//get posted data
$dataChoice = $request->request->all();
//get room number if is set
if (array_key_exists("number-room", $dataChoice))
$nbr_rooms = $dataChoice["number-room"];
/*echo "<pre>";
var_dump($dataChoice);
echo "</pre>";
die;*/
//get selected search
$selected_search = $this->session->get('selected_search');
//reset numbers adults and children if posted
if (isset($_POST["room-chambre-1-persons"])) {
$selected_search["total_adults"] = 0;
$selected_search["total_children"] = 0;
for ($key = 1; $key <= $nbr_rooms; $key++) {
if (isset($_POST["room-chambre-" . $key . "-persons"])) {
$nbrPersRoom = explode(",", $_POST["room-chambre-" . $key . "-persons"]);
$selected_search["total_adults"] += (int)$nbrPersRoom[0];
$selected_search["total_children"] += (int)$nbrPersRoom[1];
$selected_search["adults"][$key - 1] = (int)$nbrPersRoom[0];
$selected_search["children"][$key - 1] = (int)$nbrPersRoom[1];
if (isset($_POST["room-chambre-" . $key . "-pension"])) $selected_search["board"][$key - 1] = (int)$_POST["room-chambre-" . $key . "-pension"];
else $selected_search["board"][$key - 1] = "";
}
}
}
//reset numbers adults and children if posted
if (isset($_POST["numcares"])) {
$selected_search["total_adults"] = (int)$_POST["numcares"];
$selected_search["total_children"] = 0;
}
$this->session->set('selected_search', $selected_search);
//get room
$rooms = [];
if (array_key_exists("room", $dataChoice))
$rooms[] = json_decode($dataChoice["room"], true);
elseif (array_key_exists("room1", $dataChoice)) {
for ($key = 1; $key <= $nbr_rooms; $key++) {
$rooms[] = json_decode($dataChoice["room" . $key], true);
}
}
//get prices
$prices = json_decode($dataChoice["prices"], true);
//get supplements
$complements = [];
if (array_key_exists("room-1-complements-sejour", $dataChoice)) {
for ($key = 1; $key <= $nbr_rooms; $key++) {
$tabdet = json_decode($dataChoice["room-" . $key . "-complements-sejour"], true);
$complements[$key]["beneficiaire_comp"] = $key;
$complements[$key]["list_comp"] = $tabdet;
//var_dump($complements); die;
}
}
//get cares
$cares = array();
foreach ($rooms as $key => $room) {
$cares[] = array("chambre_id" => (isset($room["id"]) ? $room["id"] : intval($room)), "list-cares" => json_decode($dataChoice["room-" . ($key + 1) . "-cares"], true));
}
/*echo "<pre>";
var_dump($complements);
echo "</pre>";
die;*/
//init static amounts
$dataChoice["TotalSoins"] = $prices["totalSoins"];
$dataChoice["TotalSejour"] = $prices["totalSejour"];
$dataChoice["TotalSupplements"] = $prices["totalSupplements"];
$dataChoice["TotalTtc"] = $prices["totalTtc"];
//init rooms
$tab_rooms = array();
foreach ($rooms as $key => $room) {
$type_lit_id = 0;
$regime_id = 0;
if (isset($dataChoice["curiste-" . ($key + 1) . "-pension"])) $regime_id = ((int) $dataChoice["curiste-" . ($key + 1) . "-pension"]);
if (isset($dataChoice["room-chambre-" . ($key + 1) . "-pension"])) $regime_id = ((int) $dataChoice["room-chambre-" . ($key + 1) . "-pension"]);
if (isset($dataChoice["room-" . ($key + 1) . "-bed"])) $type_lit_id = ((int) $dataChoice["room-" . ($key + 1) . "-bed"]);
$nbrPersRoom = array(0, 0);
if (isset($_POST["room-chambre-" . ($key + 1) . "-persons"])) $nbrPersRoom = explode(",", $_POST["room-chambre-" . ($key + 1) . "-persons"]);
$tab_rooms[] = array('chambre_id' => (isset($room["id"]) ? $room["id"] : intval($room)), "type_arrangement_id" => 1, "type_lit_id" => $type_lit_id, "regime_id" => $regime_id, "qte_chambre" => 1, "mt_chambre_unite" => 150, "mt_chambre_total" => 150, "total_adults" => $nbrPersRoom[0], "total_children" => $nbrPersRoom[1]);
$dataChoice["tab_rooms"] = $tab_rooms;
}
/*echo "<pre>";
var_dump($cares);
echo "</pre>";
die;*/
//init soins
$tab_cares = array();
foreach ($cares as $keyc => $care) {
if ($care["list-cares"])
foreach ($care["list-cares"] as $key => $caredet) {
$produit = $this->em->getRepository('App\Entity\ProduitThalasso')->findOneById($caredet["id"]);
$tab_cares[] = array('beneficiaire_soin' => $keyc + 1, 'chambre_id' => $care["chambre_id"], "produit_thalasso_id" => $caredet["id"], "qte_soin" => $caredet["value"], "mt_soin_unite" => $caredet["price"], "mt_soin_total" => $caredet["totalPrice"], "label" => $produit->getNomProduitThalasso());
}
}
//init cures
if (array_key_exists("curiste-number", $dataChoice)) {
$tab_cares = array();
for ($i = 1; $i <= $dataChoice["curiste-number"]; $i++) {
if (isset($dataChoice["curiste-" . $i . "-cure"])) {
if (isset($dataChoice["curiste-" . $i . "-pension"])) $regime_id = $dataChoice["curiste-" . $i . "-pension"];
else $regime_id = null;
//static curiste program
$num_programme = 0;
if (isset($dataChoice["curiste-" . $i . "-cure"]))
$num_programme = $dataChoice["curiste-" . $i . "-program"];
$tab_cures[] = array('cure_id' => $dataChoice["curiste-" . $i . "-cure"], "regime_id" => $regime_id, "programme" => $num_programme, "curiste_index" => $i);
foreach (json_decode($dataChoice["curiste-" . $i . "-cares"], true) as $key => $caredet) {
$produit = $this->em->getRepository('App\Entity\ProduitThalasso')->findOneById($caredet["id"]);
$tab_cares[] = array('beneficiaire_soin' => $i, "produit_thalasso_id" => $caredet["id"], "qte_soin" => $caredet["value"], "mt_soin_unite" => $caredet["price"], "mt_soin_total" => $caredet["totalPrice"], "label" => $produit->getNomProduitThalasso());
}
}
}
$dataChoice["tab_cures"] = $tab_cures;
}
$dataChoice["tab_cares"] = $tab_cares;
//init cures simples
if (array_key_exists("numcares", $dataChoice)) {
for ($i = 1; $i <= $dataChoice["numcares"]; $i++) {
$tab_cures[] = array('cure_id' => $dataChoice["curiste-1"], "regime_id" => ((int) 0), "programme" => "", "curiste_index" => $i);
}
$dataChoice["tab_cures"] = $tab_cures;
}
//init supplements
$tab_addons = array();
if ($complements)
foreach ($complements as $keyr => $complementT) {
$beneficiaire = $complementT["beneficiaire_comp"];
if ($complementT["list_comp"])
foreach ($complementT["list_comp"] as $keyr => $complement) {
$supplement = $this->em->getRepository('App\Entity\Supplement')->findOneById($complement["id"]);
$tab_addons[] = array('beneficiaire_complement' => $beneficiaire, 'supplement_id' => $complement["id"], "qte_supplement" => $complement["value"], "mt_supplement_unite" => $complement["price"], "mt_supplement_total" => $complement["totalPrice"], "label" => $supplement->getNomSupplement());
}
}
$dataChoice["tab_addons"] = $tab_addons;
//init ages
$tab_ages = array();
$ages = array();
if (array_key_exists("ages", $dataChoice))
$ages = json_decode($dataChoice["ages"], true);
if ($ages)
foreach ($ages as $key => $age) {
$tab_ages[] = array('age_enfant' => $age["value"]);
}
$dataChoice["tab_ages"] = $tab_ages;
# store dataChoice in session
$this->session->set('booking_cart', $dataChoice);
# disable nrr if promotion
$promotions_list = $this->session->get('promotions_list');
if ($promotions_list && is_object($promotions_list)) {
$promotions_list = get_object_vars($promotions_list);
if ($promotions_list && array_key_exists("message", $promotions_list) && $promotions_list["message"] != "") {
$this->session->set('nrr_toapply', 0);
}
}
return $this->redirectToRoute('reservation_login', ["_locale" => $_locale]);
}
/**
* @Route("/reservations/promotion", name="reservations_promotion")
*/
public function reservationsPromotion(Request $request)
{
/* thalasso avec heberegement :{"calendar-start":"2021-09-13","calendar-end":"2021-09-19","nights":"6","curiste-number":"2","children-number":"1","curiste-1-cure":"1","curiste-1-pension":"1","curiste-1-program":"1","curiste-2-cure":"1","curiste-2-pension":"1","curiste-2-program":"1","room":"1","comments":"","visit":"visit-no","curiste-1-cares":"","curiste-2-cares":"","room-1-cares":"","room-1-complements-sejour":"","room-1-bed":"","ages":"","prices":""}*/
/* thalasso avec heberegement
{"calendar-start":"2021-11-16","calendar-end":"2021-11-22","nights":"6","curiste-number":"2","children-number":"1","curiste-1-cure":"1","curiste-1-pension":"1","curiste-1-program":"1","curiste-2-cure":"1","curiste-2-pension":"1","curiste-2-program":"1","room":"1","code_promotion":"","comments":"","visit":"visit-no","curiste-1-cares":"","curiste-2-cares":"","room-1-cares":"","room-1-complements-sejour":"","room-1-bed":"","ages":"","prices":"","room-chambre-1-bed":""}
*/
/* cure
{"calendar-start":"2021-11-17","calendar-end":"2021-11-21","nights":"4","curiste-number":"2","curiste-1-cure":"1","curiste-1-pension":"1","curiste-1-program":"1","curiste-2-cure":"1","curiste-2-pension":"1","curiste-2-program":"1","code_promotion":"","comments":"","visit":"visit-no","curiste-1-cares":"","curiste-2-cares":"","room-1-cares":"","room-1-complements-sejour":"","room-1-bed":"","ages":"","prices":"","room-chambre-1-bed":""}
*/
/* care
{"calendar-start":"2021-09-15","numcares":"1","curiste-1":"1","code_promotion":"","comments":"","visit":"visit-no","curiste-1-cares":"","curiste-2-cares":"","room-1-cares":"","room-1-complements-sejour":"","room-1-bed":"","ages":"","prices":"","room-chambre-1-bed":""}
*/
$mode_debug = false;
$msgdebug = "";
$today = date("Y-m-d");
$days_earlybooking = false;
if ($request && $request->getContent()) {
$params = json_decode($request->getContent(), true);
$id_chambre = null;
if ($params) {
if (array_key_exists("number-room", $params)) $nbr_rooms = $params["number-room"];
else $nbr_rooms = 1;
if (array_key_exists("curiste-1", $params)) $id_thalasso = $params["curiste-1"];
elseif (array_key_exists("curiste-1-cure", $params)) $id_thalasso = $params["curiste-1-cure"];
else $id_thalasso = null;
if (array_key_exists("numcares", $params)) $qte_thalasso = $params["numcares"];
else $qte_thalasso = 1;
for ($i = 1; $i <= 1; $i++) {
if (array_key_exists("room" . $i, $params)) $id_chambre = $params["room" . $i];
}
if (array_key_exists("room", $params)) $id_chambre = $params["room"];
$date_begin = $params["calendar-start"];
if (array_key_exists("calendar-end", $params)) $date_end = $params["calendar-end"];
else $date_end = $params["calendar-start"];
if (array_key_exists("curiste-1-pension", $params)) $regime = $params["curiste-1-pension"];
else $regime = null;
if (array_key_exists("nights", $params)) $duration = $params["nights"];
else $duration = 1;
}
$days_earlybooking = round((strtotime($date_begin) - strtotime($today)) / (60 * 60 * 24));
}
if ($mode_debug)
$msgdebug = "<br><h3>Values send from page :</h3>" . $request->getContent();
$params_promo_dyn = [
'today' => $today,
'id_thalasso' => $id_thalasso,
'qte_thalasso' => $qte_thalasso,
'id_chambre' => $id_chambre,
'date_debut' => $date_begin,
'date_fin' => $date_end,
'regime' => $regime,
'duration' => $duration,
];
if ($mode_debug)
$msgdebug .= "<br><h3>Dynamic values for promo :</h3>" . json_encode($params_promo_dyn);
//for static test
///debug/promo-test?today=2021-09-02&id_thalasso=26&qte_thalasso=3&id_chambre=51&date_debut=2021-09-03&date_fin=2021-09-04®ime=2&duration=2
$params_promo = [
'today' => "2021-11-02",
'id_thalasso' => 88,
'qte_thalasso' => 1,
'id_chambre' => 51,
'date_debut' => "2021-11-02",
'date_fin' => "2021-11-08",
'regime' => 4,
'duration' => 6,
];
$params_promo_calcul = $params_promo_dyn;
$promos = $this->em->getRepository('App\Entity\Promotion')->getPomotionsSteps($params_promo_calcul);
// switch nrr
$nrr_last_value = $this->getNrrLastValue($params_promo_calcul);
//disable promo if gift
if ($this->session->get('sisGift') == "true")
$promos = [];
$caseIndex = 0;
$status_globale = 1;
//Init variables
$messages[] = "";
$types[] = "message";
$values[] = 0;
$arrhes_100[] = false;
//promotions dynmiques
foreach ($promos as $key => $promo) {
$promocurrent = $this->em->getRepository('App\Entity\Promotion')->findOneById($promo["id_promotion"]);
$status_globale = 1;
if ($promocurrent) {
//tab application 1curiste 2 curiste etc
$tab_application = [];
foreach ($promocurrent->getApplications() as $key => $appli) {
$tab_application[] = $appli->getId();
}
//case (promo % type id =2, $params["curiste-number"]
if (in_array($promo["id_type_promotion"], [2])) {
$messages[] = $promocurrent->getNomPromotion();
$arrhes_100[] = $promocurrent->getArrhes100();
$types[] = "message"; //case type promotion
$values[] = 0; //case type promotion
$caseIndex++;
}
//case (promo -x euros type id =3, $params["curiste-number"]
if (in_array($promo["id_type_promotion"], [3])) {
if (
!array_key_exists("curiste-number", $params)
or (array_key_exists("curiste-number", $params) && in_array(intval($params["curiste-number"]), $tab_application))
) {
$messages[] = $promocurrent->getNomPromotion();
$arrhes_100[] = $promocurrent->getArrhes100();
$types[] = "message"; //case type promotion
$values[] = 0; //case type promotion
$caseIndex++;
}
}
//case pourcentage (promo volume type id =6,
if (in_array($promo["id_type_promotion"], [6])) {
$dispos = $this->em->getRepository('App\Entity\DispoProduit')->getApiProductCalendar($params_promo_calcul["id_thalasso"], $params_promo_calcul["id_chambre"], true, false, 'fr', $date_begin, $date_end);
if (count($dispos) > 0) {
$dispo = $dispos[0];
$regime_data = $dispo["regime_data"];
$regime_data = explode(",", $regime_data);
foreach ($regime_data as $key => $regime_price) {
$regime_price = explode("|", $regime_price);
$prix_formule1_sejour = ($dispo["price_simple_individuelle"] * $dispo["multiplicateur_regime_promo"] * 1);
$prix_formule2_sejour = ($dispo["price_simple"] * $dispo["multiplicateur_regime_promo"] * 1);
$prix_formule3_sejour = ($dispo["prix_accompagnant"] * $dispo["multiplicateur_regime_promo"] * $dispo["duree"] * 1);
$prix_formule1_regime = ($regime_price[3] * $dispo["multiplicateur_regime_promo"] * $dispo["duree"] * 1);
$prix_formule2_regime = ($regime_price[3] * $dispo["multiplicateur_regime_promo"] * $dispo["duree"] * 1);
$prix_formule3_regime = ($regime_price[3] * $dispo["multiplicateur_regime_promo"] * $dispo["duree"] * 1 * 2);
$prices[$regime_price[0]][$params_promo_calcul["id_chambre"]] = array("formule1" => $prix_formule1_sejour, "formule2" => $prix_formule2_sejour, "formule3" => $prix_formule3_sejour);
$prices_regimes[$regime_price[0]][$params_promo_calcul["id_chambre"]] = array("formule1" => $prix_formule1_regime, "formule2" => $prix_formule2_regime, "formule3" => $prix_formule3_regime);
}
}
if ($mode_debug)
$msgdebug .= "<br><h3>prices :</h3>" . json_encode($prices);
if ($mode_debug)
$msgdebug .= "<br><h3>prices regimes :</h3>" . json_encode($prices_regimes);
//cases of type prestation ************************
$value_to_substract = 0;
$display_promo = false;
$types_msg = "message";
$comp_title_promo = "";
//case accompagnant
if ($promo["id_type_prestation"] == 1 && array_key_exists("curiste-number", $params) && $params["curiste-number"] == "3") {
if (array_key_exists($regime, $prices_regimes))
$value_to_substract = $prices[$regime][$params_promo_calcul["id_chambre"]]["formule3"];
$display_promo = true;
$types_msg = "substraction";
}
//case arrangement
if ($promo["id_type_prestation"] == 2 && array_key_exists("curiste-number", $params)) {
if (array_key_exists($regime, $prices_regimes))
$value_to_substract = $prices_regimes[$regime][$params_promo_calcul["id_chambre"]]["formule" . $params["curiste-number"]];
$display_promo = true;
$types_msg = "substraction";
}
//case nuit offerte
if ($promo["id_type_prestation"] == 4) {
$value_to_substract = 0;
$display_promo = true;
$types_msg = "message";
}
//case supplement offert
if ($promo["id_type_prestation"] == 5) {
//get supplements
$label_tab_suuplement_offert = [];
foreach ($promocurrent->getSupplement() as $key => $supplement) {
if ($supplement) $label_tab_suuplement_offert[] = $supplement->getNomSupplement();
}
if (count($label_tab_suuplement_offert) > 0) $comp_title_promo = "(" . implode(", ", $label_tab_suuplement_offert) . ")";
$value_to_substract = 0;
$display_promo = true;
$types_msg = "message";
}
//case thalasso offert
if ($promo["id_type_prestation"] == 3) {
//get supplements
$label_tab_prod_offert = [];
foreach ($promocurrent->getPromotionSoins() as $key => $produit) {
if ($produit) $label_tab_prod_offert[] = $produit->getNomProduitThalasso();
}
if (count($label_tab_prod_offert) > 0) $comp_title_promo = "(" . implode(", ", $label_tab_prod_offert) . ")";
$value_to_substract = 0;
$display_promo = true;
$types_msg = "message";
}
//case perso
if ($promo["id_type_prestation"] == 6) {
$value_to_substract = 0;
$display_promo = true;
$types_msg = "message";
}
//End cases of type prestation ************************
if ($display_promo) {
$messages[] = $promocurrent->getNomPromotion() . " " . $comp_title_promo;
$arrhes_100[] = $promocurrent->getArrhes100();
$types[] = $types_msg; //case type promotion
$values[] = $value_to_substract;
$caseIndex++;
}
}
//case display only (promo surclassement type id =7, promo Xnuit achetees Y nuits offertes type id =5, promo Xnuit achetees Y nuits offertes type id =6)
if (in_array($promo["id_type_promotion"], [5])) {
$montant_sejour = 0;
if (isset($params_promo_calcul["duration"]) && isset($params["prices"])) {
$montant_sejour = $params["prices"]["stay"];
}
$montant_sejour = $montant_sejour / $params_promo_calcul["duration"];
$messages[] = $promocurrent->getNomPromotion();
$arrhes_100[] = $promocurrent->getArrhes100();
$types[] = "substraction"; //case type promotion
$values[] = $montant_sejour; //case type promotion
$caseIndex++;
}
//case display only (promo surclassement type id =7, promo Xnuit achetees Y nuits offertes type id =5, promo Xnuit achetees Y nuits offertes type id =6)
if (in_array($promo["id_type_promotion"], [7])) {
$messages[] = $promocurrent->getNomPromotion();
$arrhes_100[] = $promocurrent->getArrhes100();
$types[] = "message"; //case type promotion
$values[] = 0; //case type promotion
$caseIndex++;
}
//case promo volume type id =8,
if (in_array($promo["id_type_promotion"], [8])) {
$messages[] = $promocurrent->getNomPromotion();
$arrhes_100[] = $promocurrent->getArrhes100();
$types[] = "percentage"; //case type promotion
$values[] = 1 - (intval($promo["pourcentage"]) / 100); //case type promotion
$caseIndex++;
}
}
}
//promotion early booking
if ($days_earlybooking > 0 && ($caseIndex == 0)) {
$earlybooking = $this->em->getRepository('App\Entity\EarlyBooking')->getEarlyreduction($days_earlybooking);
if (count($earlybooking) > 0 && array_key_exists("pourcentage", $earlybooking)) {
$messages[] = "Early booking " . intval($earlybooking["pourcentage"]) . "%";
$types[] = "percentage"; //case type promotion
$values[] = 1 - (intval($earlybooking["pourcentage"]) / 100); //case pmailerpmailer
}
}
//promotion code promo
$code_promocheck = "";
if (array_key_exists("code_promotion", $params))
$code_promocheck = $params["code_promotion"];
elseif ($this->session->get('s_code_promotion_step') && $this->session->get('s_code_promotion_step') != "") {
$code_promocheck = $this->session->get('s_code_promotion_step');
}
if (($caseIndex == 0) && $code_promocheck != "") {
$codepromo = $this->em->getRepository('App\Entity\CodePromo')->findOneByParams($code_promocheck, $params_promo_calcul);
if ($codepromo) {
if ($codepromo->getPourcentageCodePromo() > 0 && strtolower($codepromo->getTypeCodePromo()) == "pourcentage") {
$messages[] = $codepromo->getNomCodePromo();
$types[] = "percentage";
$values[] = 1 - ($codepromo->getPourcentageCodePromo() * 1 / 100);
$this->session->set('s_code_promotion_step', $codepromo->getCodePromo());
$caseIndex++;
} elseif ($codepromo->getMontantCodePromo() > 0 && strtolower($codepromo->getTypeCodePromo()) == "montant") {
$messages[] = $codepromo->getNomCodePromo();
$types[] = "substraction";
$values[] = $codepromo->getMontantCodePromo() * 1;
$this->session->set('s_code_promotion_step', $codepromo->getCodePromo());
$caseIndex++;
}
} else {
$messages[] = 'Code promo "' . $code_promocheck . '" invalide.';
$types[] = "message";
$values[] = 0;
$status_globale = 0;
$caseIndex++;
}
}
if ($mode_debug && $caseIndex == 0) {
//promotion pour debug
$messages[] = "Promotion for debug only";
$types[] = "message"; //case type promotion
$values[] = 0; //case type promotion
$caseIndex++;
}
//exit;
/*$messages = [
"",
"Promotion cas 1 avec soustraction -200€ ".$params["calendar-start"],
"Promotion cas 2 avec pourcentage 80%",
"Promotion cas 3 avec juste un message",
];
$types = [
"",
"substraction",
"percentage",
"message"
];
$values = [
0,
200,
0.8,
0
];*/
$data = (object)[
"show" => $caseIndex !== 0,
"message" => $messages[$caseIndex] . $msgdebug,
"arrhes_100" => $arrhes_100[$caseIndex] ,
"type" => $types[$caseIndex],
"value" => $values[$caseIndex],
"status" => $status_globale,
"nrr" => $caseIndex < 1 && $nrr_last_value > 0 ? true : false,
];
//create session for promotion
$this->session->set('promotions_list', $data);
return new JsonResponse($data);
}
public function changeBookingStock($token = null)
{
//find resrvation by token
$reservation = $this->em->getRepository(Reservation::class)->findOneBy(["token_reservation" => $token]);
$log_changebook = "";
if ($reservation) {
$date_start = $reservation->getDateReservation() ? $reservation->getDateReservation()->format('Y-m-d') : null;
$date_end = $reservation->getDateDepart() ? $reservation->getDateDepart()->format('Y-m-d') : null;
// Case thalasso
$log_changebook .= "<br><br>*********** destockage cures ";
foreach ($reservation->getReservationCures() as $key => $cure) {
// Case thalasso
$prod_id = $cure->getProduitThalasso()->getId();
$value = $cure->getQteCure();
$type = "down";
if ($date_start != null && $date_end != null && $value > 0) {
$dispoproduit = $this->em->getRepository(DispoProduit::class)->changeStock($prod_id, $date_start, $date_end, $value, $type);
$log_changebook .= "<br>- La cure id : " . $prod_id . " a été destocké de " . $value . " entre le : " . $date_start . " et " . $date_end;
}
}
$log_changebook .= "<br><br>*********** destockage soins ";
// Case soins
foreach ($reservation->getReservationSoins() as $key => $soin) {
$prod_id = $soin->getProduitThalasso()->getId();
$value = $soin->getQteSoin();
$type = "down";
if ($date_start != null && $date_end != null && $value > 0) {
$dispoproduit = $this->em->getRepository(DispoProduit::class)->changeStock($prod_id, $date_start, $date_end, $value, $type);
$log_changebook .= "<br>- Le soin id : " . $prod_id . " a été destocké de " . $value . " entre le : " . $date_start . " et " . $date_end;
}
}
$log_changebook .= "<br><br>*********** destockage chambres ";
// Case chambre
foreach ($reservation->getReservationChambres() as $key => $chambre) {
$room_id = $chambre->getChambre()->getId();
$value = $chambre->getQteChambre();
$type = "down";
if ($date_start != null && $date_end != null && $value > 0) {
$dispoproduit = $this->em->getRepository(DispoChambre::class)->changeStock($room_id, $date_start, $date_end, $value, $type);
$log_changebook .= "<br>- La chambre id : " . $room_id . " a été destocké de " . $value . " entre le : " . $date_start . " et " . $date_end;
}
}
$log_changebook .= "<br><br>*********** destockage supplements ";
// Case chambre
foreach ($reservation->getReservationSupplements() as $key => $supp) {
$supplement_id = $supp->getSupplement()->getId();
$value = $supp->getQteSupplement();
$type = "down";
if ($date_start != null && $date_end != null && $value > 0) {
$dispoproduit = $this->em->getRepository(DispoSupplement::class)->changeStock($supplement_id, $date_start, $date_end, $value, $type);
$log_changebook .= "<br>- Le supplement id : " . $supplement_id . " a été destocké de " . $value . " entre le : " . $date_start . " et " . $date_end;
}
}
//reduce code promo if existe
$log_changebook .= "<br><br>*********** destockage code promo ";
foreach ($reservation->getReservationCodePromos() as $key => $cp) {
$codepromo = $this->em->getRepository(CodePromo::class)->changeStock($cp->getCodePromo());
$log_changebook .= "<br>- Le code promo : " . $cp->getCodePromo() . " a été destocké de 1 ";
}
} else {
$log_changebook .= "<br><br>!!!! aucune reservation avec le token :" . $token;
}
return $log_changebook;
}
/**
* @Route("/bookapi/boking-stock/{token}")
*/
public function debugChangeBookingStock($token = null)
{
$logs = $this->changeBookingStock($token);
echo $logs;
return new Response("<br><br><br>Change stock for booking " . $token);
}
public function verifRedirectSession()
{
$search_params = $this->session->get('search_params');
$booking_cart_sess = $this->session->get('booking_cart');
if( (!$search_params || !isset($search_params['date_start']) || !isset($search_params['date_end']) || !isset($search_params['duration']) ) && !isset($booking_cart_sess['isGiftCard']) )
return $this->redirect($this->generateUrl('default_hotel_page', ['hostname' => $_SERVER['HTTP_HOST']]));
else
return false;
}
public function verifProductNrr($id_product=0)
{
$nrr_val = false;
$search_params=$this->session->get('search_params');
$produit = $this->em->getRepository(ProduitThalasso::class)->findOneById($id_product);
if($produit && $produit->getNrr())
{
$nrr_val = true;
}
return $nrr_val;
}
public function verifRoomNrr($id_chambre=0)
{
$nrr_val = false;
$search_params=$this->session->get('search_params');
$chambre = $this->em->getRepository(Chambre::class)->findOneById($id_chambre);
if($chambre && $chambre->getNrr())
{
$nrr_val = true;
}
return $nrr_val;
}
public function getNrrLastValue($datacheck)
{
$search_params = $this->session->get('search_params');
$this->session->set('nrr_toapply', 0);
$pourcentage_nrr= 0;
//apply NRR to room
if($datacheck["id_thalasso"] == 0 && $datacheck["id_chambre"] !=0)
{
$parm_pourcentage_nrr= $this->em->getRepository("App\Entity\Parametrage")->findOneByCode("nrr_hotel");
if($parm_pourcentage_nrr && $parm_pourcentage_nrr->getvarValue() && $this->verifRoomNrr($datacheck["id_chambre"]))
{
$pourcentage_nrr=$parm_pourcentage_nrr->getvarValue();
$this->session->set('nrr_toapply', $pourcentage_nrr);
}
return $pourcentage_nrr;
}
//apply NRR to thalasso
if($datacheck["id_thalasso"] != 0)
{
if($search_params['type_bar'] == 4)
{
if(false)
{
//apply NRR
$parm_pourcentage_nrr= $this->em->getRepository("App\Entity\Parametrage")->findOneByCode("nrr_soins");
if($parm_pourcentage_nrr && $parm_pourcentage_nrr->getvarValue() && $this->verifProductNrr($datacheck["id_thalasso"]) )
{
$pourcentage_nrr=$parm_pourcentage_nrr->getvarValue();
$this->session->set('nrr_toapply', $pourcentage_nrr);
}
}
else {
//apply NRR
$parm_pourcentage_nrr= $this->em->getRepository("App\Entity\Parametrage")->findOneByCode("nrr_thalasso_sans_hebergement");
if($parm_pourcentage_nrr && $parm_pourcentage_nrr->getvarValue() && $this->verifProductNrr($datacheck["id_thalasso"]))
{
$pourcentage_nrr=$parm_pourcentage_nrr->getvarValue();
$this->session->set('nrr_toapply', $pourcentage_nrr);
}
}
}
if($search_params['type_bar'] == 3) {
//apply NRR
$parm_pourcentage_nrr= $this->em->getRepository("App\Entity\Parametrage")->findOneByCode("nrr_thalasso_avec_hebergement");
if($parm_pourcentage_nrr && $parm_pourcentage_nrr->getvarValue() && $this->verifProductNrr($datacheck["id_thalasso"]))
{
$pourcentage_nrr=$parm_pourcentage_nrr->getvarValue();
$this->session->set('nrr_toapply', $pourcentage_nrr);
}
}
}
return $pourcentage_nrr;
}
}