<?php
namespace App\Controller;
use Pimcore\Controller\FrontendController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Contracts\Translation\TranslatorInterface;
use Pimcore\Model\DataObject;
use Pimcore\Model\Document;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Routing\Annotation\Route;
use Pimcore\Model\WebsiteSetting;
use App\Form\ExpertiseFormType;
use App\Form\InscriptionFormType;
use App\Form\ContactModalFormType;
use Pimcore\Mail;
use Carbon\Carbon;
use Pimcore\Model\DataObject\Folder;
use App\Service\Akimedia;
use Pimcore\Bundle\AdminBundle\HttpFoundation\JsonResponse;
use GuzzleHttp\Client;
use Pimcore\Tool\Session;
class InscriptionController extends FrontendController
{
/**
* @Template
* @param Request $request
* @route("/{_locale}/inscription-centre/{id}", name="inscriptionCentre",methods={"GET", "POST"})
* @return \Symfony\Component\HttpFoundation\Response
*
*/
public function inscriptionCentreAction(Request $request, \Symfony\Contracts\Translation\TranslatorInterface $translator)
{
$session = $request->getSession();
$CentreId = $request->get('id');
$token = $session->get('akimedia-token');
$errorMessage = "";
if(!$token){
$token = Akimedia::login();
$session->set("akimedia-token", $token);
}
$dateComponents = getdate();
$month = date("n");
$year = $dateComponents['year'];
for($i=0;$i<6;$i++){
$currentMonth = $month+$i;
if($currentMonth>12):
$m = $currentMonth-12;
$y = $year+1;
else:
$m = $currentMonth;
$y = $year;
endif;
$cal[$i] = $this->build_calendar($m,$y,$CentreId,$translator);
}
// to comment start
$calJuillet = $this->build_calendar($month,$year,$CentreId,$translator);
if($month >= 11){
if($month==12){
$calAout = $this->build_calendar(1,$year+1,$CentreId,$translator);
$calSeptembre = $this->build_calendar(2,$year+1,$CentreId,$translator);
}else{
$calAout = $this->build_calendar($month+1,$year,$CentreId,$translator);
$calSeptembre = $this->build_calendar(1,$year+1,$CentreId,$translator);
}
}else{
$calAout = $this->build_calendar($month+1,$year,$CentreId,$translator);
$calSeptembre = $this->build_calendar($month+2,$year,$CentreId,$translator);
}
$tomorrow = Carbon::now()->addDay();
$date['weekStartDate'] = $tomorrow->startOfWeek()->format('d/m/Y');
$date['weekEndDate'] = $tomorrow->endOfWeek()->format('d/m/Y');
$yearAllowed = [];
$yearAllowed['year'] = 18;
$settingYearAllowed = WebsiteSetting::getByName('InscriptionYearAllowed');
if($settingYearAllowed) {
$yearAllowed['max'] = Carbon::now()->subYears($settingYearAllowed->getData());
$yearAllowed['year'] = $settingYearAllowed->getData();
} else {
$yearAllowed['max'] = Carbon::now()->subYears($yearAllowed['year']);
}
$yearAllowed['min'] = Carbon::now()->subYears(130);
$horaires = Akimedia::getSiteAvailabilities($request, $CentreId);
$centre = Akimedia::getSiteInfos($request, $CentreId);
//dd($centre);
if ($request->isMethod("POST")) {
$data = [
'datenaissance' => $request->get("dtenaissance"),
'token' => uniqid(),
'date' => $request->get("date"),
'heure' => $request->get("heure"),
'firstname' => $request->get("firstname"),
'lastname' => $request->get("lastname"),
'email' => $request->get("email"),
'phone' => $request->get("phone"),
'dejaDonnePlasma' => $request->get("alreadyPlasma"),
'dejaDonneSang' => $request->get("alreadyBlood"),
'type' => 'plasma',
];
$return = Akimedia::sendIncriptionSite($request, $data, $request->get("akimedia-centre"));
if($return !== true){
$errorMessage = $return;
}else{
// redirect vers merci
return $this->redirectToRoute("merci");
}
}
return $this->render('inscription/inscription-centre.html.twig',[
"centre" => $centre,
"dates" => $horaires,
"calendriers" => $cal,
"Juillet" => $calJuillet,
"Aout" => $calAout,
"Septembre" => $calSeptembre,
"errorMessage" => $errorMessage,
"date" => $date,
"yearAllowed" => $yearAllowed
]);
}
/**
* @Template
* @param Request $request
* @return \Symfony\Component\HttpFoundation\Response
*
*/
#[Route(path:[
'fr' => '/{_locale}/merci',
'de' => '/{_locale}/danke',
'nl' => '/{_locale}/bedankt',
], name: 'merci')]
public function merciAction(Request $request)
{
return $this->render('inscription/merci.html.twig',[
]);
}
//new full akimedia logic
/**
* @Route("gethorairecentreakimedia", name="getHoraireCentreAkimedia")
*
*/
public function gethorairecentreakimediaAction(Request $request, \Symfony\Contracts\Translation\TranslatorInterface $translator)
{
$session = $request->getSession();
$token = $session->get('akimedia-token');
if(!$token){
$token = Akimedia::login();
$session->set('akimedia-token', $token);
}
$lang = $request->get('lang');
$CentreId = $request->get("centreid");
$GetDate = $request->get("date");
$date = $GetDate . " 00:00";
$date1 = $GetDate . " 23:59";
$horairesResults = Akimedia::getSiteHorairesByDate($request, $CentreId);
$horaires = $horairesResults["plages"];
$objectif = $horairesResults["objectif_plasma_atteint"];
if($objectif){
$HoraireControle = "<span style='background:#fff6ee; border:1px solid #F6A507; padding:5px 10px;'>".$translator->trans('Nos objectifs sont atteints pour ce jour.')."</span>";
}elseif ($horaires && count($horaires) > 0) {
$HoraireControle = '';
$HoraireList = '';
$HoraireControle .= '<div>';
$HoraireControle .= '<label class="control-label">Choisissez votre horaire de départ</label>';
$count = 1;
foreach ($horaires as $h) {
if (strtotime($GetDate." ".$h['horaire']) >= strtotime($date) && strtotime($GetDate." ".$h['horaire']) <= strtotime($date1)) {
if ($h['horaire']) {
$horaire_i = 1;
$PlaceLibrre = $h['available'];
if($PlaceLibrre <= 0){
continue;
}
$now = Carbon::now();
$dateCalendar = Carbon::parse($GetDate." ".$h['horaire']);
$cuurentTime = date($h['horaire']);
if($now->gt($dateCalendar)){
continue;
}
$checked = '';
if ($PlaceLibrre <= 0) {
$checked = ' disabled ';
}
if ($PlaceLibrre <= 0) {
$class_state = "is-disabled";
} else {
$class_state = "is-active";
}
$HoraireList .= '<div class="uk-width-1-1 schedule-item-container"><div class="schedule-item ' . $class_state . '">
<label for="Hdeb' . $horaire_i . '">' . $cuurentTime . ' <small style=" font-size: 15px;">(' . $PlaceLibrre . ' ' . $translator->trans('places restantes', [], null, $lang) . ')';
$HoraireList .='</small></label>';
if ($PlaceLibrre > 0) {
$HoraireList .= '<input data-id="' . $GetDate . '" type="radio" required name="inscription"
value="' . $cuurentTime . '" ' . $checked . ' ' . '
id="Hdeb' . $horaire_i . '" class="uk-radio" />';
}
$HoraireList .= '</div></div>';
if ($count % 4 == 0):
$HoraireList .= '</div></div></li><li><div><div class="uk-grid-small" uk-grid>';
endif;
$horaire_i++;
$count++;
}
}
}
if($HoraireList){
$HoraireControle .= '<div uk-slider="finite: true;">
<div class="uk-position-relative">
<div class="uk-slider-container uk-light">
<ul class="uk-slider-items uk-child-width-1-2@s uk-grid-small">
<li><div><div class="uk-grid-small" uk-grid>';
$HoraireControle .= $HoraireList;
$HoraireControle .= '</div></div></li></ul></div>';
$HoraireControle .= '<div class="uk-hidden@s uk-light">
<a class="uk-position-center-left uk-position-small" href="#" uk-slidenav-previous uk-slider-item="previous"></a>
<a class="uk-position-center-right uk-position-small" href="#" uk-slidenav-next uk-slider-item="next"></a>
</div>
<div class="uk-visible@s">
<a class="uk-position-center-left-out uk-position-small" href="#" uk-slidenav-previous uk-slider-item="previous"></a>
<a class="uk-position-center-right-out uk-position-small" href="#" uk-slidenav-next uk-slider-item="next"></a>
</div>
</div>
<ul class="uk-slider-nav uk-dotnav uk-flex-center uk-margin"></ul>
</div>';
$HoraireControle .= '</div>';
}else{
$HoraireControle = "<span style='color: red'>".$translator->trans("Nous n’avons pas de possibilités de rendez-vous pour la date choisie.")."</span>";
}
} else {
$HoraireControle = "<span style='color: red'>".$translator->trans("Nous n’avons pas de possibilités de rendez-vous pour le date choisie.")."</span>";
}
$msg2 = "ok";
$response = array('type' => 'succes', 'msg' => $HoraireControle, 'resultat' => $CentreId . ' ' . $date, 'msg2' => $msg2);
return new JsonResponse($response);
}
/**
* @Template
*
* @param Request $request
*
* @param DataObject $object
* @Route("/{_locale}/inscription-plasma", name="formEligibleInscription")
*
* @return response
*
*/
public function formEligibleInscriptionAction(Request $request) {
/*
if(WebsiteSetting::getByName('akimediaActivate')) {
$id = $request->get('id');
if($this->editmode){
$id = 1;
}
if($id){
return $this->render('inscription/form-eligibilite-inscription.html.twig',[
'centre' => $id
]);
}else{
if($this->document->getProperty('listeCentresPlasma')) {
return $this->redirect($this->document->getProperty('listeCentresPlasma'));
} else {
return $this->redirect('/');
}
}
} else {
$session = $request->getSession();
if($request->get('centre') && $request->get('centre')){
$session->set('centre', $request->get('centre'));
$url = explode("?", $_SERVER['REQUEST_URI']);
return $this->redirect($url[0]);
}
if($this->editmode){
$session->set('centre', 2559);
}
if($session->get('centre')>0){
return $this->render('inscription/form-eligibilite-inscription.html.twig',[
'centre' => $session->get('centre')
]);
}else{
if($this->document->getProperty('listeCentresPlasma')) {
return $this->redirect($this->document->getProperty('listeCentresPlasma'));
} else {
return $this->redirect('/'. $request->getLocale());
}
}
}
*/
$id = $request->get('id');
$session = $request->getSession();
$session->set('centre', $request->get('id'));
if($this->editmode){
$id = 1;
}
if($id){
return $this->render('inscription/form-eligibilite-inscription.html.twig',[
'centre' => $id
]);
}else{
if($this->document->getProperty('listeCentresPlasma')) {
return $this->redirect($this->document->getProperty('listeCentresPlasma'));
} else {
return $this->redirect('/');
}
}
}
/**
* @Template
* @param Request $request
* @param DataObject $object
* @return response
*
*/
public function defaultContactAction(Request $request)
{
if(!WebsiteSetting::getByName('akimediaActivate')) {
$centres = null; // On ne récupère plus plusieurs centres mais un seul
//Formulaire d'inscription
$formStatus = false;
$ddsHoraires = false;
$centre = false;
$lang = $request->getLocale();
$session = $request->getSession();
$CentreId = $session->get('centre');
$token = $session->get('akimedia-token');
$errorMessage = "";
if(!$token){
$token = Akimedia::login();
$session->set("akimedia-token", $token);
}
$centre = Akimedia::getSiteInfos($request, $CentreId);
if(!$centre) {
if($this->document->getProperty('listeCentresPlasma')) {
return $this->redirect($this->document->getProperty('listeCentresPlasma'));
} else {
return $this->redirect('/'. $lang);
}
}
} else {
$session = $request->getSession();
$CentreId = $session->get('centre');
//Formulaire d'inscription
$formStatus = false;
$ddsHoraires = false;
$centre = false;
$lang = $request->getLocale();
if(strpos(WebsiteSetting::getByName('horairesCentresApi')->getData(), 'dds') !== false) {
$ddsHoraires = true;
$centres = null; // On ne récupère plus plusieurs centres mais un seul
//gestion guzzle
$client = new Client();
$response = $client->request('POST', "https://www.donneurdesang.be/". $request->getLocale() ."/api/centres-by-provinces", [
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
]
]);
$results = json_decode($response->getBody(), true);
$apiCentres = $results;
//Boucle pour récupérer le bon centre
foreach($apiCentres as $apiCentre) {
if($apiCentre["o_id"] == $CentreId) {
$centre = $apiCentre;
continue;
}
}
} else {
$centres = new DataObject\Centres\Listing();
$centres->load();
}
//Suppression des paramètres et redirect
if($request->get('centre') && $request->get('centre')){
$session->set('centre', $request->get('centre'));
$url = explode("?", $_SERVER['REQUEST_URI']);
return $this->redirect($url[0]);
}
if($this->editmode){
$session->set('centre', 2559);
}
if(!$centre) {
if($this->document->getProperty('listeCentresPlasma')) {
return $this->redirect($this->document->getProperty('listeCentresPlasma'));
} else {
return $this->redirect('/'. $lang);
}
}
}
//////////////////////////////////////////////////
// initialize form and handle request data
$formContact = $this->createForm(InscriptionFormType::class, null);
$formContact->handleRequest($request);
// On vérifie si un POST a bien été effectué et donc si le formulaire a été envoyé
if ($formContact->isSubmitted() && $formContact->isValid()) {
$data = $formContact->getData();
$email = $data['email'];
$phone = $data['phone'];
$firstname = $data['firstname'];
$lastname = $data['lastname'];
$birthday = $data['birthday'];
$sang = $data['sang'];
$plasma = $data['plasma'];
$gdpr = $data['gdpr'];
$data['centreId'] = $request->get("inscription_form_centre");
if(WebsiteSetting::getByName('akimediaActivate')) {
if($ddsHoraires) {
//$centre = DataObject\Centres::getByCodeCentre($data['centreId']);
$convertCentre = DataObject\Centres::getByCodeCentre($centre['codeCentre']);
$convertCentre = $convertCentre->load();
$data['centre'] = $convertCentre[0];
} else {
$centre = DataObject\Centres::getByAkimediaId($data['centreId']);
$centre = $centre->load();
$data['centre'] = $centre[0];
}
} else {
$centreObj = DataObject\Centres::getByAkimediaId($data['centreId']);
$centreObj = $centreObj->load();
$data['centre'] = $centreObj[0];
}
if($email != $request->get("inscription_form_confirmation")){
$viewContactForm = $formContact->createView();
return[
'centre' => $centre, // Ajout Greg pour reprendre la data depuis dds
'centres' => $centres,
'form' => $viewContactForm,
'formStatus' => $formStatus,
'error' => true,
'lang' => $lang
];
}
// On vérifie que tous les champs sont bien complétés
if($firstname !== "" && $lastname !== "" && $email !== ""){
// reCaptcha verification
$recaptchaKeyPrivate = WebsiteSetting::getByName('recaptchaKeyPrivate');
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_response = $data['recaptcha'];
$recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptchaKeyPrivate->getData() . '&response=' . $recaptcha_response);
$recaptcha = json_decode($recaptcha);
if ($recaptcha->success)
{
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// condition pour changer le folder d'enregistrement de concours dans les assets
$folderPath = Folder::getByPath("/Inscription");
if(!$folderPath){
$folderPath = new Folder();
$folderPath->setKey("Inscription");
$folderPath->setParentId(1);
$folderPath->save();
}
if($this->document->getProperty('objectFormFolder')) {
$folderPath = Folder::getByPath($this->document->getProperty('objectFormFolder'));
}
$contact = new DataObject\Inscription();
$contact->setLastname($lastname);
$contact->setFirstname($firstname);
$contact->setEmail($email);
$contact->setPhone($phone);
$contact->setBirthday($birthday);
$contact->setSang($sang);
$contact->setPlasma($plasma);
$contact->setGdpr($gdpr);
$contact->setCentre($data['centre']);
/*$contact->setLang($request->getLocale());*/
$contact->setKey($email.'_'.uniqid());
$contact->setParent($folderPath);
$contact->setPublished(true);
$contact->save();
//email au centre
// JDS On envoie à l'adresse définie dans les settings et plus vers le centre comme c'était demandé initialement.
$mail = new \Pimcore\Mail();
$mail->setDocument('/emails/inscription');
//$mail->to($data['centre']->getEmail());
$mail->setParams($data);
$mail->send();
//Copie au visiteur
$mail = new \Pimcore\Mail();
$mail->setDocument('/emails/'.$request->getLocale().'/inscription-confirmation');
$mail->to($email);
$mail->setParams($data);
$mail->send();
$formStatus = 'success';
}else{
$formStatus = 'invalid-email';
}
}else{
$formStatus = 'robot';
}
}else{
$formStatus = 'required-empty';
}
}
$viewContactForm = $formContact->createView();
return $this->render('inscription/default.html.twig',[
'centre' => $centre, // Ajout Greg pour reprendre la data depuis dds
'centres' => $centres,
'form' => $viewContactForm,
'formStatus' => $formStatus,
'ddsHoraires' => $ddsHoraires,
'error' => false,
'lang' => $lang
]);
}
/**
* @Template
* @param Request $request
* @param DataObject $object
* @return response
*/
public function fastContactAction(Request $request)
{
//Formulaire d'inscription
$formStatus = false;
$ddsHoraires = false;
$centres = new DataObject\Centres\Listing();
$centres->load();
if(strpos(WebsiteSetting::getByName('horairesCentresApi')->getData(), 'dds') !== false) {
$ddsHoraires = true;
}
// initialize form and handle request data
$formContact = $this->createForm(InscriptionFormType::class, null);
$formContact->handleRequest($request);
// On vérifie si un POST a bien été effectué et donc si le formulaire a été envoyé
if ($formContact->isSubmitted() && $formContact->isValid()) {
$data = $formContact->getData();
$email = $data['email'];
$phone = $data['phone'];
$firstname = $data['firstname'];
$lastname = $data['lastname'];
$birthday = $data['birthday'];
$sang = $data['sang'];
$plasma = $data['plasma'];
$gdpr = $data['gdpr'];
$data['centreId'] = $request->get("inscription_form_centre");
if($ddsHoraires) {
$centre = DataObject\Centres::getByCodeCentre($data['centreId']);
} else {
$centre = DataObject\Centres::getByAkimediaId($data['centreId']);
}
$centre = $centre->load();
$data['centre'] = $centre[0];
if($email != $request->get("inscription_form_confirmation")){
$viewContactForm = $formContact->createView();
return $this->render('inscription/fast-inscription.html.twig',[
'centres' => $centres,
'form' => $viewContactForm,
'formStatus' => $formStatus,
'ddsHoraires' => $ddsHoraires,
'error' => true,
]);
}
// On vérifie que tous les champs sont bien complétés
if($firstname !== "" && $lastname !== "" && $email !== ""){
// reCaptcha verification
$recaptchaKeyPrivate = WebsiteSetting::getByName('recaptchaKeyPrivate');
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_response = $data['recaptcha'];
$recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptchaKeyPrivate->getData() . '&response=' . $recaptcha_response);
$recaptcha = json_decode($recaptcha);
if ($recaptcha->success)
{
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// condition pour changer le folder d'enregistrement de concours dans les assets
$folderPath = Folder::getByPath("/Inscription");
if(!$folderPath){
$folderPath = new Folder();
$folderPath->setKey("Inscription");
$folderPath->setParentId(1);
$folderPath->save();
}
if($this->document->getProperty('objectFormFolder')) {
$folderPath = Folder::getByPath($this->document->getProperty('objectFormFolder'));
}
$contact = new DataObject\Inscription();
$contact->setLastname($lastname);
$contact->setFirstname($firstname);
$contact->setEmail($email);
$contact->setPhone($phone);
$contact->setBirthday($birthday);
$contact->setSang($sang);
$contact->setPlasma($plasma);
$contact->setGdpr($gdpr);
$contact->setCentre($data['centre']);
/*$contact->setLang($request->getLocale());*/
$contact->setKey($email.'_'.uniqid());
$contact->setParent($folderPath);
$contact->setPublished(true);
$contact->save();
//email au centre
// JDS On envoie à l'adresse définie dans les settings et plus vers le centre comme c'était demandé initialement.
$mail = new \Pimcore\Mail();
$mail->setDocument('/emails/inscription');
//$mail->to($data['centre']->getEmail());
$mail->setParams($data);
$mail->send();
//Copie au visiteur
$mail = new \Pimcore\Mail();
$mail->setDocument('/emails/'.$request->getLocale().'/inscription-confirmation');
$mail->to($email);
$mail->setParams($data);
$mail->send();
$formStatus = 'success';
}else{
$formStatus = 'invalid-email';
}
}else{
$formStatus = 'robot';
}
}else{
$formStatus = 'required-empty';
}
}
$viewContactForm = $formContact->createView();
return $this->render('inscription/fast-inscription.html.twig',[
'centres' => $centres,
'form' => $viewContactForm,
'formStatus' => $formStatus,
'ddsHoraires' => $ddsHoraires,
'error' => false
]);
}
/**
* @Template
* @param Request $request
* @route("/{_locale}/api/akimedia/site/{id}", name="apiAkimediaSite",methods={"GET"})
* @return array
*/
public function detailAction(Request $request)
{
$session = $request->getSession();
$token = $session->get('akimedia-token');
if(!$token){
$token = Akimedia::login();
$session->set('akimedia-token', $token);
}
$id = $request->get('id');
$site = Akimedia::getSiteInfos($request, $id);
return new JsonResponse($site);
}
private function build_calendar($month,$year,$CentreId,$trans) {
// Create array containing abbreviations of days of week.
$daysOfWeek = array('L','M','M','J','V','S','D');
// What is the first day of the month in question?
$firstDayOfMonth = mktime(0,0,0,$month,1,$year);
// How many days does this month contain?
$numberDays = date('t',$firstDayOfMonth);
// Retrieve some information about the first day of the
// month in question.
$dateComponents = getdate($firstDayOfMonth);
// What is the name of the month in question?
$monthName = $trans->trans($dateComponents['month']);
// What is the index value (0-6) of the first day of the
// month in question.
$dayOfWeek = $dateComponents['wday'] - 1;
if($dayOfWeek==-1){
$dayOfWeek=6;
}
// Create the table tag opener and day headers
$calendar = "<table class='calendar'>";
$calendar .= "<caption>$monthName $year</caption>";
$calendar .= "<tr>";
// Create the calendar headers
foreach($daysOfWeek as $day) {
$calendar .= "<th class='header'>$day</th>";
}
// Create the rest of the calendar
// Initiate the day counter, starting with the 1st.
$currentDay = 1;
$calendar .= "</tr><tr>";
// The variable $dayOfWeek is used to
// ensure that the calendar
// display consists of exactly 7 columns.
if ($dayOfWeek > 0) {
$calendar .= "<td colspan='$dayOfWeek'> </td>";
}
$month = str_pad($month, 2, "0", STR_PAD_LEFT);
while ($currentDay <= $numberDays) {
// Seventh column (Saturday) reached. Start a new row.
if ($dayOfWeek == 7) {
$dayOfWeek = 0;
$calendar .= "</tr><tr>";
}
$currentDayRel = str_pad($currentDay, 2, "0", STR_PAD_LEFT);
$date = "$year-$month-$currentDayRel";
$calendar .= "<td class='day' data-centre-id='$CentreId' data-date-format='".date("d-m-Y", strtotime($date))."' data-date='$date'>$currentDay</td>";
// Increment counters
$currentDay++;
$dayOfWeek++;
}
// Complete the row of the last week in month, if necessary
if ($dayOfWeek != 7) {
$remainingDays = 7 - $dayOfWeek;
$calendar .= "<td colspan='$remainingDays'> </td>";
}
$calendar .= "</tr>";
$calendar .= "</table>";
return $calendar;
}
}