src/Controller/BookingController.php line 65

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use DateTime;
  4. use App\Entity\Booking;
  5. use App\Service\Mailjet;
  6. use App\Service\SwiklyService;
  7. use App\Form\BookingType;
  8. use App\Service\StaticData;
  9. use App\Service\CheckRecaptcha;
  10. use App\Entity\ProcessLogs;
  11. use App\Form\CheckAvailabilityType;
  12. use App\Repository\BookingRepository;
  13. use Symfony\Component\Form\FormError;
  14. use App\Repository\PageHeaderRepository;
  15. use Doctrine\ORM\EntityManagerInterface;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use Symfony\Component\HttpFoundation\Response;
  18. use App\Repository\BookingConstraintRepository;
  19. use Symfony\Component\Routing\Annotation\Route;
  20. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  21. use App\Repository\BookingConstraintSaisonRepository;
  22. use App\Repository\BookingContractRepository;
  23. use App\Repository\BookingMailRepository;
  24. use DateTimeImmutable;
  25. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  26. use Symfony\Component\HttpFoundation\JsonResponse;
  27. use Symfony\Component\HttpFoundation\Session\Session;
  28. use Spipu\Html2Pdf\Html2Pdf;
  29. use Symfony\Contracts\Translation\TranslatorInterface;
  30. /**
  31.  * Gestion des réservation et des disponibilités
  32.  */
  33. class BookingController extends AbstractController
  34. {
  35.     private $manager;
  36.     private $statics;
  37.     private $pageRepo;
  38.     private $constraint;
  39.     private $translator;
  40.     public function __construct(EntityManagerInterface $managerTranslatorInterface $translatorStaticData $staticsPageHeaderRepository $pageRepoBookingConstraintRepository $bookingConstraintRepo)
  41.     {
  42.         $this->manager $manager;
  43.         $this->statics $statics->getStaticData();
  44.         $this->pageRepo $pageRepo;
  45.         $this->constraint $bookingConstraintRepo->findOneBy([]);
  46.         $this->translator $translator;
  47.     }
  48.     /**
  49.      * Permet de prendre en charge une réservation
  50.      * 
  51.      * @Route("/{_locale}/booking", name="booking_index")
  52.      *
  53.      * @param Request $request
  54.      * @param CheckRecaptcha $recaptcha
  55.      * @param PageHeaderRepository $pageRepo
  56.      * @param BookingConstraintRepository $bookingConstraintRepo
  57.      * @return Response
  58.      */
  59.     public function index(Request $requestCheckRecaptcha $recaptchaBookingConstraintRepository $bookingConstraintRepoBookingContractRepository $bookingContractRepoSession $sessionBookingRepository $bookingRepoBookingMailRepository $bookingMailRepoSwiklyService $swiklyService): Response
  60.     {
  61.         #   Variables de travail
  62.         $page $this->pageRepo->findOneBy(['page' => 'booking']);
  63.         $locale $request->getLocale();
  64.         $constraint $this->constraint;
  65.         $contract $bookingContractRepo->findOneBy([]);
  66.         $endDate $this->getEndDate();
  67.         if (is_string($endDate)) {
  68.             $endDate DateTime::createFromFormat('d/m/Y'$endDate);
  69.         }
  70.         #   Variables du formulaire
  71.         $bookingEntity = new Booking();
  72.         #   Inserssion de données en provenance d'une autre page
  73.         if (array_key_exists('startDate'$_GET)) {
  74.             $startDate DateTime::createFromFormat('d/m/Y'$_GET['startDate']);
  75.             $endDate DateTime::createFromFormat('d/m/Y'$_GET['endDate']);
  76.             $bookingEntity
  77.                 ->setStartDate($startDate)
  78.                 ->setEndDate($endDate)
  79.                 ->setNumber($_GET['number']);
  80.         }
  81.         $bookingForm $this->createForm(BookingType::class, $bookingEntity);
  82.         $bookingForm->handleRequest($request);
  83.         # Soumission du formulaire
  84.         if ($bookingForm->isSubmitted() && $bookingForm->isValid()) {
  85.             define('SITE_KEY''6LecwkQsAAAAAJ2fiCGD_CZeXV-v5UlIpBG57OmE');
  86.             define('SECRETE_KEY''6LecwkQsAAAAAEPV_YSvd_jWoaaKZG4ja_l4PS6c');
  87.             #   Google Recaptcha
  88.             if ($recaptcha->check($_POST['booking-recaptcha_response'], SECRETE_KEY)) {
  89.                 #   Récupération des données
  90.                 $data $bookingForm->getData();
  91.                 #   Formatage des données
  92.                 #   Formatage des dates selectionnées par le client
  93.                 $formatedStartDate str_replace('/''-'date_format($data->getStartDate(), 'd/m/Y'));
  94.                 $formatedEndDate str_replace('/''-'date_format($data->getEndDate(), 'd/m/Y'));
  95.                 // $formatedStartDate = str_replace('/', '-', $data->getStartDate());
  96.                 $startDate = new DateTime($formatedStartDate);
  97.                 $startDate1 = new DateTime($formatedStartDate);
  98.                 $startDate2 = new DateTime($formatedStartDate);
  99.                 // $formatedEndDate = str_replace('/', '-', $data->getEndDate());
  100.                 $endDate = new DateTime($formatedEndDate);
  101.                 $now = new DateTime();
  102.                 $uid "R" date('U');
  103.                 #   On test si on se trouve dans le cas d'une reservation iminente : si aujourd'hui est supérieur la start date moins le delai donnée pour regler le reliquat
  104.                 if (date('U'strtotime($now->format('Y-m-d'))) >= date('U'strtotime('-' . ($constraint->getBalancePaymentDeadline() + 10) . ' day'date('U'strtotime($startDate->format('Y-m-d')))))) {
  105.                     #   On défini qu'il s'agit d'une reservation iminente et on change l'etat des acompte pour ne pas envoi d'alerte d'acompte dans ce cas de figure
  106.                     $isSoonBooking true;
  107.                     $isAdvancePayed true;
  108.                     $advanceAlerte1 true;
  109.                     $advanceAlerte2 true;
  110.                     #   On défini la deadlines de paiement : now + délai de paiement pour réservation iminente (ex : now + 3)
  111.                     $paymentDelay $constraint->getSoonBookingPaymentDelay();
  112.                     $paymentDeadline $now->modify('+' $paymentDelay ' day');
  113.                     $advancePaymentDeadline $paymentDeadline;
  114.                     $balancePaymentDeadline $paymentDeadline;
  115.                     $cautionPaymentDeadline $paymentDeadline;
  116.                     #   On récupère le mail 
  117.                     $recapMail $bookingMailRepo->findOneBy(['title' => 'Récapitulatif : Réservation imminente']);
  118.                 } else {
  119.                     $isSoonBooking false;
  120.                     $isAdvancePayed false;
  121.                     $advanceAlerte1 false;
  122.                     $advanceAlerte2 false;
  123.                     #   On défini les deadlines
  124.                     $advancePaymentDeadline $now->modify('+' $constraint->getAdvancePaymentDeadline() . ' day');
  125.                     $balancePaymentDeadline $startDate1->modify('-' $constraint->getBalancePaymentDeadline() . ' day');
  126.                     $cautionPaymentDeadline $now->modify('+' $constraint->getCautionPaymentDelay() . ' day');
  127.                     #   On récupère le mail 
  128.                     $recapMail $bookingMailRepo->findOneBy(['title' => 'Récapitulatif : Réservation classique']);
  129.                 }
  130.                 $bookingEntity
  131.                     ->setUniqId($uid)
  132.                     ->setStartDate(new DateTime($formatedStartDate))
  133.                     ->setEndDate(new DateTime($formatedEndDate))
  134.                     ->setDeposit($constraint->getDeposit())
  135.                     ->setAdvancePaymentDeadline($advancePaymentDeadline)
  136.                     ->setPaymentMethod($data->getPaymentMethod())
  137.                     ->setBalancePaymentDeadline($balancePaymentDeadline)
  138.                     ->setCautionPaymentDeadline($cautionPaymentDeadline)
  139.                     ->setBookingConstraint($constraint)
  140.                     ->setIsForSoon($isSoonBooking)
  141.                     ->setIsAdvancePayed($isAdvancePayed)
  142.                     ->setIsAdvancePaymentAlert1($advanceAlerte1)
  143.                     ->setIsAdvancePaymentAlert2($advanceAlerte2)
  144.                     ->setTracking(true)
  145.                     ->setlocale($locale)
  146.                     ->setContract('contrat-' $uid '.pdf');
  147.                 #   On ajoute une réduction si il s'agit d'un long séjour
  148.                 if ($constraint->getLongStayDiscount() > && $bookingEntity->getDuration() >= 7) {
  149.                     $bookingEntity->setDiscount($constraint->getLongStayDiscount());
  150.                 }
  151.                 ### Vérification de la validité de informations soumises avec le formulaire
  152.                 #   On test si la date de départ est supérieure à la date d'arrivé
  153.                 if (strtotime($formatedStartDate) > strtotime($formatedEndDate)) {
  154.                     #   On créer l'erreur
  155.                     $bookingForm->get('startDate')->addError(new FormError($this->translator->trans("Vous ne pouvez pas partir avant d'être arrivé")));
  156.                     $bookingForm->get('endDate')->addError(new FormError($this->translator->trans("Vous ne pouvez pas partir avant d'être arrivé")));
  157.                     #   Flash
  158.                     $this->addFlash(
  159.                         'warning',
  160.                         $this->translator->trans("Vous ne pouvez pas partir avant d'être arrivé")
  161.                     );
  162.                     #   Check si les dates choisies sont disponibles
  163.                 } elseif (!$bookingEntity->isBookableDates()) {
  164.                     #   On créer l'erreur
  165.                     $bookingForm->get('startDate')->addError(new FormError($this->translator->trans('Les dates choisies ne sont pas disponibles')));
  166.                     $bookingForm->get('endDate')->addError(new FormError($this->translator->trans('Les dates choisies ne sont pas disponibles')));
  167.                     #   Flash
  168.                     $this->addFlash(
  169.                         'warning',
  170.                         $this->translator->trans("Les dates que vous avez choisi ne sont pas disponibles.")
  171.                     );
  172.                 } elseif (strtotime($formatedStartDate) >= strtotime($endDate->format('Y-m-d'))) {
  173.                     #   On créer l'erreur
  174.                     $bookingForm->get('startDate')->addError(new FormError($this->translator->trans('Les dates choisies ne sont pas disponibles')));
  175.                     $bookingForm->get('endDate')->addError(new FormError($this->translator->trans('Les dates choisies ne sont pas disponibles')));
  176.                     #   Flash
  177.                     $this->addFlash(
  178.                         'warning',
  179.                         $this->translator->trans("Les dates que vous avez choisi ne sont pas disponibles.")
  180.                     );
  181.                 } else {
  182.                     #   Préparation des données à envoyer au différent template
  183.                     $statics $this->statics['data'];
  184.                     #   Enregistrement de la réservation en BDD
  185.                     $this->manager->persist($bookingEntity);
  186.                     #   SWIKLY GENERATION (Moved here to ensure entity is fully hydrated)
  187.                     #   Generate link for ALL bookings so they can pay deposit immediately if they wish.
  188.                     if (!$bookingEntity->getSwiklyUrl()) {
  189.                         error_log("Attempting to create Swikly deposit for booking UID: " $bookingEntity->getUniqId());
  190.                         $successUrl $this->generateUrl('swikly_accept', ['uid' => $bookingEntity->getUniqId()], UrlGeneratorInterface::ABSOLUTE_URL);
  191.                         $errorUrl $this->generateUrl('swikly_decline', ['uid' => $bookingEntity->getUniqId()], UrlGeneratorInterface::ABSOLUTE_URL);
  192.                         $res $swiklyService->createDeposit($bookingEntity$successUrl$errorUrl);
  193.                         error_log("Swikly Response: " print_r($restrue));
  194.                         if ($res && isset($res['accept_url'])) {
  195.                             $bookingEntity->setSwiklyUrl($res['accept_url']);
  196.                             $bookingEntity->setSwiklyRequestId($res['swik_id'] ?? null);
  197.                             // No flush needed here as flush comes right after
  198.                         } elseif (isset($res['error'])) {
  199.                             $this->addFlash('danger''Erreur création caution Swikly : ' $res['error']);
  200.                         } else {
  201.                             $this->addFlash('danger''Erreur création caution Swikly : Réponse invalide.');
  202.                         }
  203.                     }
  204.                     $this->manager->flush();
  205.                     # Gestion du contrat de location
  206.                     $templateContract_bailleur $this->replaceVar($contract->translate($locale)->getContent(), $bookingEntity$constraint"bailleur");
  207.                     $templateContract_locataire $this->replaceVar($contract->translate($locale)->getContent(), $bookingEntity$constraint"locataire");
  208.                     $contractMaker_bailleur $this->makePdf($uid$templateContract_bailleur$request'bailleur');
  209.                     $contractMaker_locataire $this->makePdf($uid$templateContract_locataire$request'locataire');
  210.                     $contract_bailleur base64_encode(file_get_contents('/home/maxappu/www/gite-colombine.fr/v3/public/file/contrats/contrat-' $uid '-bailleur.pdf'));
  211.                     $contract_locataire base64_encode(file_get_contents('/home/maxappu/www/gite-colombine.fr/v3/public/file/contrats/contrat-' $uid '-locataire.pdf'));
  212.                     ##   Envoi d'email MailJet 
  213.                     #   Client
  214.                     $mailjet = new Mailjet();
  215.                     $mail_content $this->replaceVar($recapMail->translate($locale)->getContent(), $bookingEntity$constraint);
  216.                     $mailjet->send("caurettemarc@gmail.com""gite-colombine.fr"$data->getEmail(), $data->getFirstName() . " " $data->getLastName(), $recapMail->translate($locale)->getSubject(), $mail_content$contract_locataire$bookingEntity7650701);
  217.                     #   Propriétaire
  218.                     $mailjet = new Mailjet();
  219.                     $mail_content $this->renderView('components/mail/_booking.html.twig'compact('data''statics''bookingEntity''constraint'));
  220.                     $mailjet->send("caurettemarc@gmail.com""gite-colombine.fr""maximeavril.dev@gmail.com"$data->getFirstName() . " " $data->getLastName(), "Réservation"$mail_content$contract_bailleur$bookingEntity7650701);
  221.                     #   Flash
  222.                     $this->addFlash(
  223.                         'success',
  224.                         $this->translator->trans("Réservation enregistrée")
  225.                     );
  226.                     #   Redirection vers une page de validation reprennant les details de la réservation
  227.                     return $this->redirectToRoute('booking_validation', [
  228.                         'uid' => $bookingEntity->getUniqId()
  229.                     ]);
  230.                 }
  231.             } else {
  232.                 #   Flash
  233.                 $this->addFlash(
  234.                     'warning',
  235.                     $this->translator->trans("Erreur liée au Recaptcha...")
  236.                 );
  237.                 #   Redirection sur la page de validation de réservation
  238.                 return $this->render('booking/index.html.twig', [
  239.                     'statics' => $this->statics['data'],
  240.                     'page' => $page,
  241.                     'constraint' => $constraint,
  242.                     'endDate' => $endDate,
  243.                     'bookingForm' => $bookingForm->createView()
  244.                 ]);
  245.             }
  246.         }
  247.         #   Redirection sur la page de validation de réservation
  248.         return $this->render('booking/index.html.twig', [
  249.             'statics' => $this->statics['data'],
  250.             'page' => $page,
  251.             'constraint' => $constraint,
  252.             'endDate' => $endDate,
  253.             'bookingForm' => $bookingForm->createView()
  254.         ]);
  255.     }
  256.     /**
  257.      * Permet de check la disponibilité 
  258.      * 
  259.      * @Route("/{_locale}/check-availability", name="booking_check_avail")
  260.      *
  261.      * @param BookingConstraintRepository $bookingConstraintRepo
  262.      * @return void
  263.      */
  264.     public function checkAvailability(BookingConstraintRepository $bookingConstraintRepoRequest $request)
  265.     {
  266.         #   Variables de travail
  267.         $constraint $bookingConstraintRepo->findOneBy([]);
  268.         #   Variables du formulaire
  269.         $bookingEntity = new Booking();
  270.         $bookingForm $this->createForm(CheckAvailabilityType::class, $bookingEntity);
  271.         $bookingForm->handleRequest($request);
  272.         #   Soumission du formulaire
  273.         if ($bookingForm->isSubmitted()) {
  274.             #   Récupération des données
  275.             $data $bookingForm->getData();
  276.             #   Formatage des dates selectionnées par le client
  277.             $formatedStartDate str_replace('/''-'date_format($data->getStartDate(), 'd/m/Y'));
  278.             $formatedEndDate str_replace('/''-'date_format($data->getEndDate(), 'd/m/Y'));
  279.             #   Insertion des donnée formatées dans l'entity
  280.             $bookingEntity
  281.                 ->setStartDate(new DateTime($formatedStartDate))
  282.                 ->setEndDate(new DateTime($formatedEndDate))
  283.                 ->setDeposit($constraint->getDeposit() / 100)
  284.                 ->setBookingConstraint($constraint);
  285.             #   On test si la date de départ est supérieure à la date d'arrivé
  286.             if ($data->getStartDate() > $data->getEndDate()) {
  287.                 #   Ajax Flash
  288.                 $flashbag = [
  289.                     'label' => "warning",
  290.                     'title' => "Oups...",
  291.                     'message' => $this->translator->trans("Vous ne pouvez pas partir avant d'être arrivé") . ' <i class="fas fa-smile-wink"></i> <br> <strong>' $data->getStartDate()->format("d/m/Y") . '</strong> < <strong>' $data->getEndDate()->format("d/m/Y") . '</strong>',
  292.                     'btnText' => $this->translator->trans("Je recommence"),
  293.                     'btnPath' => "#"
  294.                 ];
  295.                 return $this->render('components/flash/ajax_check_avail.html.twig', [
  296.                     'flashbag' => $flashbag,
  297.                 ]);
  298.             }
  299.             #   On test si le client essaye de reservé pour une date anterieur ou trop proche d'aujourd'hui
  300.             $minDate = (new \DateTime())->modify('+1 day')->setTime(000);
  301.             if ($data->getStartDate() < $minDate || $data->getEndDate() < $minDate) {
  302.                 #   Ajax Flash
  303.                 $flashbag = [
  304.                     'label' => "warning",
  305.                     'title' => $this->translator->trans("Bien essayé..."),
  306.                     'message' => $data->getStartDate()->format('d/m/Y') . " " $data->getEndDate()->format('d/m/Y'),
  307.                     'btnText' => $this->translator->trans("Je recommence"),
  308.                     'btnPath' => "#"
  309.                 ];
  310.                 return $this->render('components/flash/ajax_check_avail.html.twig', [
  311.                     'flashbag' => $flashbag,
  312.                 ]);
  313.             }
  314.             #   Check si les dates choisies sont disponibles
  315.             if (!$bookingEntity->isBookableDates()) {
  316.                 #   Ajax Flash
  317.                 $flashbag = [
  318.                     'label' => "warning",
  319.                     'title' => $this->translator->trans("Désolé..."),
  320.                     'message' => $this->translator->trans("La période du") . " <strong>" $data->getStartDate()->format('d/m/Y') . "</strong> " $this->translator->trans("au") . " <strong>" $data->getEndDate()->format('d/m/Y') . "</strong> " $this->translator->trans("pour") . " <strong>" $data->getNumber() . "</strong> " $this->translator->trans("personnes n'est pas disponible à la réservation") . ".",
  321.                     'btnText' => $this->translator->trans("Je recommence"),
  322.                     'btnPath' => "#"
  323.                 ];
  324.                 return $this->render('components/flash/ajax_check_avail.html.twig', [
  325.                     'flashbag' => $flashbag,
  326.                 ]);
  327.             }
  328.             #   Check si le nombre de personnes ne dépasse pas la limite 
  329.             if ($data->getNumber() > $constraint->getMaxNumber()) {
  330.                 #   Ajax flash 
  331.                 $flashbag = [
  332.                     'label' => "warning",
  333.                     'title' => "Oups...",
  334.                     'message' => $this->translator->trans("Vous avez dépassé le nombre maximum de personnes") . " <br> " $this->translator->trans("Le nombre maximum est de") . " " $constraint->getMaxNumber() . " " $this->translator->trans("personnes") . "",
  335.                     'btnText' => $this->translator->trans("Je recommence"),
  336.                     'btnPath' => "#"
  337.                 ];
  338.                 return $this->render('components/flash/ajax_check_avail.html.twig', [
  339.                     'flashbag' => $flashbag,
  340.                 ]);
  341.             }
  342.             #   Sinon, validation du checking
  343.             #   Ajax flash 
  344.             $flashbag = [
  345.                 'label' => "success",
  346.                 'title' => $this->translator->trans("C'est bon"),
  347.                 'message' => $this->translator->trans("La période du") . " <strong>" $data->getStartDate()->format('d/m/Y') . "</strong> " $this->translator->trans("au") . " <strong>" $data->getEndDate()->format('d/m/Y') . "</strong> " $this->translator->trans("pour") . " <strong>" $data->getNumber() . "</strong> " $this->translator->trans("personnes est disponible à la réservation") . ".",
  348.                 'btnText' => $this->translator->trans("Je réserve"),
  349.                 'btnPath' => $this->generateUrl('booking_index', [
  350.                     'startDate' => $data->getStartDate()->format('d/m/Y'),
  351.                     'endDate' => $data->getEndDate()->format('d/m/Y'),
  352.                     'number' => $data->getNumber()
  353.                 ])
  354.             ];
  355.             return $this->render('components/flash/ajax_check_avail.html.twig', [
  356.                 'flashbag' => $flashbag,
  357.             ]);
  358.         } else {
  359.             return $this->json(false);
  360.         }
  361.     }
  362.     /**
  363.      * Affiche la page de validation d'une réservation
  364.      *
  365.      * @Route("/{_locale}/booking/{uid}", name="booking_validation")
  366.      * 
  367.      * @param Booking $booking
  368.      */
  369.     public function validation($uidRequest $requestBookingRepository $bookingRepoBookingConstraintRepository $bookingConstraintRepoBookingMailRepository $bookingMailRepo)
  370.     {
  371.         $page $this->pageRepo->findOneBy(['page' => 'validation']);
  372.         $booking $bookingRepo->findOneBy(["uniqId" => $uid]);
  373.         $constraint $bookingConstraintRepo->findOneBy([]);
  374.         $locale $request->getLocale();
  375.         if ($booking->getIsForSoon() == true) {
  376.             #   On récupère le contenu de la page de validation 
  377.             $validationContent $bookingMailRepo->findOneBy(['title' => 'Validation : Réservation imminente']);
  378.         } else {
  379.             #   On récupère le contenu de la page de validation 
  380.             $validationContent $bookingMailRepo->findOneBy(['title' => 'Validation : Réservation classique']);
  381.         }
  382.         return $this->render('booking/validation.html.twig', [
  383.             'statics' => $this->statics['data'],
  384.             'page' => $page,
  385.             'booking' => $booking,
  386.             'constraint' => $constraint,
  387.             'content' => $this->replaceVar($validationContent->translate($locale)->getContent(), $booking$constraint)
  388.         ]);
  389.     }
  390.     /**
  391.      * Permet de connaitre la saison de la réservation
  392.      *
  393.      * @Route("/booking/get-saison", name="booking_get_saison")
  394.      * 
  395.      * @return JsonResponce
  396.      */
  397.     public function checkSaison(BookingConstraintSaisonRepository $bookingConstraintSaisonRepo)
  398.     {
  399.         if (array_key_exists('start'$_GET)) {
  400.             $formatedStartDate date('Y-m-d'strtotime($_GET['start']));
  401.             $formatedEndDate date('Y-m-d'strtotime($_GET['end']));
  402.             $start date('U'strtotime($formatedStartDate));
  403.             $end date('U'strtotime($formatedEndDate));
  404.             $bookingDays = [
  405.                 'start' => $start,
  406.                 'end' => $end
  407.             ];
  408.             $saisonConstraints $bookingConstraintSaisonRepo->findAll();
  409.             $saisons $this->getSaison($bookingDays);
  410.             $temp = [];
  411.             $temp['count'] = 0;
  412.             $temp['price'] = 0;
  413.             foreach ($saisonConstraints as $saisonConstraint) {
  414.                 foreach ($saisons as $key => $saison) {
  415.                     #   On récupère les saisons dans les quel on se trouve 
  416.                     if ($saisonConstraint->translate('fr')->getTitle() == $saison['saison']) {
  417.                         #   On incrémente le prix et le nombre de jour à chaque boucle
  418.                         $temp['count'] += 1;
  419.                         $temp['price'] += $saisonConstraint->getPrice();
  420.                     }
  421.                 }
  422.             }
  423.             $mediumPrice ceil($temp['price'] / $temp['count']);
  424.             return $this->json([
  425.                 'price' => $mediumPrice
  426.             ]);
  427.         }
  428.     }
  429.     public function getSaison($bookingDays)
  430.     {
  431.         $saisons $this->constraint->getSaisons();
  432.         $periods_days = [];
  433.         foreach ($saisons as $key => $saison) {
  434.             foreach ($saison->getPeriods() as $key => $period) {
  435.                 $resultat range(
  436.                     $period->getStartDate()->getTimestamp(),
  437.                     $period->getEndDate()->getTimestamp(),
  438.                     24 60 60
  439.                 );
  440.                 $days array_map(function ($dayTimestamp) {
  441.                     return new \DateTime(date('Y-m-d'$dayTimestamp));
  442.                 }, $resultat);
  443.                 $periods_days[$saison->translate('fr')->getTitle()][$key] = $days;
  444.             }
  445.         }
  446.         $resultat range(
  447.             $bookingDays['start'],
  448.             $bookingDays['end'],
  449.             24 60 60
  450.         );
  451.         $bookingDays array_map(function ($dayTimestamp) {
  452.             return new \DateTime(date('Y-m-d'$dayTimestamp));
  453.         }, $resultat);
  454.         $formatDays = function ($day) {
  455.             return $day->format('Y-m-d');
  456.         };
  457.         //Tableau des strings de mes journées à reserver
  458.         $daysToReserve array_map($formatDays$bookingDays);
  459.         //Tableau des jours diférentes saisons
  460.         foreach ($periods_days as $saison_key => $array) {
  461.             foreach ($array as $key => $item) {
  462.                 $saisonsDays[$saison_key][$key] = array_map($formatDays$item);
  463.             }
  464.         }
  465.         //Pour chaques journées à reserver je regarde si elle se trouve dans les journées d'une saison
  466.         $temp = [];
  467.         foreach ($daysToReserve as $day) {
  468.             foreach ($saisonsDays as $saison_key => $saison) {
  469.                 foreach ($saison as $key => $item) {
  470.                     if (array_search($day$item) !== false) {
  471.                         $temp[] = [
  472.                             'day' => $day,
  473.                             'saison' => $saison_key,
  474.                         ];
  475.                     }
  476.                 }
  477.             }
  478.         }
  479.         return $temp;
  480.     }
  481.     /**
  482.      * CRONJOB
  483.      * Permet de vérifier l'état des paiements pour chaque réservation
  484.      * 
  485.      * @Route("/booking/check-payment", name="booking_check_payment") 
  486.      */
  487.     public function checkPayments(BookingRepository $bookingRepoBookingMailRepository $bookingMailRepoSwiklyService $swiklyService)
  488.     {
  489.         $now date('Y-m-d');
  490.         $bookings $bookingRepo->findFutures($now);
  491.         $statics $this->statics['data'];
  492.         $logs = [];
  493.         $logs['advance']['title'] = 'CRON du paiement de l\'acompte';
  494.         $logs['balance']['title'] = 'CRON du paiement du reliquat';
  495.         $logs['caution']['title'] = 'CRON du paiement du dépôt';
  496.         foreach ($bookings as $key => $booking) {
  497.             $advancePaymentDeadline $booking->getAdvancePaymentDeadline();
  498.             $balancePaymentDeadline $booking->getBalancePaymentDeadline();
  499.             $cautionPaymentDeadline $booking->getCautionPaymentDeadline();
  500.             $isForSoon $booking->getIsForSoon();
  501.             $bookingCreatedAt $booking->getCreatedAt();
  502.             $constraint $booking->getBookingConstraint();
  503.             ###   On check si le tracking est activé sur la réservation
  504.             if ($booking->getTracking() == true && date('U'strtotime($now)) < date('U'strtotime($booking->getStartDate()->format('Y-m-d')))) {
  505.                 ### Alerte 1 acompte
  506.                 #   On check si il s'agit d'une reservation imminente et si les alerte n'ont pas déja été envoyées
  507.                 if ($booking->getIsAdvancePaymentAlert1() != true && $booking->getIsAdvancePayed() != true && $isForSoon != true) {
  508.                     #   Pour chaque reservation on vérifie si la advancePaymentDeadline/3 est dépassée pour envoyer une 1ere alerte au client
  509.                     if ((date('U'strtotime($now))) > (date('U'strtotime($advancePaymentDeadline->format('Y-m-d'))) - ((ceil($constraint->getAdvancePaymentDeadline() / 3) * 86400)))) {
  510.                         #   Logs de process
  511.                         $logs['advance'][1][$key]['process'] = 'Vérification N°1 du paiement de l\'accompte';
  512.                         $logs['advance'][1][$key]['reference'] = $booking->getUniqId();
  513.                         #   Récupéreration du contenu du mail
  514.                         $templateMail_locataire $bookingMailRepo->findOneBy(['title' => 'Alerte acompte N°1']);
  515.                         ##  Envoi d'email d'alerte MailJet 
  516.                         #   Client
  517.                         $mailjet = new Mailjet();
  518.                         $mail_content_c $this->replaceVar($templateMail_locataire->translate($booking->getLocale())->getContent(), $booking$constraint);
  519.                         $mailjet->send("caurettemarc@gmail.com""gite-colombine.fr"$booking->getEmail(), $booking->getFirstName() . " " $booking->getLastName(), $this->translator->trans("Votre réservation") . " N°" $booking->getUniqId(), $mail_content_cfalsefalse7650701);
  520.                         #   Propriétaire
  521.                         $mailjet = new Mailjet();
  522.                         $mail_content_p $this->renderView('components/mail/_booking_advance_alert_1_p.html.twig'compact('booking''statics''constraint'));
  523.                         $mailjet->send("caurettemarc@gmail.com""gite-colombine.fr""maximeavril.dev@gmail.com"$booking->getFirstName() . " " $booking->getLastName(), "Alerte réservation N°" $booking->getUniqId(), $mail_content_pfalsefalse7650701);
  524.                         $logs['advance'][1][$key]['content'] = $mail_content_c;
  525.                         $booking->setIsAdvancePaymentAlert1(true);
  526.                         $this->manager->persist($booking);
  527.                         $ProcessLogs = new ProcessLogs();
  528.                         $ProcessLogs
  529.                             ->setTitle($logs['advance']['title'])
  530.                             ->setProcess($logs['advance'][1][$key]['process'])
  531.                             ->setReference($logs['advance'][1][$key]['reference'])
  532.                             ->setContent($logs['advance'][1][$key]['content'])
  533.                             ->setCreatedAt(new DateTimeImmutable());
  534.                         $this->manager->persist($ProcessLogs);
  535.                     }
  536.                 }
  537.                 ###   Alerte 2 acompte
  538.                 if ($booking->getIsAdvancePaymentAlert2() != true && $booking->getIsAdvancePaymentAlert1() == true && $booking->getIsAdvancePayed() != true && $isForSoon != true) {
  539.                     #   Pour chaque reservation on vérifie si la advancePaymentDeadline est dépasser pour envoyer une 1ere alerte au client
  540.                     if ((date('U'strtotime($now))) > (date('U'strtotime($advancePaymentDeadline->format('Y-m-d'))) + 86400)) {
  541.                         #   Logs de process
  542.                         $logs['advance'][2][$key]['process'] = 'Vérification N°2 du paiement de l\'accompte';
  543.                         $logs['advance'][2][$key]['reference'] = $booking->getUniqId();
  544.                         #   Récupéreration du contenu du mail
  545.                         $templateMail_locataire $bookingMailRepo->findOneBy(['title' => 'Alerte acompte N°2']);
  546.                         ##  Envoi d'email d'alerte MailJet 
  547.                         #   Client
  548.                         $mailjet = new Mailjet();
  549.                         $mail_content_c $this->replaceVar($templateMail_locataire->translate($booking->getLocale())->getContent(), $booking$constraint);
  550.                         $mailjet->send("caurettemarc@gmail.com""gite-colombine.fr"$booking->getEmail(), $booking->getFirstName() . " " $booking->getLastName(), $this->translator->trans("Votre réservation") . " N°" $booking->getUniqId(), $mail_content_cfalsefalse7650701);
  551.                         #   Propriétaire
  552.                         $mailjet = new Mailjet();
  553.                         $mail_content_p $this->renderView('components/mail/_booking_advance_alert_2_p.html.twig'compact('booking''statics''constraint'));
  554.                         $mailjet->send("caurettemarc@gmail.com""gite-colombine.fr""maximeavril.dev@gmail.com"$booking->getFirstName() . " " $booking->getLastName(), "Alerte réservation N°" $booking->getUniqId(), $mail_content_pfalsefalse7650701);
  555.                         $logs['advance'][2][$key]['content'] = $mail_content_c;
  556.                         $booking->setIsAdvancePaymentAlert2(true);
  557.                         $this->manager->persist($booking);
  558.                         $ProcessLogs = new ProcessLogs();
  559.                         $ProcessLogs
  560.                             ->setTitle($logs['advance']['title'])
  561.                             ->setProcess($logs['advance'][2][$key]['process'])
  562.                             ->setReference($logs['advance'][2][$key]['reference'])
  563.                             ->setContent($logs['advance'][2][$key]['content'])
  564.                             ->setCreatedAt(new DateTimeImmutable());
  565.                         $this->manager->persist($ProcessLogs);
  566.                     }
  567.                 }
  568.                 ###   Alerte 1 caution
  569.                 if ($booking->getIsCautionPaymentAlert1() != true && $booking->getIsCautionPayed() != true && $isForSoon == false) {
  570.                     #   Pour chaque reservation on vérifie si la cautionPaymentDeadline est dépassée pour envoyer une 1ere alerte au client
  571.                     if ((date('U'strtotime($now))) > (date('U'strtotime($cautionPaymentDeadline->format('Y-m-d'))) - ((ceil($constraint->getCautionPaymentDelay() / 3) * 86400)))) {
  572.                         #   Logs de process
  573.                         $logs['caution'][1][$key]['reference'] = $booking->getUniqId();
  574.                         #   Récupéreration du contenu du mail
  575.                         $templateMail_locataire $bookingMailRepo->findOneBy(['title' => 'Alerte caution N°1']);
  576.                         #   SWIKLY GENERATION
  577.                         if (!$booking->getSwiklyUrl()) {
  578.                             $successUrl $this->generateUrl('swikly_accept', ['uid' => $booking->getUniqId()], UrlGeneratorInterface::ABSOLUTE_URL);
  579.                             $errorUrl $this->generateUrl('swikly_decline', ['uid' => $booking->getUniqId()], UrlGeneratorInterface::ABSOLUTE_URL);
  580.                             $res $swiklyService->createDeposit($booking$successUrl$errorUrl);
  581.                             if ($res && isset($res['accept_url'])) {
  582.                                 $booking->setSwiklyUrl($res['accept_url']);
  583.                                 $booking->setSwiklyRequestId($res['swik_id'] ?? null);
  584.                                 $this->manager->persist($booking);
  585.                                 $this->manager->flush(); // Flush explicitly to save the link
  586.                             }
  587.                         }
  588.                         ##  Envoi d'email d'alerte MailJet 
  589.                         #   Client
  590.                         $mailjet = new Mailjet();
  591.                         $mail_content_c $this->replaceVar($templateMail_locataire->translate($booking->getLocale())->getContent(), $booking$constraint);
  592.                         $mailjet->send("caurettemarc@gmail.com""gite-colombine.fr"$booking->getEmail(), $booking->getFirstName() . " " $booking->getLastName(), $this->translator->trans("Votre réservation") . " N°" $booking->getUniqId(), $mail_content_cfalsefalse7650701);
  593.                         #   Propriétaire
  594.                         $mailjet = new Mailjet();
  595.                         $mail_content_p $this->renderView('components/mail/_booking_caution_alert_1_p.html.twig'compact('booking''statics''constraint'));
  596.                         $mailjet->send("caurettemarc@gmail.com""gite-colombine.fr""maximeavril.dev@gmail.com"$booking->getFirstName() . " " $booking->getLastName(), "Alerte réservation N°" $booking->getUniqId(), $mail_content_pfalsefalse7650701);
  597.                         #   Logs de process
  598.                         $logs['caution'][1][$key]['process'] = 'Vérification N°1 du paiement de la caution';
  599.                         $logs['caution'][1][$key]['content'] = $mail_content_c;
  600.                         #   Changement d'état 
  601.                         $booking->setIsCautionPaymentAlert1(true);
  602.                         $this->manager->persist($booking);
  603.                         #   Enregistrement des logs de process
  604.                         $ProcessLogs = new ProcessLogs();
  605.                         $ProcessLogs
  606.                             ->setTitle($logs['caution']['title'])
  607.                             ->setProcess($logs['caution'][1][$key]['process'])
  608.                             ->setReference($logs['caution'][1][$key]['reference'])
  609.                             ->setContent($logs['caution'][1][$key]['content'])
  610.                             ->setCreatedAt(new DateTimeImmutable());
  611.                         $this->manager->persist($ProcessLogs);
  612.                     }
  613.                 }
  614.                 ###   Alerte 2 caution
  615.                 if ($booking->getIsCautionPaymentAlert2() != true && $booking->getIsCautionPayed() != true && $isForSoon == false) {
  616.                     #   Pour chaque reservation on vérifie si la cautionPaymentDeadline est dépassée pour envoyer une 2eme alerte au client
  617.                     if ((date('U'strtotime($now))) > (date('U'strtotime($cautionPaymentDeadline->format('Y-m-d'))))) {
  618.                         #   Logs de process
  619.                         $logs['caution'][2][$key]['reference'] = $booking->getUniqId();
  620.                         #   Récupéreration du contenu du mail
  621.                         $templateMail_locataire $bookingMailRepo->findOneBy(['title' => 'Alerte caution N°2']);
  622.                         #   SWIKLY GENERATION (Reuse or create if missing)
  623.                         if (!$booking->getSwiklyUrl()) {
  624.                             $successUrl $this->generateUrl('swikly_accept', ['uid' => $booking->getUniqId()], UrlGeneratorInterface::ABSOLUTE_URL);
  625.                             $errorUrl $this->generateUrl('swikly_decline', ['uid' => $booking->getUniqId()], UrlGeneratorInterface::ABSOLUTE_URL);
  626.                             $res $swiklyService->createDeposit($booking$successUrl$errorUrl);
  627.                             if ($res && isset($res['accept_url'])) {
  628.                                 $booking->setSwiklyUrl($res['accept_url']);
  629.                                 $booking->setSwiklyRequestId($res['swik_id'] ?? null);
  630.                                 $this->manager->persist($booking);
  631.                                 $this->manager->flush();
  632.                             }
  633.                         }
  634.                         ##  Envoi d'email d'alerte MailJet 
  635.                         #   Client
  636.                         $mailjet = new Mailjet();
  637.                         $mail_content_c $this->replaceVar($templateMail_locataire->translate($booking->getLocale())->getContent(), $booking$constraint);
  638.                         $mailjet->send("caurettemarc@gmail.com""gite-colombine.fr"$booking->getEmail(), $booking->getFirstName() . " " $booking->getLastName(), $this->translator->trans("Votre réservation") . " N°" $booking->getUniqId(), $mail_content_cfalsefalse7650701);
  639.                         #   Propriétaire
  640.                         $mailjet = new Mailjet();
  641.                         $mail_content_p $this->renderView('components/mail/_booking_caution_alert_2_p.html.twig'compact('booking''statics''constraint'));
  642.                         $mailjet->send("caurettemarc@gmail.com""gite-colombine.fr""maximeavril.dev@gmail.com"$booking->getFirstName() . " " $booking->getLastName(), "Alerte réservation N°" $booking->getUniqId(), $mail_content_pfalsefalse7650701);
  643.                         #   Logs de process
  644.                         $logs['caution'][2][$key]['process'] = 'Vérification N°2 du paiement de la caution';
  645.                         $logs['caution'][2][$key]['content'] = $mail_content_c;
  646.                         #   Changement d'état 
  647.                         $booking->setIsCautionPaymentAlert1(true);
  648.                         $this->manager->persist($booking);
  649.                         #   Enregistrement des logs de process
  650.                         $ProcessLogs = new ProcessLogs();
  651.                         $ProcessLogs
  652.                             ->setTitle($logs['caution']['title'])
  653.                             ->setProcess($logs['caution'][2][$key]['process'])
  654.                             ->setReference($logs['caution'][2][$key]['reference'])
  655.                             ->setContent($logs['caution'][2][$key]['content'])
  656.                             ->setCreatedAt(new DateTimeImmutable());
  657.                         $this->manager->persist($ProcessLogs);
  658.                     }
  659.                 }
  660.                 ###   Alerte 1 reliquat
  661.                 if ($booking->getIsBalancePaymentAlert1() != true && $booking->getIsBalancePayed() != true) {
  662.                     #   Si il s'agit d'une reservation iminente
  663.                     if ($isForSoon == true) {
  664.                         #   On vérifie si nous sommes à la deadline de paiement du montant total
  665.                         if ((date('U'strtotime($now))) > (date('U'strtotime($balancePaymentDeadline->format('Y-m-d'))))) {
  666.                             #   Logs de process
  667.                             $logs['balance'][1][$key]['reference'] = $booking->getUniqId();
  668.                             #   Récupéreration du contenu du mail
  669.                             $templateMail_locataire $bookingMailRepo->findOneBy(['title' => 'Alerte solde N°1 : Réservation imminente']);
  670.                             ##  Envoi d'email d'alerte MailJet 
  671.                             #   Client
  672.                             $mailjet = new Mailjet();
  673.                             $mail_content_c $this->replaceVar($templateMail_locataire->translate($booking->getLocale())->getContent(), $booking$constraint);
  674.                             $mailjet->send("caurettemarc@gmail.com""gite-colombine.fr"$booking->getEmail(), $booking->getFirstName() . " " $booking->getLastName(), $this->translator->trans("Votre réservation") . " N°" $booking->getUniqId(), $mail_content_cfalsefalse7650701);
  675.                             #   Propriétaire
  676.                             $mailjet = new Mailjet();
  677.                             $mail_content_p $this->renderView('components/mail/_booking_balance_alert_1_p.html.twig'compact('booking''statics''constraint'));
  678.                             $mailjet->send("caurettemarc@gmail.com""gite-colombine.fr""maximeavril.dev@gmail.com"$booking->getFirstName() . " " $booking->getLastName(), "Alerte réservation N°" $booking->getUniqId(), $mail_content_pfalsefalse7650701);
  679.                             #   Logs de process
  680.                             $logs['balance'][1][$key]['process'] = 'Vérification N°1 du paiement total';
  681.                             $logs['balance'][1][$key]['content'] = $mail_content_c;
  682.                             #   Changement d'état 
  683.                             $booking->setIsBalancePaymentAlert1(true);
  684.                             $this->manager->persist($booking);
  685.                             #   Enregistrement des logs de process
  686.                             $ProcessLogs = new ProcessLogs();
  687.                             $ProcessLogs
  688.                                 ->setTitle($logs['balance']['title'])
  689.                                 ->setProcess($logs['balance'][1][$key]['process'])
  690.                                 ->setReference($logs['balance'][1][$key]['reference'])
  691.                                 ->setContent($logs['balance'][1][$key]['content'])
  692.                                 ->setCreatedAt(new DateTimeImmutable());
  693.                             $this->manager->persist($ProcessLogs);
  694.                         }
  695.                     } else {
  696.                         #   Pour chaque reservation on vérifie si la balancePaymentDeadline est dépasser pour envoyer une 1ere alerte au client
  697.                         if ((date('U'strtotime($now))) > (date('U'strtotime($balancePaymentDeadline->format('Y-m-d'))))) {
  698.                             #   Logs de process
  699.                             $logs['balance'][1][$key]['reference'] = $booking->getUniqId();
  700.                             #   Récupéreration du contenu du mail
  701.                             $templateMail_locataire $bookingMailRepo->findOneBy(['title' => 'Alerte solde N°1 : Réservation classique']);
  702.                             ##  Envoi d'email d'alerte MailJet 
  703.                             #   Client
  704.                             $mailjet = new Mailjet();
  705.                             $mail_content_c $this->replaceVar($templateMail_locataire->translate($booking->getLocale())->getContent(), $booking$constraint);
  706.                             $mailjet->send("caurettemarc@gmail.com""gite-colombine.fr"$booking->getEmail(), $booking->getFirstName() . " " $booking->getLastName(), $this->translator->trans("Votre réservation") . " N°" $booking->getUniqId(), $mail_content_cfalsefalse7650701);
  707.                             #   Propriétaire
  708.                             $mailjet = new Mailjet();
  709.                             $mail_content_p $this->renderView('components/mail/_booking_balance_alert_1_p.html.twig'compact('booking''statics''constraint'));
  710.                             $mailjet->send("caurettemarc@gmail.com""gite-colombine.fr""maximeavril.dev@gmail.com"$booking->getFirstName() . " " $booking->getLastName(), "Alerte réservation N°" $booking->getUniqId(), $mail_content_pfalsefalse7650701);
  711.                             #   Logs de process
  712.                             $logs['balance'][1][$key]['process'] = 'Vérification N°1 du paiement du recliquat';
  713.                             $logs['balance'][1][$key]['content'] = $mail_content_c;
  714.                             #   Changement d'état 
  715.                             $booking->setIsBalancePaymentAlert1(true);
  716.                             $this->manager->persist($booking);
  717.                             #   Enregistrement des logs de process
  718.                             $ProcessLogs = new ProcessLogs();
  719.                             $ProcessLogs
  720.                                 ->setTitle($logs['balance']['title'])
  721.                                 ->setProcess($logs['balance'][1][$key]['process'])
  722.                                 ->setReference($logs['balance'][1][$key]['reference'])
  723.                                 ->setContent($logs['balance'][1][$key]['content'])
  724.                                 ->setCreatedAt(new DateTimeImmutable());
  725.                             $this->manager->persist($ProcessLogs);
  726.                         }
  727.                     }
  728.                 }
  729.                 ###   Alerte 2 reliquat
  730.                 if ($booking->getIsBalancePaymentAlert2() != true && $booking->getIsBalancePaymentAlert1() == true && $booking->getIsBalancePayed() != true) {
  731.                     #   Réservation iminente
  732.                     if ($isForSoon == true) {
  733.                         #   On vérifie si nous sommes 72h après la deadline de paiement du montant total
  734.                         if ((date('U'strtotime($now))) > (date('U'strtotime($balancePaymentDeadline->format('Y-m-d')) + (84600)))) {
  735.                             #   Logs de process
  736.                             $logs['balance'][2][$key]['reference'] = $booking->getUniqId();
  737.                             #   Récupéreration du contenu du mail
  738.                             $templateMail_locataire $bookingMailRepo->findOneBy(['title' => 'Alerte solde N°2 : Réservation imminente']);
  739.                             ##  Envoi d'email d'alerte MailJet 
  740.                             #   Client
  741.                             $mailjet = new Mailjet();
  742.                             $mail_content_c $this->replaceVar($templateMail_locataire->translate($booking->getLocale())->getContent(), $booking$constraint);
  743.                             $mailjet->send("caurettemarc@gmail.com""gite-colombine.fr"$booking->getEmail(), $booking->getFirstName() . " " $booking->getLastName(), $this->translator->trans("Votre réservation") . " N°" $booking->getUniqId(), $mail_content_cfalsefalse7650701);
  744.                             #   Propriétaire
  745.                             $mailjet = new Mailjet();
  746.                             $mail_content_p $this->renderView('components/mail/_booking_balance_alert_2_p.html.twig'compact('booking''statics''constraint'));
  747.                             $mailjet->send("caurettemarc@gmail.com""gite-colombine.fr""maximeavril.dev@gmail.com"$booking->getFirstName() . " " $booking->getLastName(), "Alerte réservation N°" $booking->getUniqId(), $mail_content_pfalsefalse7650701);
  748.                             #   Logs de process
  749.                             $logs['balance'][2][$key]['process'] = 'Vérification N°1 du paiement total';
  750.                             $logs['balance'][2][$key]['content'] = $mail_content_c;
  751.                             #   Changement d'état 
  752.                             $booking
  753.                                 ->setIsBalancePaymentAlert2(true)
  754.                                 ->setTracking(false);
  755.                             $this->manager->persist($booking);
  756.                             #   Enregistrement des logs de process
  757.                             $ProcessLogs = new ProcessLogs();
  758.                             $ProcessLogs
  759.                                 ->setTitle($logs['balance']['title'])
  760.                                 ->setProcess($logs['balance'][2][$key]['process'])
  761.                                 ->setReference($logs['balance'][2][$key]['reference'])
  762.                                 ->setContent($logs['balance'][2][$key]['content'])
  763.                                 ->setCreatedAt(new DateTimeImmutable());
  764.                             $this->manager->persist($ProcessLogs);
  765.                         }
  766.                         #   Réservation normale
  767.                     } else {
  768.                         #   Pour chaque reservation on vérifie si la balancePaymentDeadline + 72h est dépasser pour envoyer une 2eme alerte au client
  769.                         if ((date('U'strtotime($now))) > (date('U'strtotime($balancePaymentDeadline->format('Y-m-d'))) + (84600))) {
  770.                             #   Logs de process
  771.                             $logs['balance'][2][$key]['reference'] = $booking->getUniqId();
  772.                             #   Récupéreration du contenu du mail
  773.                             $templateMail_locataire $bookingMailRepo->findOneBy(['title' => 'Alerte solde N°2 : Réservation classique']);
  774.                             ##  Envoi d'email d'alerte MailJet 
  775.                             #   Client
  776.                             $mailjet = new Mailjet();
  777.                             $mail_content_c $this->replaceVar($templateMail_locataire->translate($booking->getLocale())->getContent(), $booking$constraint);
  778.                             $mailjet->send("caurettemarc@gmail.com""gite-colombine.fr"$booking->getEmail(), $booking->getFirstName() . " " $booking->getLastName(), $this->translator->trans("Votre réservation") . " N°" $booking->getUniqId(), $mail_content_cfalsefalse7650701);
  779.                             #   Propriétaire
  780.                             $mailjet = new Mailjet();
  781.                             $mail_content_p $this->renderView('components/mail/_booking_balance_alert_2_p.html.twig'compact('booking''statics''constraint'));
  782.                             $mailjet->send("caurettemarc@gmail.com""gite-colombine.fr""maximeavril.dev@gmail.com"$booking->getFirstName() . " " $booking->getLastName(), "Alerte réservation N°" $booking->getUniqId(), $mail_content_pfalsefalse7650701);
  783.                             #   Logs de process
  784.                             $logs['balance'][2][$key]['process'] = 'Vérification N°1 du paiement du recliquat';
  785.                             $logs['balance'][2][$key]['content'] = $mail_content_c;
  786.                             #   Changement d'état 
  787.                             $booking
  788.                                 ->setIsBalancePaymentAlert2(true)
  789.                                 ->setTracking(false);
  790.                             $this->manager->persist($booking);
  791.                             #   Enregistrement des logs de process
  792.                             $ProcessLogs = new ProcessLogs();
  793.                             $ProcessLogs
  794.                                 ->setTitle($logs['balance']['title'])
  795.                                 ->setProcess($logs['balance'][2][$key]['process'])
  796.                                 ->setReference($logs['balance'][2][$key]['reference'])
  797.                                 ->setContent($logs['balance'][2][$key]['content'])
  798.                                 ->setCreatedAt(new DateTimeImmutable());
  799.                             $this->manager->persist($ProcessLogs);
  800.                         }
  801.                     }
  802.                 }
  803.             }
  804.         }
  805.         $this->manager->flush();
  806.         // return new Response('success', 200);
  807.         return new JsonResponse($logs);
  808.     }
  809.     /** 
  810.      * Permet de récupérer la date la plus éloignée parmis les periodes des saisons en BDD
  811.      * Afin de bloquer les reservations en ligne après cette date
  812.      * 
  813.      * @Route("/booking/get-end-date", name="booking_end_date")
  814.      */
  815.     public function getEndDate()
  816.     {
  817.         $saisons $this->constraint->getSaisons();
  818.         $endDates = [];
  819.         foreach ($saisons as $key => $saison) {
  820.             foreach ($saison->getPeriods() as $key => $period) {
  821.                 $endDates[] = date('U'strtotime($period->getEndDate()->format('Y-m-d')));
  822.             }
  823.         }
  824.         sort($endDatesSORT_NUMERIC);
  825.         $endDate date('d/m/Y'array_slice($endDates, -11)[0]);
  826.         return $endDate;
  827.     }
  828.     /** 
  829.      * Permet d'afficher la page des conditions générales
  830.      * 
  831.      * @Route("/booking/conditions-generales", name="booking_conditions")
  832.      */
  833.     public function showConditions()
  834.     {
  835.         $page $this->pageRepo->findOneBy(['page' => 'CGV']);
  836.         #   Redirection sur la page de validation de réservation
  837.         return $this->render('booking/conditions.html.twig', [
  838.             'statics' => $this->statics['data'],
  839.             'page' => $page,
  840.             'constraints' => $this->constraint,
  841.         ]);
  842.     }
  843.     /** 
  844.      * Permet de générer un PDF a partir d'un template HTML
  845.      * 
  846.      * @Route("/booking/make-pdf/{uid}", name="booking_make_pdf")
  847.      */
  848.     public function makePdf($uid$template$request$for null)
  849.     {
  850.         $locale $request->attributes->get('_locale');
  851.         $html2pdf = new Html2Pdf('p''A4'$localetrue'UTF-8', [15151515], true);
  852.         $html2pdf->writeHTML($template);
  853.         if ($for == 'bailleur') {
  854.             $html2pdf->output('/home/maxappu/www/' str_replace('https://'''$request->getSchemeAndHttpHost()) . '/v3/public/file/contrats/contrat-' $uid '-bailleur.pdf''F');
  855.         } elseif ($for == 'locataire') {
  856.             $html2pdf->output('/home/maxappu/www/' str_replace('https://'''$request->getSchemeAndHttpHost()) . '/v3/public/file/contrats/contrat-' $uid '-locataire.pdf''F');
  857.         }
  858.         return $this->json(true);
  859.     }
  860.     /** 
  861.      * Permet de remplacer les variables des templates de mail
  862.      * 
  863.      * @Route("/{_locale}/booking/replacevar", name="booking_make_pdf")
  864.      */
  865.     public function replaceVar($template$booking$constraint$for null)
  866.     {
  867.         $copyFor "";
  868.         if ($for == 'locataire') {
  869.             $copyFor "Copie pour le locataire";
  870.         } elseif ($for == 'bailleur') {
  871.             $copyFor "Copie pour le bailleur";
  872.         }
  873.         $search = [
  874.             '__uid__',
  875.             '__copyFor__',
  876.             '__a.phone__',
  877.             '__gender__',
  878.             '__firstname__',
  879.             '__lastname__',
  880.             '__advancePayment__',
  881.             '__c.advancePaymentDeadline__',
  882.             '__balance__',
  883.             '__c.balancePaymentDeadline__',
  884.             '__advancePaymentDeadline__',
  885.             '__balancePaymentDeadline__',
  886.             '__deposit__',
  887.             '__c.cautionPaymentDelay__',
  888.             '__cautionPaymentDeadline__',
  889.             '__finalAmount__',
  890.             '__rib__',
  891.             '__paypal__',
  892.             '__startdate__',
  893.             '__enddate__',
  894.             '__housework__',
  895.             '__staytax__',
  896.             '__email__',
  897.             '__phone__',
  898.             '__comment__',
  899.             '__dayprice__',
  900.             '__paymentMethod__',
  901.             '__number__',
  902.             '__duration__',
  903.             '__swikly_url__',
  904.         ];
  905.         $replace = [
  906.             $booking->getUniqId(),
  907.             $copyFor,
  908.             $this->statics['data']['about']->getPhone(),
  909.             $booking->getGender(),
  910.             $booking->getFirstName(),
  911.             $booking->getLastName(),
  912.             number_format(($booking->getAdvancePayment() / 100), 2','' '),
  913.             $constraint->getAdvancePaymentDeadline(),
  914.             number_format((($booking->getFinalAmount() - $booking->getAdvancePayment()) / 100), 2','' '),
  915.             $constraint->getBalancePaymentDeadline(),
  916.             $booking->getAdvancePaymentDeadline()->format('d/m/Y'),
  917.             $booking->getBalancePaymentDeadline()->format('d/m/Y'),
  918.             number_format(($booking->getDeposit() / 100), 2','' '),
  919.             $constraint->getCautionPaymentDelay(),
  920.             $booking->getCautionPaymentDeadline()->format('d/m/Y'),
  921.             number_format(($booking->getFinalAmount() / 100), 2','' '),
  922.             'www.gite-colombine.fr/images/profile/' $constraint->getPaymentMethods()[0]->getImg(),
  923.             $constraint->getPaymentMethods()[1]->getUrl(),
  924.             $booking->getStartDate()->format('d/m/Y'),
  925.             $booking->getEndDate()->format('d/m/Y'),
  926.             number_format(($booking->getHousework() / 100), 2','' '),
  927.             number_format(($booking->getStayTax() / 100), 2','' '),
  928.             $booking->getEmail(),
  929.             $booking->getPhone(),
  930.             html_entity_decode($booking->getComment()),
  931.             number_format(($booking->getDayPrice() / 100), 2','' '),
  932.             $booking->getPaymentMethod(),
  933.             $booking->getNumber(),
  934.             $booking->getDuration(),
  935.             $booking->getSwiklyUrl() ?? '',
  936.         ];
  937.         $template str_replace($search$replace$template);
  938.         return $template;
  939.     }
  940. }