<?php
namespace Acme\SudcmsBundle\Controller\Front;
use Acme\SudcmsBundle\Entity\ApiSettings;
use Acme\SudcmsBundle\Entity\Cure;
use Acme\SudcmsBundle\Repository\CureRepository;
use Acme\SudcmsBundle\Service\ApiService;
use Acme\SudcmsBundle\Service\Ecommerce\BasketService;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Routing\Annotation\Route;
use Throwable;
class FrontCureController extends AbstractController
{
private $session;
private BasketService $basketService;
private EntityManagerInterface $em;
private ApiService $apiService;
private ?ApiSettings $apiSettings;
public function __construct(BasketService $basketService,
EntityManagerInterface $em,
ApiService $apiService)
{
$this->session = new Session();
$this->basketService = $basketService;
$this->em = $em;
$this->apiService = $apiService;
$this->apiSettings = $this->em->getRepository(ApiSettings::class)->findOneBy([]);
}
/**
* @throws Throwable
*/
#[Route(path: ['/cures'], name: 'front_cures', defaults: ['categorie' => null])]
public function index(CureRepository $cureRepository): Response
{
$this->denyAccessUnlessGranted('IS_AUTHENTICATED');
if (!$this->apiService->testConnexion()) {
$this->addFlash('danger', 'Une erreur est survenue, veuillez réessayer ultérieurement.');
return $this->redirectToRoute('front_home');
}
// Retrait de la récupération des CURES en BDD au profit de l'API (Steeven : 16/11/23)
// $cures = $cureRepository->findBy([], ['title' => 'ASC']);
try {
$curesP = $this->apiService->listerItp();
$curesS = $this->apiService->listerIts();
} catch (\Throwable $e) {
$this->addFlash('danger', 'Une erreur est survenue, veuillez réessayer ultérieurement.');
return $this->redirectToRoute('front_home');
}
$patient = $this->getUser()->getCustomer()[0]->getOdysseeReference();
$dateDebut = $this->apiSettings->isCureQuota() ? null : (new \DateTime())->modify('+1 day')->format('Y-m-d');
$dateFin = null;
$cureP = null;
$cureS = null;
$cureUrl = null;
$cureName = 'Cure';
$datasComplete = 1;
$plageHoraire = null;
$allOdysseeCustomers = $this->apiService->rechercherClient(adrCourriel: $this->getUser()->getEmail());
// Vérifie si il y a des produits dans le panier qui ne sont pas des cures
$basketAsProduct = false;
foreach ($this->session->get('basket') as $items) {
if (!is_string($items['referenceObject'])) {
$basketAsProduct = true;
}
}
$currentSaisonStart = $this->apiSettings->getCurrentYearStartDate();
$currentSaisonEnd = $this->apiSettings->getCurrentYearEndDate();
$nextSaisonStart = $this->apiSettings->getNextYearStartDate();
$nextSaisonEnd = $this->apiSettings->getNextYearEndDate();
$startYear = $currentSaisonStart->format('Y');
$endYear = $nextSaisonEnd->format('Y');
$datesExcluded = [];
// Parcourir toutes les dates de l'année en cours
for ($year = $startYear; $year <= $endYear; $year++) {
for ($month = 1; $month <= 12; $month++) {
$daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
for ($day = 1; $day <= $daysInMonth; $day++) {
// Date du jour testé
$dateActuelle = new DateTime("$year-$month-$day");
// Si la date est en dehors des saisons en cours et à venir
if (($dateActuelle < $currentSaisonStart || $dateActuelle > $currentSaisonEnd) &&
($dateActuelle < $nextSaisonStart || $dateActuelle > $nextSaisonEnd)) {
$datesExcluded[] = $dateActuelle->format('Y-m-d');
}
}
}
}
$plagesHoraires = null;
if (!$this->apiSettings->isCureQuota()) {
try {
$plagesHoraires = $this->apiService->listerPlageHoraire();
} catch (\Throwable $e) {
$this->addFlash('danger', 'Une erreur est survenue, veuillez réessayer ultérieurement.');
return $this->redirectToRoute('front_home');
}
}
return $this->render('front/front_cure/index.html.twig', [
'patient' => $patient,
'cureP' => $cureP,
'cureS' => $cureS,
'cureUrl' => $cureUrl,
'cureName' => $cureName,
'dateDebut' => $dateDebut,
'dateFin' => $dateFin,
// 'cures' => $cures,
'curesP' => $curesP,
'curesS' => $curesS,
'allOdysseeCustomers' => $allOdysseeCustomers,
'datasComplete' => $datasComplete,
'apiSettings' => $this->apiSettings,
'basketAsProduct' => $basketAsProduct,
'datesExcluded' => $datesExcluded,
'startYear' => $startYear,
'endYear' => $endYear,
'plagesHoraires' => $plagesHoraires,
'plageHoraire' => $plageHoraire
]);
}
/**
* @throws Throwable
*/
#[Route(path: '/axSearchMedPresc', name: 'front_cures_axSearchMedPresc', options: ['expose' => true])]
public function axSearchMedPresc(Request $request, ApiService $api): JsonResponse
{
if ($request->isXmlHttpRequest()) {
$curesForThisPatient = $api->rechercherResaCure(idOdysseeClient: (int)$request->get('idCuriste'));
// Récupère les médecins en fonction du nom saisi
$name = $request->get('name');
$resultSearchMedPresc = $api->rechercherMedPr(nom: $name);
if (isset($curesForThisPatient->status)) {
$curesForThisPatient = null;
}
return new JsonResponse(
[
'status' => true,
'resultSearchMedPresc' => $resultSearchMedPresc,
'selectMedPresc' => $curesForThisPatient && count($curesForThisPatient) > 0 ? end($curesForThisPatient)->{'Medecin_Prescripteur'} : null
]
);
}
return new JsonResponse(
[
'status' => false,
'test2' => 'test2'
]
);
}
/**
* @throws Throwable
*/
#[Route(path: '/axAddCureStepOne', name: 'front_cures_axAddCureStepOne', options: ['expose' => true])]
public function axAddCureStepOne(Request $request, ApiService $api): JsonResponse
{
if ($request->isXmlHttpRequest()) {
$cureP = $request->get('cureP');
$cureS = $request->get('cureS');
$dateDebut = $request->get('datesDebut');
$cureUrl = $this->em->getRepository(Cure::class)->findOneBy(['odysseeReference' => $cureP])->getUrl();
$cureName = $this->em->getRepository(Cure::class)->findOneBy(['odysseeReference' => $cureP])->getTitle();
$plageHoraire = $request->get('plageHoraire');
$date1 = \DateTime::createFromFormat('d-m-Y', $dateDebut);
$date2 = \DateTime::createFromFormat('d-m-Y', $dateDebut);
date_add($date2, date_interval_create_from_date_string("6 days"));
$difference = $date1->diff($date2);
$dispos = $api->quotaResaCure(
cureP: $cureP,
cureS: $cureS,
dateDebut: $date1->format('Y-m-d') . "T00:00:00",
dateFin: $date2->format('Y-m-d') . "T00:00:00"
);
$error = false;
$status = true;
if (!is_string($dispos) && isset($dispos->status)) {
switch ($dispos->status) {
case 404:
$dispos = null;
$status = false;
$error = 'Aucunes disponibilités entre le ' . $date1->format('d/m/Y') . ' et le ' . $date2->format('d/m/Y') . '.';
break;
case 500:
case 502:
case 503:
$dispos = null;
$status = false;
$error = 'Une erreur est survenue, veuillez réessayer.';
break;
}
}
$creneau = $request->request->get('creneau');
$render = $this->renderView('front/front_cure/step/stepOne.html.twig', [
'difference' => !$difference ?: $difference->days,
'dispos' => $dispos,
'creneau' => $creneau,
'cureUrl' => $cureUrl,
'cureName' => $cureName,
'plageHoraire' => $plageHoraire
]);
return new JsonResponse(
[
'status' => $status,
'dispo' => $dispos,
'stepOne' => html_entity_decode($render),
'errorApi' => $error
]
);
}
return new JsonResponse(
[
'status' => false
]
);
}
/**
* @throws Throwable
*/
#[Route(path: '/axAddCureStepTwo', name: 'front_cures_axAddCureStepTwo', options: ['expose' => true])]
public function axAddCureStepTwo(Request $request, ApiService $api): JsonResponse
{
if ($request->isXmlHttpRequest()) {
$cureUrl = null;
$cureName = null;
// Si les quotas ne sont pas activés, on récupère les données de la cure car on ne passe pas par le stepOne
if ($this->apiSettings->isCureQuota() == 0) {
$cureP = $request->get('cureP');
$cureS = $request->get('cureS');
$cureUrl = $this->em->getRepository(Cure::class)->findOneBy(['odysseeReference' => $cureP])->getUrl();
$cureName = $this->em->getRepository(Cure::class)->findOneBy(['odysseeReference' => $cureP])->getTitle();
}
$dateSelect = $request->get('dateSelect');
if ($dateSelect) {
$medsTherm = $api->listerMedTh();
$resultSearchMedPresc = null;
$searchMedPresc = null;
$selectMedPresc = null;
$selectMedTherm = $request->request->get('selectMedTherm');
$render = $this->renderView('front/front_cure/step/stepTwo.html.twig', [
'medsTherm' => $medsTherm,
'selectMedTherm' => $selectMedTherm,
'searchMedPresc' => $searchMedPresc,
'selectMedPresc' => $selectMedPresc,
'resultSearchMedPresc' => json_decode($resultSearchMedPresc),
'cureUrl' => $cureUrl,
'cureName' => $cureName
]);
return new JsonResponse(
[
'status' => true,
'medsTherm' => $medsTherm,
'stepTwo' => html_entity_decode($render),
]
);
}
}
return new JsonResponse(
[
'status' => false,
'test2' => 'test2'
]
);
}
#[Route(path: '/axAddCureStepThree', name: 'front_cures_axAddCureStepThree', options: ['expose' => true])]
public function axAddCureStepThree(Request $request, ApiService $api): JsonResponse
{
if ($request->isXmlHttpRequest()) {
$selectMedPresc = $request->get('selectMedPresc');
$render = $this->renderView('front/front_cure/step/stepThree.html.twig', [
'selectMedPresc' => $selectMedPresc,
]);
return new JsonResponse(
[
'status' => true,
'stepThree' => html_entity_decode($render),
]
);
}
return new JsonResponse(
[
'status' => false,
'test2' => 'test2'
]
);
}
/**
* Permet l'ajout d'une cure au panier
*/
#[Route(path: '/addCureToBasket', name: 'front_cures_addCureToBasket')]
public function addCureToBasket(Request $request): RedirectResponse
{
if ($this->basketService->addCure($request->request) == 'ok') {
$this->addFlash('success', 'Votre réservation a été ajouté au panier');
} elseif ($this->basketService->addCure($request->request) == 'nok') {
$this->addFlash('danger',
'Ce curiste a déjà une Cure en cours de validitée ou de réservation sur cette période');
} else {
$this->addFlash('danger', 'Une erreur est survenue, veuillez réessayer ultérieurement.');
}
return $this->redirectToRoute('front_basket_index');
}
}