src/Controller/RdvController.php line 7140

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use DateTime;
  4. use DateInterval;
  5. use DateTimeZone;
  6. use Dompdf\Dompdf;
  7. use App\Entity\Rdv;
  8. use Dompdf\Options;
  9. use App\Entity\Lieu;
  10. use App\Entity\Audio;
  11. use App\Entity\Motif;
  12. use App\Entity\Token;
  13. use Twig\Environment;
  14. use App\Entity\Centre;
  15. use App\Entity\Client;
  16. use \IntlDateFormatter;
  17. use App\Entity\EtatRdv;
  18. use App\Entity\LeadRdv;
  19. use App\Entity\Proches;
  20. use App\Entity\LieuTier;
  21. use App\Entity\RdvEvent;
  22. use App\Entity\AudioMotif;
  23. use App\Entity\CentreTier;
  24. use App\Entity\ClientTemp;
  25. use App\Entity\LeadStatus;
  26. use App\Entity\Remplacant;
  27. use App\Entity\TestClient;
  28. use App\Entity\AudioCentre;
  29. use App\Service\SmsHandler;
  30. use App\Entity\AccessCentre;
  31. use App\Entity\ClientStatus;
  32. use Psr\Log\LoggerInterface;
  33. use App\Entity\ClientBlocked;
  34. use App\Entity\CentreMutuelle;
  35. use App\Entity\LieuPrestation;
  36. use App\Entity\AudioSpecialite;
  37. use App\Service\PublicFunction;
  38. use App\Entity\CentrePrestation;
  39. use App\Entity\RegionDepartment;
  40. use App\Repository\RdvRepository;
  41. use Symfony\Component\Mime\Email;
  42. use App\Entity\Device\ClientDevice;
  43. use App\Entity\Notification\RdvSms;
  44. use App\Service\Lead\TwilioService;
  45. use App\Service\Lead\WhatsappService;
  46. use App\Entity\SynchronisationSetting;
  47. use App\Service\Lead\ElevenLabsService;
  48. use Doctrine\ORM\EntityManagerInterface;
  49. use Symfony\Contracts\Cache\ItemInterface;
  50. use App\Service\Cosium\ClientCosiumService;
  51. use App\Service\Notification\RdvSmsService;
  52. use Symfony\Contracts\Cache\CacheInterface;
  53. use App\Entity\Synchronisation\CosiumCenter;
  54. use App\Service\Lead\AppointmentCallService;
  55. use Symfony\Component\Filesystem\Filesystem;
  56. use Symfony\Component\HttpFoundation\Request;
  57. use Symfony\Component\Mailer\MailerInterface;
  58. use Symfony\Component\HttpFoundation\Response;
  59. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  60. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  61. use Symfony\Component\Routing\Annotation\Route;
  62. use Doctrine\Common\Collections\ArrayCollection;
  63. use App\EasyAdmin\Controller\DashboardController;
  64. use Symfony\Component\HttpKernel\KernelInterface;
  65. use Symfony\Component\HttpFoundation\JsonResponse;
  66. use App\EasyAdmin\Controller\LeadRdvCrudController;
  67. use App\Service\AdsCompany\RepresentativeCdaService;
  68. use App\Entity\Synchronisation\SynchronisationCosium;
  69. use App\Service\GoogleCalendar\GoogleCalendarService;
  70. use App\Service\Notification\EmailNotificationService;
  71. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  72. use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
  73. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  74. class RdvController extends AbstractController
  75. {
  76.     private $emailNotificationService;
  77.     private $clientCosiumService;
  78.     private $rdvRepository;
  79.     private $entityManager;
  80.     private $cache;
  81.     private $twig;
  82.     private AdminUrlGenerator $adminUrlGenerator;
  83.     private WhatsappService $whatsapp;
  84.     private LoggerInterface $logger;  // Service de journalisation
  85.     private RdvRepository $rdvRepo;
  86.     public function __construct(CacheInterface $cacheEntityManagerInterface $entityManager,RdvRepository $rdvRepoEmailNotificationService $emailNotificationServiceClientCosiumService $clientCosiumServiceRdvRepository $rdvRepositoryEnvironment $twigAdminUrlGenerator $adminUrlGeneratorWhatsappService $whatsappLoggerInterface $logger)
  87.     {
  88.         $this->entityManager $entityManager;
  89.         $this->emailNotificationService $emailNotificationService;
  90.         $this->clientCosiumService $clientCosiumService;
  91.         $this->rdvRepository $rdvRepository;
  92.         $this->cache $cache;
  93.         $this->twig $twig;
  94.         $this->adminUrlGenerator $adminUrlGenerator;
  95.         $this->whatsapp $whatsapp;
  96.         $this->logger $logger;
  97.         $this->rdvRepo $rdvRepo;
  98.     }
  99.     /**
  100.      * @Route("/rdv/{id}", name="deleteRdvByID", methods={"DELETE"})
  101.      */
  102.     public function deleteRdvByID(Request $requestRdv $rdvGoogleCalendarService $googleCalendar)
  103.     {
  104.         if (!$request->query->get('token')) {
  105.             return new Response(json_encode([
  106.                 "message" => "Pas de token n'a été spécifié",
  107.                 "status" => 401,
  108.             ]), 401);
  109.         }
  110.         $entityManager $this->getDoctrine()->getManager();
  111.         /** @var Token */
  112.         $token $this->getDoctrine()
  113.             ->getRepository(Token::class)
  114.             ->findOneBy(['token' => $request->query->get('token')]);
  115.         if (!$token) {
  116.             return new Response(json_encode([
  117.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  118.                 "status" => 404,
  119.             ]), 404);
  120.         }
  121.         // get token age
  122.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  123.         // if the token if older than 7 days
  124.         if ($dateDiff->7) {
  125.             $entityManager->remove($token);
  126.             $entityManager->flush();
  127.             return $this->json([
  128.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  129.                 'path' => 'src/Controller/ClientController.php',
  130.                 "status" => 401,
  131.             ], 401);
  132.         }
  133.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  134.             return new Response(json_encode([
  135.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  136.                 "status" => 404,
  137.             ]), 404);
  138.         }
  139.         $entityManager->remove($rdv);
  140.         $entityManager->flush();
  141.         return new Response(json_encode(([
  142.             'message' => "Rdv has been successfully deleted",
  143.             "status" => 200,
  144.         ])));
  145.     }
  146.     /**
  147.      * @Route("/rdv/{id}", name="getRdvByID", methods={"GET","HEAD"})
  148.      */
  149.     public function getRdvByID(Request $requestRdv $rdvPublicFunction $publicFunction)
  150.     {
  151.         if (!$request->query->get('token')) {
  152.             return new Response(json_encode([
  153.                 "message" => "Pas de token n'a été spécifié",
  154.                 "status" => 401,
  155.             ]), 401);
  156.         }
  157.         $entityManager $this->getDoctrine()->getManager();
  158.         /** @var Token */
  159.         $token $this->getDoctrine()
  160.             ->getRepository(Token::class)
  161.             ->findOneBy(['token' => $request->query->get('token')]);
  162.         if (!$token) {
  163.             return new Response(json_encode([
  164.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  165.                 "status" => 404,
  166.             ]), 404);
  167.         }
  168.         // get token age
  169.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  170.         // if the token if older than 7 days
  171.         if ($dateDiff->7) {
  172.             $entityManager->remove($token);
  173.             $entityManager->flush();
  174.             return $this->json([
  175.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  176.                 'path' => 'src/Controller/ClientController.php',
  177.                 "status" => 401,
  178.             ], 401);
  179.         }
  180.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  181.             return new Response(json_encode([
  182.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  183.                 "status" => 404,
  184.             ]), 404);
  185.         }
  186.         /** @var AudioCentre */
  187.         $liaison $this->getDoctrine()->getRepository(AudioCentre::class)
  188.             ->findOneBy(array('id_audio' => $rdv->getIdAudio(), 'id_centre' => $rdv->getIdCentre(), 'isConfirmed' => true));
  189.         // Motif filter
  190.         /** @var AudioMotif[] */
  191.         $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  192.             ->findBy(array('id_audio' => $rdv->getIdAudio(), 'id_motif' => $rdv->getIdMotif()));
  193.         $resultMotif = new ArrayCollection();
  194.         foreach ($motifs as $motif) {
  195.             $resultMotif->add([
  196.                 "id" => $motif->getIdMotif()->getId(),
  197.                 "titre" => $motif->getIdMotif()->getTitre(),
  198.                 "consigne" => $motif->getConsigne(),
  199.                 "duration" => $motif->getDuration(),
  200.             ]);
  201.         }
  202.         // Specialities
  203.         /** @var AudioSpecialite[] */
  204.         $specialities $this->getDoctrine()->getRepository(AudioSpecialite::class)
  205.             ->findBy(array('id_audio' => $rdv->getIdAudio()));
  206.         $resultSpeciality = new ArrayCollection();
  207.         foreach ($specialities as $speciality) {
  208.             $resultSpeciality->add([
  209.                 "id" => $speciality->getIdSpecialite()->getId(),
  210.                 "titre" => $speciality->getIdSpecialite()->getLibelle(),
  211.             ]);
  212.         }
  213.         if ($rdv->getIdCentre())
  214.         /** @var AccessCentre*/
  215.         {
  216.             $accessCentre $this->getDoctrine()->getRepository(AccessCentre::class)
  217.                 ->findOneBy(array('id_centre' => $rdv->getIdCentre()));
  218.         } else
  219.         /** @var AccessCentre*/
  220.         {
  221.             $accessCentre $this->getDoctrine()->getRepository(AccessCentre::class)
  222.                 ->findOneBy(array('id_lieu' => $rdv->getIdLieu()));
  223.         }
  224.         if ($rdv->getIdCentre())
  225.         /** @var CentrePrestation[]*/
  226.         {
  227.             $prestations $this->getDoctrine()->getRepository(CentrePrestation::class)
  228.                 ->findBy(array('id_centre' => $liaison->getIdCentre()->getId()));
  229.         } else
  230.         /** @var LieuPrestation[]*/
  231.         {
  232.             $prestations $this->getDoctrine()->getRepository(LieuPrestation::class)
  233.                 ->findBy(array('id_lieu' => $rdv->getIdLieu()));
  234.         }
  235.         $resultPrestation = new ArrayCollection();
  236.         foreach ($prestations as $prestation) {
  237.             $resultPrestation->add([
  238.                 "id" => $prestation->getIdPrestation()->getId(),
  239.                 "titre" => $prestation->getIdPrestation()->getLibelle(),
  240.             ]);
  241.         }
  242.         $mutuelles $this->getDoctrine()->getRepository(CentreMutuelle::class)
  243.             ->findBy(array('id_centre' => $rdv->getIdCentre()));
  244.         $resultMutuelle = new ArrayCollection();
  245.         foreach ($mutuelles as $mutuelle) {
  246.             $resultMutuelle->add([
  247.                 "id" => $mutuelle->getIdMutuelle()->getId(),
  248.                 "titre" => $mutuelle->getIdMutuelle()->getLibelle(),
  249.             ]);
  250.         }
  251.         if ($rdv->getIdCentre())
  252.         /** @var CentreTier[]*/
  253.         {
  254.             $tiers $this->getDoctrine()->getRepository(CentreTier::class)
  255.                 ->findBy(array('id_centre' => $liaison->getIdCentre()->getId()));
  256.         } else
  257.         /** @var LieuTier[]*/
  258.         {
  259.             $tiers $this->getDoctrine()->getRepository(LieuTier::class)
  260.                 ->findBy(array('id_lieu' => $rdv->getIdLieu()));
  261.         }
  262.         $resultTier = new ArrayCollection();
  263.         foreach ($tiers as $tier) {
  264.             $resultTier->add([
  265.                 "id" => $tier->getIdTier()->getId(),
  266.                 "titre" => $tier->getIdTier()->getLibelle(),
  267.             ]);
  268.         }
  269.         $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  270.         /** @var Rdv[] */
  271.         $audioRdvs $this->getDoctrine()->getRepository(Rdv::class)
  272.             ->findAllReviewsAudio($rdv->getIdAudio()->getId());
  273.         /** @var Rdv[] */
  274.         $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  275.             ->findAllReviewsCentre($rdvCentre->getId());
  276.         // Comment
  277.         /** @var Rdv[] */
  278.         $rdvs $this->getDoctrine()->getRepository(Rdv::class)
  279.             ->findBy(array('id_audio' => $rdv->getIdAudio()));
  280.         $comments = [];
  281.         foreach ($rdvs as $rdv)
  282.             if ($rdv->getComment() && $rdv->getReview() && $rdv->getIdClient())
  283.                 array_push($comments, [
  284.                     "id" => $rdv->getIdClient()->getId(),
  285.                     "name" => $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname()[0] . ".",
  286.                     "comment" => $rdv->getComment(),
  287.                     "isMale" => $rdv->getIdClient()->getCivilite() == "Monsieur",
  288.                     "review" => $rdv->getReview(),
  289.                 ]);
  290.         return new Response(json_encode(([
  291.             "id" => $rdv->getId(),
  292.             "motif_id" => $rdv->getIdMotif()->getId(),
  293.             "motif_titre" => $rdv->getIdMotif()->getTitre(),
  294.             "audio_id" => $rdv->getIdAudio()->getId(),
  295.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  296.             "client_id" => $rdv->getIdClient()->getId(),
  297.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  298.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  299.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  300.             "etat_id" => $rdv->getIdEtat()->getId(),
  301.             "date" => $rdv->getDate(),
  302.             "comment" => $rdv->getComment(),
  303.             "review" => $rdv->getReview(),
  304.             "note" => $rdv->getNote(),
  305.             "testclient" => $rdv->getTestClient() ? [
  306.                 "result" => $rdv->getTestClient()->getResultTonal(),
  307.                 "date" => $rdv->getTestClient()->getDate(),
  308.                 "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  309.             ] : null,
  310.             "comments" => $comments,
  311.             "audio" => [
  312.                 "id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : $rdv->getIdAudio()->getId(),
  313.                 "civilite" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getCivilite() : $rdv->getIdAudio()->getCivilite(),
  314.                 "name" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getName() : $rdv->getIdAudio()->getName(),
  315.                 "lastname" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getLastname() : $rdv->getIdAudio()->getLastname(),
  316.                 "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  317.                 "mail" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getMail() : $rdv->getIdAudio()->getMail(),
  318.                 "phone" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getPhone() : $rdv->getIdAudio()->getPhone(),
  319.                 "adeli" => $rdv->getIdAudio()->getAdeli(),
  320.                 "pin" => $rdv->getIdAudio()->getPin(),
  321.                 "description" => $rdv->getIdAudio()->getDescription(),
  322.                 "averageRating" => $publicFunction->calculateRating($audioRdvs),
  323.                 "nbrReview" => count($audioRdvs),
  324.                 "motifs" => $resultMotif->toArray(),
  325.                 "specialities" => $resultSpeciality->toArray(),
  326.             ],
  327.             "centre" => [
  328.                 "id" => $rdvCentre->getId(),
  329.                 "audio_id" => $rdvCentre->getIdGerant()->getId(),
  330.                 "name" => $rdvCentre->getName(),
  331.                 "imgUrl" => $rdvCentre->getImgUrl(),
  332.                 "isRdvDomicile" => $rdv->getIdCentre() ? $rdvCentre->getIsRdvDomicile() : $rdv->getIdAudio()->getIsRdvDomicileIndie(),
  333.                 "address" => $rdvCentre->getAddress(),
  334.                 "postale" => $rdvCentre->getPostale(),
  335.                 "city" => $rdvCentre->getCity(),
  336.                 "finess" => $rdvCentre->getFiness(),
  337.                 "siret" => $rdvCentre->getSiret(),
  338.                 "website" => $rdvCentre->getWebsite(),
  339.                 "phone" => $rdvCentre->getPhone(),
  340.                 "isHandicap" => $rdvCentre->getIsHandicap(),
  341.                 "longitude" => $rdvCentre->getLongitude(),
  342.                 "latitude" => $rdvCentre->getLatitude(),
  343.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  344.                 "nbrReview" => count($centreRdvs),
  345.                 "tram" => $accessCentre->getTram(),
  346.                 "rer" => $accessCentre->getRer(),
  347.                 "metro" => $accessCentre->getMetro(),
  348.                 "bus" => $accessCentre->getBus(),
  349.                 "parking" => $accessCentre->getParkingPublic(),
  350.                 "description" => $rdv->getIdCentre()->getDescription(),
  351.                 "parkingPrivate" => $accessCentre->getParkingPrivate(),
  352.                 "other" => $accessCentre->getOther(),
  353.                 "prestations" => $resultPrestation->toArray(),
  354.                 "mutuelles" => $resultMutuelle->toArray(),
  355.                 "tiers" => $resultTier->toArray(),
  356.                 "isLieu" => false,
  357.                 "schedule" => $rdv->getIdAudio()->getIsIndie() == false $rdv->getIdCentre()->getHoraire() : ($rdv->getIdLieu() ? $rdv->getIdLieu()->getHoraire() : $liaison->getHoraire()),
  358.             ],
  359.             "status" => 200,
  360.         ])));
  361.     }
  362.     /**
  363.      * @Route("/rdvs/client/{id}", name="getRdvsByClientID", methods={"GET","HEAD"})
  364.      */
  365.     public function getRdvsByClientID(Request $requestClient $clientPublicFunction $publicFunction)
  366.     {
  367.         if (!$request->query->get('token')) {
  368.             return new Response(json_encode([
  369.                 "message" => "Pas de token n'a été spécifié",
  370.                 "status" => 401,
  371.             ]), 401);
  372.         }
  373.         $entityManager $this->getDoctrine()->getManager();
  374.         /** @var Token */
  375.         $token $this->getDoctrine()
  376.             ->getRepository(Token::class)
  377.             ->findOneBy(['token' => $request->query->get('token')]);
  378.         if (!$token) {
  379.             return new Response(json_encode([
  380.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  381.                 "status" => 404,
  382.             ]), 404);
  383.         }
  384.         // get token age
  385.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  386.         // if the token if older than 7 days
  387.         if ($dateDiff->7) {
  388.             $entityManager->remove($token);
  389.             $entityManager->flush();
  390.             return $this->json([
  391.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  392.                 'path' => 'src/Controller/ClientController.php',
  393.                 "status" => 401,
  394.             ], 401);
  395.         }
  396.         if ($token->getIdClient()) {
  397.             if ($client != $token->getIdClient()) {
  398.                 return new Response(json_encode([
  399.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  400.                     "status" => 404,
  401.                 ]), 404);
  402.             }
  403.         } else if ($token->getIdAudio()) {
  404.             /** @var Token */
  405.             $token $this->getDoctrine()
  406.                 ->getRepository(Rdv::class)
  407.                 ->findOneBy(['id_client' => $client'id_audio' => $token->getIdAudio()]);
  408.             if ($client != $token->getIdClient()) {
  409.                 return new Response(json_encode([
  410.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  411.                     "status" => 404,
  412.                 ]), 404);
  413.             }
  414.         } else {
  415.             return new Response(json_encode([
  416.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  417.                 "status" => 404,
  418.             ]), 404);
  419.         }
  420.         if ($request->query->get('audio')) {
  421.             /** @var Rdv[] */
  422.             $rdvs $this->getDoctrine()
  423.                 ->getRepository(Rdv::class)
  424.                 ->findBy(['id_client' => $client->getId(), 'id_audio' => $token->getIdAudio()]);
  425.             $rdvResult = new ArrayCollection();
  426.         } else {
  427.             /** @var Rdv[] */
  428.             $rdvs $this->getDoctrine()
  429.                 ->getRepository(Rdv::class)
  430.                 ->findBy(['id_client' => $client->getId()]);
  431.             $rdvResult = new ArrayCollection();
  432.         }
  433.         if ($request->query->get('old')) {
  434.             $oldRdvResult = new ArrayCollection();
  435.         }
  436.         foreach ($rdvs as $rdv) {
  437.             if ($rdv->getIdEtat()->getId() != 1) {
  438.                 continue;
  439.             }
  440.             /** @var AudioMotif */
  441.             $audioMotif $this->getDoctrine()
  442.                 ->getRepository(AudioMotif::class)
  443.                 ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  444.             if (!$audioMotif) {
  445.                 continue;
  446.             }
  447.             $duration '';
  448.             if (is_null($rdv->getDuration())) {
  449.                 $duration $audioMotif->getDuration();
  450.             } else {
  451.                 $duration $rdv->getDuration();
  452.             }
  453.             $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  454.             /** @var Rdv[] */
  455.             $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  456.                 ->findAllReviewsCentre($rdvCentre->getId());
  457.             $rdvItem = [
  458.                 "id" => $rdv->getId(),
  459.                 "motif_id" => $rdv->getIdMotif()->getId(),
  460.                 "duration" => $duration,
  461.                 "color" => $audioMotif->getColor(),
  462.                 "audio_id" => $rdv->getIdAudio()->getId(),
  463.                 "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  464.                 "audio_name" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getName() . " " $rdv->getRemplacant()->getLastname() : $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  465.                 "client_id" => $rdv->getIdClient()->getId(),
  466.                 "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  467.                 "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  468.                 "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  469.                 "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  470.                 "testclient" => $rdv->getTestClient() ? [
  471.                     "result" => $rdv->getTestClient()->getResultTonal(),
  472.                     "date" => $rdv->getTestClient()->getDate(),
  473.                     "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  474.                 ] : null,
  475.                 "name" => $rdvCentre->getName(),
  476.                 "phone" => $rdvCentre->getPhone(),
  477.                 "imgUrl" => $rdvCentre->getImgUrl(),
  478.                 "address" => $rdvCentre->getAddress(),
  479.                 "postale" => $rdvCentre->getPostale(),
  480.                 "city" => $rdvCentre->getCity(),
  481.                 "etat_id" => $rdvCentre->getId(),
  482.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  483.                 "nbrReview" => count($centreRdvs),
  484.                 "acceptedCurrency" => "CB Chèque",
  485.                 "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  486.                 "note" => $rdv->getNote(),
  487.                 "comment" => $rdv->getComment(),
  488.                 "review" => $rdv->getReview(),
  489.             ];
  490.             if ($rdv->getDate() >= new DateTime()) {
  491.                 $rdvResult->add($rdvItem);
  492.             } else if ($request->query->get('old')) {
  493.                 $oldRdvResult->add($rdvItem);
  494.             }
  495.         }
  496.         if ($request->query->get('old')) {
  497.             if ($request->query->get('onlyOld')) {
  498.                 if (count($rdvResult) > || count($oldRdvResult) > 0) {
  499.                     return new Response(json_encode(([
  500.                         "oldRdv" => $oldRdvResult->toArray(),
  501.                         "status" => 200,
  502.                     ])));
  503.                 } else {
  504.                     return new Response(json_encode(([
  505.                         "message" => "Aucun rendez-vous n'a été trouvé!",
  506.                         "test" => "count:" count($rdvs),
  507.                         'path' => 'src/Controller/RdvController.php',
  508.                         "rdv" => array(),
  509.                         "oldRdv" => array(),
  510.                         "status" => 404,
  511.                     ])));
  512.                 }
  513.             } else {
  514.                 if (count($rdvResult) > || count($oldRdvResult) > 0) {
  515.                     return new Response(json_encode(([
  516.                         "rdv" => $rdvResult->toArray(),
  517.                         "oldRdv" => $oldRdvResult->toArray(),
  518.                         "status" => 200,
  519.                     ])));
  520.                 } else {
  521.                     return new Response(json_encode(([
  522.                         "message" => "Aucun rendez-vous n'a été trouvé!",
  523.                         "test" => "count:" count($rdvs),
  524.                         'path' => 'src/Controller/RdvController.php',
  525.                         "rdv" => array(),
  526.                         "oldRdv" => array(),
  527.                         "status" => 404,
  528.                     ])));
  529.                 }
  530.             }
  531.         } else {
  532.             if (count($rdvResult) > 0) {
  533.                 return new Response(json_encode(([
  534.                     "content" => $rdvResult->toArray(),
  535.                     "status" => 200,
  536.                 ])));
  537.             } else {
  538.                 return new Response(json_encode(([
  539.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  540.                     "test" => "count2:" count($rdvs),
  541.                     'path' => 'src/Controller/RdvController.php',
  542.                     "status" => 404,
  543.                 ])));
  544.             }
  545.         }
  546.     }
  547.     /**
  548.      * @Route("/rdvs/client/{id}/centre", name="getRdvsByClientIDForCentre", methods={"GET","HEAD"})
  549.      */
  550.     public function getRdvsByClientIDForCentre(Request $requestClient $clientPublicFunction $publicFunction)
  551.     {
  552.         if (!$request->query->get('token')) {
  553.             return new Response(json_encode([
  554.                 "message" => "Pas de token n'a été spécifié",
  555.                 "status" => 401,
  556.             ]), 401);
  557.         }
  558.         $entityManager $this->getDoctrine()->getManager();
  559.         /** @var Token */
  560.         $token $this->getDoctrine()
  561.             ->getRepository(Token::class)
  562.             ->findOneBy(['token' => $request->query->get('token')]);
  563.         if (!$token) {
  564.             return new Response(json_encode([
  565.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  566.                 "status" => 404,
  567.             ]), 404);
  568.         }
  569.         $audio $this->getDoctrine()
  570.             ->getRepository(Audio::class)
  571.             ->findOneBy(['id' => $request->query->get('audio')]);
  572.         $audioCentre $this->getDoctrine()
  573.             ->getRepository(AudioCentre::class)
  574.             ->findOneBy(['id_audio' => $audio]);
  575.         // get token age
  576.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  577.         // if the token if older than 7 days
  578.         if ($dateDiff->7) {
  579.             $entityManager->remove($token);
  580.             $entityManager->flush();
  581.             return $this->json([
  582.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  583.                 'path' => 'src/Controller/ClientController.php',
  584.                 "status" => 401,
  585.             ], 401);
  586.         }
  587.         if ($token->getIdClient()) {
  588.             if ($client != $token->getIdClient()) {
  589.                 return new Response(json_encode([
  590.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  591.                     "status" => 404,
  592.                 ]), 404);
  593.             }
  594.         } else if ($token->getIdAudio()) {
  595.             /** @var Token */
  596.             if ($token->getIdAudio() != $audio) {
  597.                 return new Response(json_encode([
  598.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  599.                     "status" => 404,
  600.                 ]), 404);
  601.             }
  602.         } else {
  603.             return new Response(json_encode([
  604.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  605.                 "status" => 404,
  606.             ]), 404);
  607.         }
  608.         if ($request->query->get('centre')) {
  609.             /** @var Rdv[] */
  610.             $rdvs $this->getDoctrine()
  611.                 ->getRepository(Rdv::class)
  612.                 ->findBy(['id_client' => $client->getId(), 'id_centre' => $audioCentre->getIdCentre()]);
  613.             $rdvResult = new ArrayCollection();
  614.         } else {
  615.             /** @var Rdv[] */
  616.             $rdvs $this->getDoctrine()
  617.                 ->getRepository(Rdv::class)
  618.                 ->findBy(['id_client' => $client->getId()]);
  619.             $rdvResult = new ArrayCollection();
  620.         }
  621.         if ($request->query->get('old')) {
  622.             $oldRdvResult = new ArrayCollection();
  623.         }
  624.         foreach ($rdvs as $rdv) {
  625.             /*if ($rdv->getIdEtat()->getId() != 1) {
  626.                 continue;
  627.             }*/
  628.             /** @var AudioMotif */
  629.             $audioMotif $this->getDoctrine()
  630.                 ->getRepository(AudioMotif::class)
  631.                 ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  632.             if (!$audioMotif) {
  633.                 continue;
  634.             }
  635.             $duration '';
  636.             if (is_null($rdv->getDuration())) {
  637.                 $duration $audioMotif->getDuration();
  638.             } else {
  639.                 $duration $rdv->getDuration();
  640.             }
  641.             $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  642.             /** @var Rdv[] */
  643.             $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  644.                 ->findAllReviewsCentre($rdvCentre->getId());
  645.             $rdvItem = [
  646.                 "id" => $rdv->getId(),
  647.                 "motif_id" => $rdv->getIdMotif()->getId(),
  648.                 "duration" => $duration,
  649.                 "color" => $audioMotif->getColor(),
  650.                 "audio_id" => $rdv->getIdAudio()->getId(),
  651.                 "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  652.                 "audio_name" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getName() . " " $rdv->getRemplacant()->getLastname() : $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  653.                 "client_id" => $rdv->getIdClient()->getId(),
  654.                 "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  655.                 "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  656.                 "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  657.                 "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  658.                 "testclient" => $rdv->getTestClient() ? [
  659.                     "result" => $rdv->getTestClient()->getResultTonal(),
  660.                     "date" => $rdv->getTestClient()->getDate(),
  661.                     "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  662.                 ] : null,
  663.                 "name" => $rdvCentre->getName(),
  664.                 "phone" => $rdvCentre->getPhone(),
  665.                 "imgUrl" => $rdvCentre->getImgUrl(),
  666.                 "address" => $rdvCentre->getAddress(),
  667.                 "postale" => $rdvCentre->getPostale(),
  668.                 "city" => $rdvCentre->getCity(),
  669.                 "etat_id" => $rdvCentre->getId(),
  670.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  671.                 "nbrReview" => count($centreRdvs),
  672.                 "acceptedCurrency" => "CB Chèque",
  673.                 "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  674.                 "note" => $rdv->getNote(),
  675.                 "comment" => $rdv->getComment(),
  676.                 "review" => $rdv->getReview(),
  677.                 "status" => $rdv->getIdEtat()->getLibelle()
  678.             ];
  679.             // dd(new DateTime());
  680.             if ($rdv->getDate() >= new DateTime()) {
  681.                 $rdvResult->add($rdvItem);
  682.             } else if ($request->query->get('old')) {
  683.                 $oldRdvResult->add($rdvItem);
  684.             }
  685.         }
  686.         if ($request->query->get('old')) {
  687.             if (count($rdvResult) > || count($oldRdvResult) > 0) {
  688.                 return new Response(json_encode(([
  689.                     "rdv" => $rdvResult->toArray(),
  690.                     "oldRdv" => $oldRdvResult->toArray(),
  691.                     "status" => 200,
  692.                 ])));
  693.             } else {
  694.                 return new Response(json_encode(([
  695.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  696.                     "test" => "count:" count($rdvs),
  697.                     'path' => 'src/Controller/RdvController.php',
  698.                     "status" => 404,
  699.                 ])), 404);
  700.             }
  701.         } else {
  702.             if (count($rdvResult) > 0) {
  703.                 return new Response(json_encode(([
  704.                     "content" => $rdvResult->toArray(),
  705.                     "status" => 200,
  706.                 ])));
  707.             } else {
  708.                 return new Response(json_encode(([
  709.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  710.                     "test" => "count2:" count($rdvs),
  711.                     'path' => 'src/Controller/RdvController.php',
  712.                     "status" => 404,
  713.                 ])));
  714.             }
  715.         }
  716.     }
  717.     /////// CRON
  718.     /**
  719.      * @Route("/confirmRdvSms", name="confirmRdvSms", methods={"GET","HEAD"})
  720.      */
  721.     public function confirmRdvSms(PublicFunction $publicFunction): Response
  722.     {
  723.         $date = new DateTime();
  724.         $minutes_to_add 30;
  725.         $date->add(new DateInterval('PT' $minutes_to_add 'M'));
  726.         $date->setTimezone(new DateTimeZone('Europe/Paris'));
  727.         $currentDate $date->format('Y-m-d H:i:00');
  728.         $toSend $this->getDoctrine()->getRepository(Rdv::class)
  729.             ->findRdvsIn10Mins($currentDate);
  730.         $entityManager $this->getDoctrine()->getManager();
  731.         $rdvResult = new ArrayCollection();
  732.         foreach ($toSend as $rdv) {
  733.             $date $rdv->getDate();
  734.             // $smsDate = $date->format('d-m-Y H:i');
  735.             //$client = $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  736.             //$sms = "Vous avez votre RDV du " . substr($smsDate, 0, 10) . " à " . substr($smsDate, 11, 15) . ", taper 1 si vous confirmer votre arrivé au centre auditif ou 2 si vous avez un empêchement.";
  737.             // // $publicFunction->sendEmail("MyAudio <noreply@myaudio.fr>", $client->getMail(), "My Audio: Testing CRON", "<p>Testing Cron.</p>");
  738.             //$response = $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone(), 4);
  739.             //$another_response = explode(" | ", $response);
  740.             // $idSms = trim($another_response[2]);
  741.             // $rdv->setIdSms($idSms);
  742.             //$entityManager->persist($rdv);
  743.             // $entityManager->flush();
  744.         }
  745.         return new Response(json_encode([
  746.             // "test" => $idSms,
  747.             "currentDate" => $currentDate
  748.         ]));
  749.     }
  750.     /////// CRON 
  751.     /**
  752.      * @Route("/validateRdvSms", name="validateRdvSms", methods={"GET","HEAD"})
  753.      */
  754.     public function validateRdvSms(Request $requestPublicFunction $publicFunction): Response
  755.     {
  756.         $smsId $request->query->get('token');
  757.         $message $request->query->get('message');
  758.         $rdv $this->getDoctrine()
  759.             ->getRepository(Rdv::class)
  760.             ->findOneBy(['id_sms' => $smsId]);
  761.         $date $rdv->getDate();
  762.         $currentDate date('Y-m-d H:i:s');
  763.         $smsDate $date->format('d-m-Y H:i');
  764.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  765.         $entityManager $this->getDoctrine()->getManager();
  766.         if ($date $currentDate) {
  767.             if ($message == "1") {
  768.                 $sms "Parfait, votre audioprothésiste est averti de votre venue. Présentez-vous à l'accueil du centre, il vous recevra dans quelques minutes.\nNe pas répondre";
  769.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  770.             } else if ($message == "2") {
  771.                 $sms "Votre absence est bien enregistrée, votre audioprothésiste est averti. Contactez votre centre pour reprogrammer un autre RDV.\nNe pas répondre.";
  772.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  773.                 $etat $this->getDoctrine()
  774.                     ->getRepository(EtatRdv::class)
  775.                     ->findOneBy(['id' => 2]);
  776.                 $rdv->setIdEtat($etat);
  777.                 $entityManager->persist($rdv);
  778.                 $entityManager->flush();
  779.             } else {
  780.                 return new Response(json_encode([
  781.                     "message" => "La réponse spécifiée est incorrecte",
  782.                     "status" => 401,
  783.                 ]), 401);
  784.             }
  785.         } else {
  786.             return new Response(json_encode([
  787.                 "message" => "Le rendez-vous est déjà passé, vous ne pouvez plus répondre à ce sms !",
  788.                 "status" => 401,
  789.             ]), 401);
  790.         }
  791.         return new Response(json_encode([
  792.             "smsId" => $smsId,
  793.             "message" => $currentDate
  794.         ]));
  795.     }
  796.     /**
  797.      * @Route("/rdvs/old/client/{id}", name="getOldRdvsByClientId", methods={"GET","HEAD"})
  798.      */
  799.     public function getOldRdvsByClientId(Request $requestClient $clientPublicFunction $publicFunction)
  800.     {
  801.         if (!$request->query->get('token')) {
  802.             return new Response(json_encode([
  803.                 "message" => "Pas de token n'a été spécifié",
  804.                 "status" => 401,
  805.             ]), 401);
  806.         }
  807.         $entityManager $this->getDoctrine()->getManager();
  808.         /** @var Token */
  809.         $token $this->getDoctrine()
  810.             ->getRepository(Token::class)
  811.             ->findOneBy(['token' => $request->query->get('token')]);
  812.         if (!$token) {
  813.             return new Response(json_encode([
  814.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  815.                 "status" => 404,
  816.             ]), 404);
  817.         }
  818.         // get token age
  819.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  820.         // if the token if older than 7 days
  821.         if ($dateDiff->7) {
  822.             $entityManager->remove($token);
  823.             $entityManager->flush();
  824.             return $this->json([
  825.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  826.                 'path' => 'src/Controller/ClientController.php',
  827.                 "status" => 401,
  828.             ], 401);
  829.         }
  830.         if ($token->getIdClient()) {
  831.             if ($client != $token->getIdClient()) {
  832.                 return new Response(json_encode([
  833.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  834.                     "status" => 404,
  835.                 ]), 404);
  836.             }
  837.         } else if ($token->getIdAudio()) {
  838.             /** @var Token */
  839.             $token $this->getDoctrine()
  840.                 ->getRepository(Rdv::class)
  841.                 ->findOneBy(['id_client' => $client'id_audio' => $token->getIdAudio()]);
  842.             if ($client != $token->getIdClient()) {
  843.                 return new Response(json_encode([
  844.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  845.                     "status" => 404,
  846.                 ]), 404);
  847.             }
  848.         } else {
  849.             return new Response(json_encode([
  850.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  851.                 "status" => 404,
  852.             ]), 404);
  853.         }
  854.         if ($request->query->get('audio')) {
  855.             /** @var ActivityRepository */
  856.             $activityRepo $this->getDoctrine();
  857.             if ($request->query->get('limit')) {
  858.                 /** @var Rdv[] */
  859.                 $rdvs $activityRepo
  860.                     ->getRepository(Rdv::class)
  861.                     ->findLastsOldRdvsWithLimit($request->query->get('limit'), $client->getId(), $request->query->get('audio'), new DateTime());
  862.                 $rdvResult = new ArrayCollection();
  863.             } else {
  864.                 /** @var Rdv[] */
  865.                 $rdvs $activityRepo
  866.                     ->getRepository(Rdv::class)
  867.                     ->findOldRdvs($client->getId(), $request->query->get('audio'), new DateTime());
  868.                 $rdvResult = new ArrayCollection();
  869.             }
  870.             foreach ($rdvs as $rdv) {
  871.                 /*if ($rdv->getIdEtat()->getId() != 1) {
  872.                     continue;
  873.                 }*/
  874.                 /** @var AudioMotif */
  875.                 $audioMotif $this->getDoctrine()
  876.                     ->getRepository(AudioMotif::class)
  877.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  878.                 if (!$audioMotif) {
  879.                     continue;
  880.                 }
  881.                 $duration '';
  882.                 if (is_null($rdv->getDuration())) {
  883.                     $duration $audioMotif->getDuration();
  884.                 } else {
  885.                     $duration $rdv->getDuration();
  886.                 }
  887.                 $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  888.                 /** @var Rdv[] */
  889.                 $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  890.                     ->findAllReviewsCentre($rdvCentre->getId());
  891.                 $rdvItem = [
  892.                     "id" => $rdv->getId(),
  893.                     "motif_id" => $rdv->getIdMotif()->getId(),
  894.                     "duration" => $duration,
  895.                     "color" => $audioMotif->getColor(),
  896.                     "audio_id" => $rdv->getIdAudio()->getId(),
  897.                     "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  898.                     "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  899.                     "client_id" => $rdv->getIdClient()->getId(),
  900.                     "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  901.                     "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  902.                     "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  903.                     "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  904.                     "testclient" => $rdv->getTestClient() ? [
  905.                         "result" => $rdv->getTestClient()->getResultTonal(),
  906.                         "date" => $rdv->getTestClient()->getDate(),
  907.                         "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  908.                     ] : null,
  909.                     "name" => $rdvCentre->getName(),
  910.                     "phone" => $rdvCentre->getPhone(),
  911.                     "imgUrl" => $rdvCentre->getImgUrl(),
  912.                     "address" => $rdvCentre->getAddress(),
  913.                     "postale" => $rdvCentre->getPostale(),
  914.                     "city" => $rdvCentre->getCity(),
  915.                     "etat_id" => $rdvCentre->getId(),
  916.                     "averageRating" => $publicFunction->calculateRating($centreRdvs),
  917.                     "nbrReview" => count($centreRdvs),
  918.                     "acceptedCurrency" => "CB Chèque",
  919.                     "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  920.                     "note" => $rdv->getNote(),
  921.                     "comment" => $rdv->getComment(),
  922.                     "review" => $rdv->getReview(),
  923.                 ];
  924.                 $rdvResult->add($rdvItem);
  925.             }
  926.         }
  927.         if (count($rdvResult) > 0) {
  928.             return new Response(json_encode(([
  929.                 "rdv" => $rdvResult->toArray(),
  930.                 "status" => 200,
  931.             ])));
  932.         } else {
  933.             return new Response(json_encode(([
  934.                 "message" => "Aucun rendez-vous a venir!",
  935.                 'path' => 'src/Controller/RdvController.php',
  936.                 "status" => 404,
  937.             ])));
  938.         }
  939.     }
  940.     /**
  941.      * @Route("/rdvs/old/client/{id}/centre", name="getOldRdvsByClientIdForCentre", methods={"GET","HEAD"})
  942.      */
  943.     public function getOldRdvsByClientIdForCentre(Request $requestClient $clientPublicFunction $publicFunction)
  944.     {
  945.         if (!$request->query->get('token')) {
  946.             return new Response(json_encode([
  947.                 "message" => "Pas de token n'a été spécifié",
  948.                 "status" => 401,
  949.             ]), 401);
  950.         }
  951.         $entityManager $this->getDoctrine()->getManager();
  952.         /** @var Token */
  953.         $token $this->getDoctrine()
  954.             ->getRepository(Token::class)
  955.             ->findOneBy(['token' => $request->query->get('token')]);
  956.         if (!$token) {
  957.             return new Response(json_encode([
  958.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  959.                 "status" => 404,
  960.             ]), 404);
  961.         }
  962.         $audio $this->getDoctrine()
  963.             ->getRepository(Audio::class)
  964.             ->findOneBy(['id' => $request->query->get('audio')]);
  965.         $audioCentre $this->getDoctrine()
  966.             ->getRepository(AudioCentre::class)
  967.             ->findOneBy(['id_audio' => $audio]);
  968.         // get token age
  969.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  970.         // if the token if older than 7 days
  971.         if ($dateDiff->7) {
  972.             $entityManager->remove($token);
  973.             $entityManager->flush();
  974.             return $this->json([
  975.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  976.                 'path' => 'src/Controller/ClientController.php',
  977.                 "status" => 401,
  978.             ], 401);
  979.         }
  980.         if ($token->getIdClient()) {
  981.             if ($client != $token->getIdClient()) {
  982.                 return new Response(json_encode([
  983.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  984.                     "status" => 404,
  985.                 ]), 404);
  986.             }
  987.         } else if ($token->getIdAudio()) {
  988.             /** @var Token */
  989.             if ($token->getIdAudio() != $audio) {
  990.                 return new Response(json_encode([
  991.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  992.                     "status" => 404,
  993.                 ]), 404);
  994.             }
  995.         } else {
  996.             return new Response(json_encode([
  997.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  998.                 "status" => 404,
  999.             ]), 404);
  1000.         }
  1001.         if ($request->query->get('audio')) {
  1002.             /** @var ActivityRepository */
  1003.             $activityRepo $this->getDoctrine();
  1004.             if ($request->query->get('limit')) {
  1005.                 /** @var Rdv[] */
  1006.                 $rdvs $activityRepo
  1007.                     ->getRepository(Rdv::class)
  1008.                     ->findLastsOldRdvCentresWithLimit($request->query->get('limit'), $client->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  1009.                 $rdvResult = new ArrayCollection();
  1010.             } else {
  1011.                 /** @var Rdv[] */
  1012.                 $rdvs $activityRepo
  1013.                     ->getRepository(Rdv::class)
  1014.                     ->findOldRdvsByCentre($client->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  1015.                 $rdvResult = new ArrayCollection();
  1016.             }
  1017.             //dd($rdvs);
  1018.             foreach ($rdvs as $rdv) {
  1019.                 // we comment this becoz it was just the validate , we implment other choice select
  1020.                 /* if ($rdv->getIdEtat()->getId() != 5) {
  1021.                     continue;
  1022.                 }*/
  1023.                 /** @var AudioMotif */
  1024.                 $audioMotif $this->getDoctrine()
  1025.                     ->getRepository(AudioMotif::class)
  1026.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  1027.                 if (!$audioMotif) {
  1028.                     continue;
  1029.                 }
  1030.                 $duration '';
  1031.                 if (is_null($rdv->getDuration())) {
  1032.                     $duration $audioMotif->getDuration();
  1033.                 } else {
  1034.                     $duration $rdv->getDuration();
  1035.                 }
  1036.                 $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  1037.                 /** @var Rdv[] */
  1038.                 $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  1039.                     ->findAllReviewsCentre($rdvCentre->getId());
  1040.                 $rdvItem = [
  1041.                     "id" => $rdv->getId(),
  1042.                     "motif_id" => $rdv->getIdMotif()->getId(),
  1043.                     "duration" => $duration,
  1044.                     "color" => $audioMotif->getColor(),
  1045.                     "audio_id" => $rdv->getIdAudio()->getId(),
  1046.                     "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  1047.                     "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  1048.                     "client_id" => $rdv->getIdClient()->getId(),
  1049.                     "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  1050.                     "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  1051.                     "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  1052.                     "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  1053.                     "testclient" => $rdv->getTestClient() ? [
  1054.                         "result" => $rdv->getTestClient()->getResultTonal(),
  1055.                         "date" => $rdv->getTestClient()->getDate(),
  1056.                         "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  1057.                     ] : null,
  1058.                     "name" => $rdvCentre->getName(),
  1059.                     "phone" => $rdvCentre->getPhone(),
  1060.                     "imgUrl" => $rdvCentre->getImgUrl(),
  1061.                     "address" => $rdvCentre->getAddress(),
  1062.                     "postale" => $rdvCentre->getPostale(),
  1063.                     "city" => $rdvCentre->getCity(),
  1064.                     "etat_id" => $rdvCentre->getId(),
  1065.                     "averageRating" => $publicFunction->calculateRating($centreRdvs),
  1066.                     "nbrReview" => count($centreRdvs),
  1067.                     "acceptedCurrency" => "CB Chèque",
  1068.                     "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  1069.                     "note" => $rdv->getNote(),
  1070.                     "comment" => $rdv->getComment(),
  1071.                     "review" => $rdv->getReview(),
  1072.                     "status" => $rdv->getIdEtat()->getLibelle()
  1073.                 ];
  1074.                 $rdvResult->add($rdvItem);
  1075.             }
  1076.         }
  1077.         if (count($rdvResult) > 0) {
  1078.             return new Response(json_encode(([
  1079.                 "rdv" => $rdvResult->toArray(),
  1080.                 "status" => 200,
  1081.             ])));
  1082.         } else {
  1083.             return new Response(json_encode(([
  1084.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  1085.                 'path' => 'src/Controller/RdvController.php',
  1086.                 "status" => 404,
  1087.             ])));
  1088.         }
  1089.     }
  1090.     private function getOpeningHours($centerId)
  1091.     {
  1092.         $center $this->getDoctrine()->getRepository(Centre::class)->find($centerId);
  1093.         $audioCentre $this->getDoctrine()->getRepository(AudioCentre::class)
  1094.             ->findOneBy(['id_centre' => $center->getId(), 'id_audio' => $center->getIdGerant()->getId()]);
  1095.         $schedule $audioCentre->getHoraire();
  1096.         $availableHours = [];
  1097.         if (isset($schedule['fixed'])) {
  1098.             foreach ($schedule['fixed'] as $day => $hours) {
  1099.                 $dayInFrench strtolower($day);
  1100.                 $slots = [];
  1101.                 foreach ($hours as $period) {
  1102.                     $start strtotime($period['open']);
  1103.                     $end strtotime($period['close']);
  1104.                     while ($start $end) {
  1105.                         $slots[] = date('H:i'$start);
  1106.                         $start strtotime('+30 minutes'$start);
  1107.                     }
  1108.                 }
  1109.                 $availableHours[$dayInFrench] = $slots;
  1110.             }
  1111.         }
  1112.         if (isset($schedule['exceptionalOpened'])) {
  1113.             foreach ($schedule['exceptionalOpened'] as $exception) {
  1114.                 $dayOfWeek strtolower(date('l'strtotime($exception['open'])));
  1115.                 $start strtotime($exception['open']);
  1116.                 $end strtotime($exception['close']);
  1117.                 $exceptionSlots = [];
  1118.                 while ($start $end) {
  1119.                     $exceptionSlots[] = date('H:i'$start);
  1120.                     $start strtotime('+30 minutes'$start);
  1121.                 }
  1122.                 $availableHours[$dayOfWeek] = array_merge(
  1123.                     $availableHours[$dayOfWeek] ?? [],
  1124.                     $exceptionSlots
  1125.                 );
  1126.             }
  1127.         }
  1128.         if (isset($schedule['exceptionalClosed'])) {
  1129.             foreach ($schedule['exceptionalClosed'] as $exception) {
  1130.                 $dayOfWeek strtolower(date('l'strtotime($exception['open'])));
  1131.                 unset($availableHours[$dayOfWeek]);
  1132.             }
  1133.         }
  1134.         return $availableHours;
  1135.     }
  1136.     private function getBookedSlotsForDate($centerId$date)
  1137.     {
  1138.         $bookedSlots $this->getDoctrine()
  1139.             ->getRepository(Rdv::class)
  1140.             ->getBookedSlotsForDate($centerId$date);
  1141.         return $bookedSlots;
  1142.     }
  1143.     private function getAvailableSlotsForDate($openingHours$centerId$date)
  1144.     {
  1145.         $dayOfWeek date('l'strtotime($date));
  1146.         $dayInFrench $this->convertDayToFrench($dayOfWeek);
  1147.         if (!$dayInFrench) {
  1148.             throw new \Exception("Invalid day of the week: $dayOfWeek");
  1149.         }
  1150.         $slots $openingHours[$dayInFrench] ?? [];
  1151.         $bookedSlots $this->getBookedSlotsForDate($centerId$date);
  1152.         $bookedTimes = [];
  1153.         foreach ($bookedSlots as $bookedSlot) {
  1154.             $startTime $bookedSlot['date'];
  1155.             $duration $bookedSlot['duration'];
  1156.             $endTime = (clone $startTime)->modify("+$duration minutes");
  1157.             $bookedTimes[] = ['start' => $startTime'end' => $endTime];
  1158.         }
  1159.         $availableSlots = [];
  1160.         foreach ($slots as $slot) {
  1161.             $slotTime \DateTime::createFromFormat('H:i'$slot);
  1162.             $slotTime->setDate(date('Y'strtotime($date)), date('m'strtotime($date)), date('d'strtotime($date)));
  1163.             if (!$slotTime) {
  1164.                 continue;
  1165.             }
  1166.             $isAvailable true;
  1167.             foreach ($bookedTimes as $bookedTime) {
  1168.                 if ($slotTime >= $bookedTime['start'] && $slotTime $bookedTime['end']) {
  1169.                     $isAvailable false;
  1170.                     break;
  1171.                 }
  1172.             }
  1173.             if ($isAvailable) {
  1174.                 $availableSlots[] = $slot;
  1175.             }
  1176.         }
  1177.         return $availableSlots;
  1178.     }
  1179.     private function convertDayToFrench($englishDay)
  1180.     {
  1181.         $daysMap = [
  1182.             'monday' => 'lundi',
  1183.             'tuesday' => 'mardi',
  1184.             'wednesday' => 'mercredi',
  1185.             'thursday' => 'jeudi',
  1186.             'friday' => 'vendredi',
  1187.             'saturday' => 'samedi',
  1188.             'sunday' => 'dimanche'
  1189.         ];
  1190.         return $daysMap[strtolower($englishDay)] ?? null;
  1191.     }
  1192.     /**
  1193.      * @Route("/audio/{id}/rdvs/", name="getAudioRdvs", methods={"GET","HEAD"})
  1194.      */
  1195.     public function getAudioRdvs(Request $requestAudio $audio)
  1196.     {
  1197.         if (!$request->query->get('token')) {
  1198.             return new Response(json_encode([
  1199.                 "message" => "Pas de token n'a été spécifié",
  1200.                 "status" => 401,
  1201.             ]), 401);
  1202.         }
  1203.         $entityManager $this->getDoctrine()->getManager();
  1204.         /** @var Token */
  1205.         $token $this->getDoctrine()
  1206.             ->getRepository(Token::class)
  1207.             ->findOneBy(['token' => $request->query->get('token')]);
  1208.         if (!$token) {
  1209.             return new Response(json_encode([
  1210.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1211.                 "status" => 404,
  1212.             ]), 404);
  1213.         }
  1214.         // get token age
  1215.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1216.         // if the token if older than 7 days
  1217.         if ($dateDiff->7) {
  1218.             $entityManager->remove($token);
  1219.             $entityManager->flush();
  1220.             return $this->json([
  1221.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1222.                 'path' => 'src/Controller/ClientController.php',
  1223.                 "status" => 401,
  1224.             ], 401);
  1225.         }
  1226.         if ($audio != $token->getIdAudio()) {
  1227.             return new Response(json_encode([
  1228.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1229.                 "status" => 404,
  1230.             ]), 404);
  1231.         }
  1232.         $centre = (int)$request->query->get('centre');
  1233.         if (($request->query->get('debut')) && ($request->query->get('fin'))) {
  1234.             $rdvs $this->getDoctrine()
  1235.                 ->getRepository(Rdv::class)
  1236.                 ->findBetweenDate(
  1237.                     $audio->getId(),
  1238.                     new DateTime($request->query->get('debut')),
  1239.                     new DateTime($request->query->get('fin')),
  1240.                     $centre // Le centre est maintenant un entier
  1241.                 );
  1242.         } else {
  1243.             $rdvs $this->getDoctrine()
  1244.                 ->getRepository(Rdv::class)
  1245.                 ->findBy(['id_audio' => $audio->getId()]);
  1246.         }
  1247.         $rdvResult = new ArrayCollection();
  1248.         $centerId $request->query->get('centre');
  1249.         // $openingHours = $this->getOpeningHours($centerId); 
  1250.         $centerId $request->query->get('centre');
  1251.         $dateCache = new \DateTime();
  1252.         $openingHours $this->cache->get('centre_' $centerId '_horaires_' $dateCache->format('Y-m-d'), function (ItemInterface $item) use ($centerId$dateCache) {
  1253.             $item->expiresAfter(7200);
  1254.             return $this->getOpeningHours($centerId);
  1255.         });
  1256.         //dd($openingHours);
  1257.         foreach ($rdvs as $rdv) {
  1258.             if ($rdv->getIdEtat()->getId() != null) {
  1259.                 if ($rdv->getIsAbsence() != 1) {
  1260.                     /** @var AudioMotif */
  1261.                     $audioMotif $this->getDoctrine()
  1262.                         ->getRepository(AudioMotif::class)
  1263.                         ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $audio->getId()]);
  1264.                     if (!isset($audioMotif)) {
  1265.                         continue;
  1266.                     }
  1267.                     $motif $this->getDoctrine()
  1268.                         ->getRepository(Motif::class)
  1269.                         ->findOneBy(['id' => $rdv->getIdMotif()->getId()]);
  1270.                     $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  1271.                     if ($rdv->getIdClientTemp()) {
  1272.                         $confiance "";
  1273.                     } else {
  1274.                         $confiance $client->getIdPersonneConfiance() ? $client->getIdPersonneConfiance()->getId() : null;
  1275.                     }
  1276.                 }
  1277.                 $duration '';
  1278.                 if (is_null($rdv->getDuration())) {
  1279.                     $duration $audioMotif->getDuration();
  1280.                 } else {
  1281.                     $duration $rdv->getDuration();
  1282.                 }
  1283.                 $dateFin = new DateTime($rdv->getDate()->format('Y-m-d\TH:i:s'));
  1284.                 $dateFin $dateFin->add(new DateInterval("PT" $duration "M"));
  1285.                 if ($rdv->getIdClientTemp()) {
  1286.                     $findNextRdv $this->getDoctrine()
  1287.                         ->getRepository(Rdv::class)
  1288.                         ->findBy([
  1289.                             "id_client_temp" => $rdv->getIdClientTemp(),
  1290.                             "id_motif" => ['106''107''108''109']
  1291.                         ]);
  1292.                 } else {
  1293.                     $findNextRdv $this->getDoctrine()
  1294.                         ->getRepository(Rdv::class)
  1295.                         ->findBy([
  1296.                             "id_client_temp" => $rdv->getIdClient(),
  1297.                             "id_motif" => ['106''107''108''109']
  1298.                         ]);
  1299.                 }
  1300.                 $finalRdv null;
  1301.                 /*if ($rdv->getRdvParent()) {
  1302.     $finalRdv = $this->getDoctrine()
  1303.         ->getRepository(Rdv::class)
  1304.         ->find($rdv->getRdvParent());
  1305. }*/
  1306.                 //if($client->getClientDevices())
  1307.                 //{
  1308.                 //if ($client->getClientDevices()->first()) {
  1309.                 /*$nextRdv = $this->getDoctrine()
  1310.                  ->getRepository(Rdv::class)
  1311.                  ->find($finalRdv->getClientDevice()->getRdv()->getId());*/
  1312.                 //  }
  1313.                 //}
  1314.                 if ($rdv->getIsAbsence() != 1) {
  1315.                     if ($rdv->getIdClientTemp()) {
  1316.                         $nextRdvs $this->getDoctrine()
  1317.                             ->getRepository(Rdv::class)
  1318.                             ->findBy([
  1319.                                 "id_client_temp" => $client,
  1320.                                 "id_motif" => ['106''107''108''109']
  1321.                             ]);
  1322.                     } else {
  1323.                         $nextRdvs $this->getDoctrine()
  1324.                             ->getRepository(Rdv::class)
  1325.                             ->findBy([
  1326.                                 "id_client" => $client,
  1327.                                 "id_motif" => ['106''107''108''109']
  1328.                             ]);
  1329.                     }
  1330.                     if ($client->getClientDevices()) {
  1331.                         if ($client->getClientDevices()->first()) {
  1332.                             if (empty($nextRdvs)) {
  1333.                                 $isNextRdv false;
  1334.                                 $initialRdvDate $rdv->getDate();
  1335.                                 $availableSlots = [
  1336.                                     'Suivi de l’essai' => $this->findFirstAvailableSlot($centerId$initialRdvDate7),
  1337.                                     'Confirmation de l’essai' => $this->findFirstAvailableSlot($centerId$initialRdvDate14),
  1338.                                     'Validation de l’appareillage' => $this->findFirstAvailableSlot($centerId$initialRdvDate21),
  1339.                                     'Facturation de l’appareillage' => $this->findFirstAvailableSlot($centerId$initialRdvDate30),
  1340.                                     'duration' => "30"
  1341.                                 ];
  1342.                                 $mappedNextRdvs = [
  1343.                                     'Suivi de l’essai' => $this->findAvailableDay($centerId$initialRdvDate7),
  1344.                                     'Confirmation de l’essai' => $this->findAvailableDay($centerId$initialRdvDate14),
  1345.                                     'Validation de l’appareillage' => $this->findAvailableDay($centerId$initialRdvDate21),
  1346.                                     'Facturation de l’appareillage' => $this->findAvailableDay($centerId$initialRdvDate30),
  1347.                                     'duration' => "30"
  1348.                                 ];
  1349.                             } else {
  1350.                                 $isNextRdv true;
  1351.                                 $initialRdvDate $rdv->getDate();
  1352.                                 // Available slots for each follow-up date
  1353.                                 $availableSlots = [];
  1354.                                 if (isset($nextRdvs[0])) {
  1355.                                     $availableSlots['Suivi de l’essai'] = $this->getAvailableSlotsForDate(
  1356.                                         $openingHours,
  1357.                                         $centerId,
  1358.                                         $nextRdvs[0]->getDate()->format('Y-m-d')
  1359.                                     );
  1360.                                 }
  1361.                                 if (isset($nextRdvs[1])) {
  1362.                                     $availableSlots['Confirmation de l’essai'] = $this->getAvailableSlotsForDate(
  1363.                                         $openingHours,
  1364.                                         $centerId,
  1365.                                         $nextRdvs[1]->getDate()->format('Y-m-d')
  1366.                                     );
  1367.                                 }
  1368.                                 if (isset($nextRdvs[2])) {
  1369.                                     $availableSlots['Validation de l’appareillage'] = $this->getAvailableSlotsForDate(
  1370.                                         $openingHours,
  1371.                                         $centerId,
  1372.                                         $nextRdvs[2]->getDate()->format('Y-m-d')
  1373.                                     );
  1374.                                 }
  1375.                                 if (isset($nextRdvs[3])) {
  1376.                                     $availableSlots['Facturation de l’appareillage'] = $this->getAvailableSlotsForDate(
  1377.                                         $openingHours,
  1378.                                         $centerId,
  1379.                                         $nextRdvs[3]->getDate()->format('Y-m-d')
  1380.                                     );
  1381.                                 }
  1382.                                 $mappedNextRdvs array_map(function ($rdv) {
  1383.                                     return [
  1384.                                         'id' => $rdv->getId(),
  1385.                                         'date' => $rdv->getDate()->format('d-m-Y'),
  1386.                                         'hours' => $rdv->getDate()->format('H:i'),
  1387.                                         'duration' => $rdv->getDuration(),
  1388.                                         "motif_id" => $rdv->getIdMotif()->getId(),
  1389.                                         "motif_titre" => $rdv->getIdMotif()->getTitre(),
  1390.                                     ];
  1391.                                 }, $nextRdvs);
  1392.                             }
  1393.                         }
  1394.                     }
  1395.                     $rdvItem = [
  1396.                         "id" => $rdv->getId(),
  1397.                         "motif_id" => $rdv->getIdMotif()->getId(),
  1398.                         "motif_titre" => $motif->getTitre(),
  1399.                         "duration" => $duration,
  1400.                         "color" => $audioMotif->getColor(),
  1401.                         "audio_id" => $rdv->getIdAudio()->getId(),
  1402.                         "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  1403.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  1404.                         "client_id" => $client->getId(),
  1405.                         "isClient" => ($client instanceof Client) ? 0,
  1406.                         "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() : $client->getName(),
  1407.                         "client_lastname" => $rdv->getIdProche() ? $rdv->getIdProche()->getLastname() : $client->getLastname(),
  1408.                         "client_mail" => $client->getMail(),
  1409.                         "client_tel" => $client->getPhone(),
  1410.                         "client_fixe" => $client->getPhoneFixe(),
  1411.                         "confiance" =>  $confiance,
  1412.                         "client_birthday" => $client->getBirthdate() ? $client->getBirthdate()->format("Y-m-d") : null,
  1413.                         "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  1414.                         "centre_id" => $rdv->getIdCentre()->getId(),
  1415.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  1416.                         "testclient" => $rdv->getTestClient() ? [
  1417.                             "result" => $rdv->getTestClient()->getResultTonal(),
  1418.                             "date" => $rdv->getTestClient()->getDate(),
  1419.                             "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  1420.                         ] : null,
  1421.                         "name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : $rdv->getIdLieu()->getName(),
  1422.                         "centerName" => $rdv->getIdCentre()->getName(),
  1423.                         "phone" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getPhone() : $rdv->getIdLieu()->getPhone(),
  1424.                         "etat_id" => $rdv->getIdEtat()->getId(),
  1425.                         "clientEtatId" => $client->getClientStatus() ? $client->getClientStatus()->getId() : 0,
  1426.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  1427.                         "dateFin" => $dateFin->format('Y-m-d\TH:i:s'),
  1428.                         "comment" => $rdv->getComment(),
  1429.                         "note" => $rdv->getNote(),
  1430.                         "isTemp" => $rdv->getIdClientTemp() ? 0,
  1431.                         "isAbsence" => $rdv->getIsAbsence(),
  1432.                         "device" => $client->getClientDevices()->first() ? [
  1433.                             "isDevice" => true,
  1434.                             "isNextRdv" => $isNextRdv,
  1435.                             "deviceID" => $client->getClientDevices()->first()->getDevice()->getId(),
  1436.                             "clientDeviceID" => $client->getClientDevices()->first()->getId(),
  1437.                             "deviceModel" => $client->getClientDevices()->first()->getDevice()->getModel(),
  1438.                             "settingDeviceId" => $client->getClientDevices()->first()->getSettingDevice()->getSlug(),
  1439.                             "settingName" => $client->getClientDevices()->first()->getSettingDevice()->getName(),
  1440.                             "settingSlug" => $client->getClientDevices()->first()->getSettingDevice()->getSlug(),
  1441.                             "nextRdvs" => $mappedNextRdvs,
  1442.                             "available_slots" => $availableSlots
  1443.                         ] : [
  1444.                             "isDevice" => false
  1445.                         ]
  1446.                     ];
  1447.                 } else {
  1448.                     // $clientDevice = $client->getClientDevices()->first();
  1449.                     $rdvItem = [
  1450.                         "id" => $rdv->getId(),
  1451.                         "duration" => $duration,
  1452.                         "color" => $rdv->getColor() ? $rdv->getColor() . '66' '#ffb2b266',
  1453.                         "audio_id" => $rdv->getIdAudio()->getId(),
  1454.                         "client_id" =>  "",
  1455.                         "isClient" => false,
  1456.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  1457.                         "centre_id" => $rdv->getIdCentre()->getId(),
  1458.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  1459.                         "name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : $rdv->getIdLieu()->getName(),
  1460.                         "phone" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getPhone() : $rdv->getIdLieu()->getPhone(),
  1461.                         "etat_id" => $rdv->getIdEtat()->getId(),
  1462.                         "clientEtatId" => "",
  1463.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  1464.                         "dateFin" => $dateFin->format('Y-m-d\TH:i:s'),
  1465.                         "note" => $rdv->getNote(),
  1466.                         "device" => "",
  1467.                         "centerName" => $rdv->getIdCentre()->getName(),
  1468.                         "isTemp" => $rdv->getIdClientTemp() ? 0,
  1469.                         "isAbsence" => $rdv->getIsAbsence(),
  1470.                         "motif_titre" => $rdv->getMotifAbsence() ? $rdv->getMotifAbsence() : "Absence",
  1471.                     ];
  1472.                 }
  1473.                 //  if ($rdv->getDate() >= new DateTime())
  1474.                 $rdvResult->add($rdvItem);
  1475.             }
  1476.         }
  1477.         $startDate = new \DateTime('2024-02-20');
  1478. $rdvs $this->rdvRepo->findRdvsNeedingReminderByAudio($startDate$audio->getId());
  1479. //dd($audio->getId());
  1480. $reminders = [];
  1481. //dd($rdvs);
  1482. foreach ($rdvs as $rdv) {
  1483.     $info $this->checkRdvReminder($rdv);
  1484.     if ($info !== null) {
  1485.         $reminders[] = $info;
  1486.     }
  1487. }
  1488. //dd($reminders);
  1489.         if (count($rdvResult) > 0) {
  1490.             return new Response(json_encode(([
  1491.                 "content" => $rdvResult->toArray(),
  1492.                 "status" => 200,
  1493.                 "reminders" => $reminders,
  1494.                 "datefin" => $dateFin
  1495.             ])));
  1496.         } else {
  1497.             $rdvItem = [];
  1498.             //$rdvResult->add($rdvItem);
  1499.             return new Response(json_encode(([
  1500.                 "content" => $rdvResult->toArray(),
  1501.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  1502.                 'path' => 'src/Controller/RdvController.php',
  1503.                 "reminders" => $reminders,
  1504.                 "status" => 404,
  1505.             ])));
  1506.         }
  1507.     }
  1508.     private function findAvailableDay(int $centerId\DateTime $initialRdvDateint $offset): string
  1509.     {
  1510.         $currentDate = (clone $initialRdvDate)->modify("+{$offset} days");
  1511.         while (true) {
  1512.             $formattedDate $currentDate->format('Y-m-d');
  1513.             $slots $this->getAvailableSlotsForDate(
  1514.                 $this->getOpeningHoursList($centerId$formattedDate),
  1515.                 $centerId,
  1516.                 $formattedDate
  1517.             );
  1518.             if (!empty($slots)) {
  1519.                 return $formattedDate;
  1520.             }
  1521.             $currentDate->modify('+1 day');
  1522.         }
  1523.     }
  1524.     private function findFirstAvailableSlot(int $centerId\DateTime $initialRdvDateint $offset): array
  1525.     {
  1526.         $currentDate = (clone $initialRdvDate)->modify("+{$offset} days");
  1527.         while (true) {
  1528.             $formattedDate $currentDate->format('Y-m-d');
  1529.             $slots $this->getAvailableSlotsForDate(
  1530.                 $this->getOpeningHoursList($centerId$formattedDate),
  1531.                 $centerId,
  1532.                 $formattedDate
  1533.             );
  1534.             if (!empty($slots)) {
  1535.                 return $slots;
  1536.             }
  1537.             $currentDate->modify('+1 day');
  1538.         }
  1539.     }
  1540.     private function getOpeningHoursList($centerId$date)
  1541.     {
  1542.         $center $this->getDoctrine()->getRepository(Centre::class)->find($centerId);
  1543.         $audioCentre $this->getDoctrine()->getRepository(AudioCentre::class)
  1544.             ->findOneBy(['id_centre' => $center->getId(), 'id_audio' => $center->getIdGerant()->getId()]);
  1545.         $schedule $audioCentre->getHoraire();
  1546.         $availableHours = [];
  1547.         $holidayDates = [
  1548.             'JourdelAn' => '01-01',
  1549.             'LundidePâques' => '21-04',
  1550.             'FêteduTravail' => '01-05',
  1551.             'Victoire1945' => '08-05',
  1552.             'Ascension' => '29-05',
  1553.             'LundidePentecôte' => '09-06',
  1554.             'FêteNationale' => '14-07',
  1555.             'Assomption' => '15-08',
  1556.             'Toussaint' => '01-11',
  1557.             'Armistice1918' => '11-11',
  1558.             'Noël' => '25-12',
  1559.         ];
  1560.         $holidays $center->getHorairesHoliday();
  1561.         $requestDate date('d-m'strtotime($date));
  1562.         $englishToFrenchDays = [
  1563.             'monday' => 'lundi',
  1564.             'tuesday' => 'mardi',
  1565.             'wednesday' => 'mercredi',
  1566.             'thursday' => 'jeudi',
  1567.             'friday' => 'vendredi',
  1568.             'saturday' => 'samedi',
  1569.             'sunday' => 'dimanche',
  1570.         ];
  1571.         $dayOfWeek strtolower(date('l'strtotime($date)));
  1572.         $dayInFrench $englishToFrenchDays[$dayOfWeek];
  1573.         if (isset($schedule['fixed'])) {
  1574.             foreach ($schedule['fixed'] as $day => $hours) {
  1575.                 $dayKey strtolower($day);
  1576.                 $slots = [];
  1577.                 foreach ($hours as $period) {
  1578.                     $start strtotime($period['open']);
  1579.                     $end strtotime($period['close']);
  1580.                     while ($start $end) {
  1581.                         $slots[] = date('H:i'$start);
  1582.                         $start strtotime('+30 minutes'$start);
  1583.                     }
  1584.                 }
  1585.                 $availableHours[$dayKey] = $slots;
  1586.             }
  1587.         }
  1588.         foreach ($holidays['fixed'] as $holiday => $hours) {
  1589.             if (isset($holidayDates[$holiday]) && $holidayDates[$holiday] === $requestDate) {
  1590.                 $holidaySlots = [];
  1591.                 if (!empty($hours)) {
  1592.                     foreach ($hours as $period) {
  1593.                         $start strtotime($period['open']);
  1594.                         $end strtotime($period['close']);
  1595.                         while ($start $end) {
  1596.                             $holidaySlots[] = date('H:i'$start);
  1597.                             $start strtotime('+30 minutes'$start);
  1598.                         }
  1599.                     }
  1600.                     $availableHours[$dayInFrench] = $holidaySlots;
  1601.                 } else {
  1602.                     $availableHours[$dayInFrench] = [];
  1603.                 }
  1604.                 break;
  1605.             }
  1606.         }
  1607.         return $availableHours;
  1608.     }
  1609.     /**
  1610.      * @Route("/audio/{id}/rdvsTest/", name="getAudioRdvsTest", methods={"GET","HEAD"})
  1611.      */
  1612.     public function getAudioRdvsTest(Request $requestAudio $audio)
  1613.     {
  1614.         if (!$request->query->get('token')) {
  1615.             return new Response(json_encode([
  1616.                 "message" => "Pas de token n'a été spécifié",
  1617.                 "status" => 401,
  1618.             ]), 401);
  1619.         }
  1620.         $entityManager $this->getDoctrine()->getManager();
  1621.         /** @var Token */
  1622.         $token $this->getDoctrine()
  1623.             ->getRepository(Token::class)
  1624.             ->findOneBy(['token' => $request->query->get('token')]);
  1625.         if (!$token) {
  1626.             return new Response(json_encode([
  1627.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1628.                 "status" => 404,
  1629.             ]), 404);
  1630.         }
  1631.         // get token age
  1632.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1633.         // if the token if older than 7 days
  1634.         if ($dateDiff->7) {
  1635.             $entityManager->remove($token);
  1636.             $entityManager->flush();
  1637.             return $this->json([
  1638.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1639.                 'path' => 'src/Controller/ClientController.php',
  1640.                 "status" => 401,
  1641.             ], 401);
  1642.         }
  1643.         if ($audio != $token->getIdAudio()) {
  1644.             return new Response(json_encode([
  1645.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1646.                 "status" => 404,
  1647.             ]), 404);
  1648.         }
  1649.         /** @var Rdv[] */
  1650.         if (($request->query->get('debut')) && ($request->query->get('fin'))) {
  1651.             $rdvs $this->getDoctrine()
  1652.                 ->getRepository(Rdv::class)
  1653.                 ->findBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1654.         } else {
  1655.             $rdvs $this->getDoctrine()
  1656.                 ->getRepository(Rdv::class)
  1657.                 ->findBy(['id_audio' => $audio->getId()]);
  1658.         }
  1659.         $rdvResult = new ArrayCollection();
  1660.         foreach ($rdvs as $rdv) {
  1661.             if ($rdv->getIdEtat()->getId() != null) {
  1662.                 /** @var AudioMotif */
  1663.                 $audioMotif $this->getDoctrine()
  1664.                     ->getRepository(AudioMotif::class)
  1665.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $audio->getId()]);
  1666.                 if (!isset($audioMotif)) {
  1667.                     continue;
  1668.                 }
  1669.                 $motif $this->getDoctrine()
  1670.                     ->getRepository(Motif::class)
  1671.                     ->findOneBy(['id' => $rdv->getIdMotif()->getId()]);
  1672.                 $dateFin = new DateTime($rdv->getDate()->format('Y-m-d H:i:s'));
  1673.                 $dateFin $dateFin->add(new DateInterval("PT" $audioMotif->getDuration() . "M"));
  1674.                 $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  1675.                 $name $rdv->getIdProche() ? $rdv->getIdProche()->getName() : $client->getName();
  1676.                 $lastName $rdv->getIdProche() ? $rdv->getIdProche()->getLastname() : $client->getLastname();
  1677.                 $rdvItem = [
  1678.                     "id" => $rdv->getId(),
  1679.                     "title" => $lastName ' ' $name,
  1680.                     "start" => $rdv->getDate()->format('Y-m-d H:i:s'),
  1681.                     "end"   => $dateFin->format('Y-m-d H:i:s'),
  1682.                     "backgroundColor" => $audioMotif->getColor(),
  1683.                     "editable" => true,
  1684.                     "durationEditable" => false,
  1685.                     "resourceEditable" => true,
  1686.                     "cache" => false,
  1687.                     "motif_id" => $rdv->getIdMotif()->getId(),
  1688.                     "motif" => $motif->getTitre(),
  1689.                     "duree" => $audioMotif->getDuration(),
  1690.                     "color" => $audioMotif->getColor(),
  1691.                     "color_motif" => $audioMotif->getColor(),
  1692.                     "client_id" => $client->getId(),
  1693.                     "clientName" => $name,
  1694.                     "clientLastName" => $lastName,
  1695.                     "mail" => $client->getMail(),
  1696.                     "telephone" => $client->getPhone(),
  1697.                     "birthday" => $client->getBirthdate(),
  1698.                     "etat_id" => $rdv->getIdEtat()->getId(),
  1699.                     "dateDeb" => $rdv->getDate()->format('Y-m-d H:i:s'),
  1700.                     "dateFin" => $dateFin->format('Y-m-d H:i:s'),
  1701.                     "commentaire" => $rdv->getNote(),
  1702.                     "event_title" => "<b>" $lastName "</b> " $name,
  1703.                 ];
  1704.                 //  if ($rdv->getDate() >= new DateTime())
  1705.                 $rdvResult->add($rdvItem);
  1706.             }
  1707.         }
  1708.         if (count($rdvResult) > 0) {
  1709.             return new Response(json_encode(
  1710.                 $rdvResult->toArray(),
  1711.             ));
  1712.         } else {
  1713.             $rdvItem = [];
  1714.             //$rdvResult->add($rdvItem);
  1715.             return new Response(json_encode(
  1716.                 $rdvResult->toArray(),
  1717.             ));
  1718.         }
  1719.     }
  1720.     /**
  1721.      * @Route("/audio/{id}/rdvs/count", name="getCountAudioRdvs", methods={"GET","HEAD"})
  1722.      */
  1723.     public function getCountAudioRdvs(Request $requestAudio $audio)
  1724.     {
  1725.         if (!$request->query->get('token')) {
  1726.             return new Response(json_encode([
  1727.                 "message" => "Pas de token n'a été spécifié",
  1728.                 "status" => 401,
  1729.             ]), 401);
  1730.         }
  1731.         $entityManager $this->getDoctrine()->getManager();
  1732.         /** @var Token */
  1733.         $token $this->getDoctrine()
  1734.             ->getRepository(Token::class)
  1735.             ->findOneBy(['token' => $request->query->get('token')]);
  1736.         if (!$token) {
  1737.             return new Response(json_encode([
  1738.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1739.                 "status" => 404,
  1740.             ]), 404);
  1741.         }
  1742.         // get token age
  1743.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1744.         // if the token if older than 7 days
  1745.         if ($dateDiff->7) {
  1746.             $entityManager->remove($token);
  1747.             $entityManager->flush();
  1748.             return $this->json([
  1749.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1750.                 'path' => 'src/Controller/ClientController.php',
  1751.                 "status" => 401,
  1752.             ], 401);
  1753.         }
  1754.         if ($audio != $token->getIdAudio()) {
  1755.             return new Response(json_encode([
  1756.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1757.                 "status" => 404,
  1758.             ]), 404);
  1759.         }
  1760.         /** @var Rdv[] */
  1761.         $rdvs $this->getDoctrine()
  1762.             ->getRepository(Rdv::class)
  1763.             ->findBy(['id_audio' => $audio->getId()]);
  1764.         return new Response(json_encode(([
  1765.             "content" => count($rdvs),
  1766.             "status" => 200,
  1767.         ])));
  1768.     }
  1769.     /**
  1770.      * @Route("/audio/{id}/rdvsDate/count", name="getCountAudioRdvsBetweenDate", methods={"GET","HEAD"})
  1771.      */
  1772.     public function getCountAudioRdvsBetweenDate(Request $requestAudio $audio)
  1773.     {
  1774.         if (!$request->query->get('token')) {
  1775.             return new Response(json_encode([
  1776.                 "message" => "Pas de token n'a été spécifié",
  1777.                 "status" => 401,
  1778.             ]), 401);
  1779.         }
  1780.         $entityManager $this->getDoctrine()->getManager();
  1781.         /** @var Token */
  1782.         $token $this->getDoctrine()
  1783.             ->getRepository(Token::class)
  1784.             ->findOneBy(['token' => $request->query->get('token')]);
  1785.         if (!$token) {
  1786.             return new Response(json_encode([
  1787.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1788.                 "status" => 404,
  1789.             ]), 404);
  1790.         }
  1791.         // get token age
  1792.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1793.         // if the token if older than 7 days
  1794.         if ($dateDiff->7) {
  1795.             $entityManager->remove($token);
  1796.             $entityManager->flush();
  1797.             return $this->json([
  1798.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1799.                 'path' => 'src/Controller/ClientController.php',
  1800.                 "status" => 401,
  1801.             ], 401);
  1802.         }
  1803.         if ($audio != $token->getIdAudio()) {
  1804.             return new Response(json_encode([
  1805.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1806.                 "status" => 404,
  1807.             ]), 404);
  1808.         }
  1809.         /** @var Rdv[] */
  1810.         $allRdvs $this->getDoctrine()
  1811.             ->getRepository(Rdv::class)
  1812.             ->findOnlyRdvAudioBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1813.         /** @var Rdv[] */
  1814.         $rdvs $this->getDoctrine()
  1815.             ->getRepository(Rdv::class)
  1816.             ->findOnlyRdvAudioWithoutTestBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1817.         /** @var Rdv[] */
  1818.         $rdvsWithTest $this->getDoctrine()
  1819.             ->getRepository(Rdv::class)
  1820.             ->findOnlyRdvAudioWithTestBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1821.         /** @var Rdv[] */
  1822.         $allRdvsCanceled $this->getDoctrine()
  1823.             ->getRepository(Rdv::class)
  1824.             ->findCanceledRdvAudioBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1825.         /** @var Rdv[] */
  1826.         $allRdvsCanceledCentre $this->getDoctrine()
  1827.             ->getRepository(Rdv::class)
  1828.             ->findCanceledRdvCentreBetweenDate(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1829.         /** @var Rdv[] */
  1830.         $rdvsClosed $this->getDoctrine()
  1831.             ->getRepository(Rdv::class)
  1832.             ->findClosedRdvBetweenDate(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1833.         $myLead 0;
  1834.         $rdvsCanceled $this->getDoctrine()
  1835.             ->getRepository(Rdv::class)
  1836.             ->findCanceledRdvAudioBetweenDateWithoutTest($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1837.         foreach ($rdvsCanceled as $rdvc) {
  1838.             if (!is_null($rdvc->getIdClient())) {
  1839.                 $rdvClient $this->getDoctrine()
  1840.                     ->getRepository(Rdv::class)
  1841.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1842.                 if (count($rdvClient) == 0) {
  1843.                     $myLead $myLead 1;
  1844.                 }
  1845.             }
  1846.         }
  1847.         $myLeadAdvanced 0;
  1848.         $rdvsCanceledA $this->getDoctrine()
  1849.             ->getRepository(Rdv::class)
  1850.             ->findCanceledRdvAudioBetweenDateWithTest($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1851.         foreach ($rdvsCanceledA as $rdvc) {
  1852.             if (!is_null($rdvc->getIdClient())) {
  1853.                 $rdvClient $this->getDoctrine()
  1854.                     ->getRepository(Rdv::class)
  1855.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1856.                 if (count($rdvClient) == 0) {
  1857.                     $myLeadAdvanced $myLeadAdvanced 1;
  1858.                 }
  1859.             }
  1860.         }
  1861.         /**** MY RDV Centre****/
  1862.         $myrdvCentre 0;
  1863.         $rdvs $this->getDoctrine()
  1864.             ->getRepository(Rdv::class)
  1865.             ->findRDVCentreBetweenDateWithoutTest(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1866.         $myrdvCentre count($rdvs);
  1867.         /**** MY RDV ADVANCED ****/
  1868.         $myRdvAdvancedCentre 0;
  1869.         $rdvsA $this->getDoctrine()
  1870.             ->getRepository(Rdv::class)
  1871.             ->findRDVCentreBetweenDateWithTestId(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1872.         $myRdvAdvancedCentre count($rdvsA);
  1873.         /**** FIRST RDV BY MOTIF PREMIER RDV ****/
  1874.         $myFirstRdv 0;
  1875.         $rdvsFirst $this->getDoctrine()
  1876.             ->getRepository(Rdv::class)
  1877.             ->findFirstRdv(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1878.         $myFirstRdv count($rdvsFirst);
  1879.         /****  RDV BY RECHERCHE RESULT VIA MYAUDIO ****/
  1880.         $myAudioRdv 0;
  1881.         $audioRdv $this->getDoctrine()
  1882.             ->getRepository(Rdv::class)
  1883.             ->findRdvMyAudio(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1884.         $myAudioRdv count($audioRdv);
  1885.         /****  RDV BY GENDER ****/
  1886.         $myRdvByGender 0;
  1887.         $audioRdvGender $this->getDoctrine()
  1888.             ->getRepository(Rdv::class)
  1889.             ->countMaleAndFemalePatient(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1890.         $myRdvByGender $audioRdvGender;
  1891.         /****  RDV BY AGE ****/
  1892.         $myRdvByAge 0;
  1893.         $audioRdvAge $this->getDoctrine()
  1894.             ->getRepository(Rdv::class)
  1895.             ->countClientsByAgeGroupsPatient(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1896.         $myRdvByAge $audioRdvAge;
  1897.         //  dd($myRdvByAge);
  1898.         /**** MY LEAD ****/
  1899.         $myLeadCentre 0;
  1900.         $rdvsCanceled $this->getDoctrine()
  1901.             ->getRepository(Rdv::class)
  1902.             ->findCanceledRdvCentreBetweenDateWithoutTest(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1903.         foreach ($rdvsCanceled as $rdvc) {
  1904.             if (!is_null($rdvc->getIdClient())) {
  1905.                 $rdvClient $this->getDoctrine()
  1906.                     ->getRepository(Rdv::class)
  1907.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1908.                 if (count($rdvClient) == 0) {
  1909.                     $myLeadCentre $myLeadCentre 1;
  1910.                 }
  1911.             }
  1912.         }
  1913.         /**** MY LEAD ADVANCED****/
  1914.         $myLeadAdvancedCentre 0;
  1915.         $rdvsCanceledA $this->getDoctrine()
  1916.             ->getRepository(Rdv::class)
  1917.             ->findCanceledRdvCentreBetweenDateWithTest(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1918.         foreach ($rdvsCanceledA as $rdvc) {
  1919.             if (!is_null($rdvc->getIdClient())) {
  1920.                 $rdvClient $this->getDoctrine()
  1921.                     ->getRepository(Rdv::class)
  1922.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1923.                 if (count($rdvClient) == 0) {
  1924.                     $myLeadAdvancedCentre $myLeadAdvancedCentre 1;
  1925.                 }
  1926.             }
  1927.         }
  1928.         return $this->json([
  1929.             "rdvs" => count($rdvs),
  1930.             "rdvsFromTest" => count($rdvsWithTest),
  1931.             "allRdvs" => count($allRdvs),
  1932.             "rdvsCanceled" => count($allRdvsCanceled),
  1933.             "rdvsClosed" => $rdvsClosed,
  1934.             "myRdvByGender" => $myRdvByGender,
  1935.             "myLead" => $myLead,
  1936.             "myRdvByAge" => $myRdvByAge,
  1937.             "myAudioRdv" => $myAudioRdv,
  1938.             "myLeadAdvanced" => $myLeadAdvanced,
  1939.             "myRDVCentre" => $myrdvCentre,
  1940.             "myRDVAdancedCentre" => $myRdvAdvancedCentre,
  1941.             "myLeadCentre" => $myLeadCentre,
  1942.             "myLeadAdvancedCentre" => $myLeadAdvancedCentre,
  1943.             "rdvsCanceledCentre" => count($allRdvsCanceledCentre),
  1944.             "myFirstRdv" => $myFirstRdv,
  1945.             "status" => 200,
  1946.         ]);
  1947.     }
  1948.     /**
  1949.      * @Route("/rdvs/old/clientTemp/{id}", name="getOldRdvsByClientTempId", methods={"GET","HEAD"})
  1950.      */
  1951.     public function getOldRdvsByClientTempId(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  1952.     {
  1953.         if (!$request->query->get('token')) {
  1954.             return new Response(json_encode([
  1955.                 "message" => "Pas de token n'a été spécifié",
  1956.                 "status" => 401,
  1957.             ]), 401);
  1958.         }
  1959.         $entityManager $this->getDoctrine()->getManager();
  1960.         /** @var Token */
  1961.         $token $this->getDoctrine()
  1962.             ->getRepository(Token::class)
  1963.             ->findOneBy(['token' => $request->query->get('token')]);
  1964.         if (!$token) {
  1965.             return new Response(json_encode([
  1966.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1967.                 "status" => 404,
  1968.             ]), 404);
  1969.         }
  1970.         // get token age
  1971.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1972.         // if the token if older than 7 days
  1973.         if ($dateDiff->7) {
  1974.             $entityManager->remove($token);
  1975.             $entityManager->flush();
  1976.             return $this->json([
  1977.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1978.                 'path' => 'src/Controller/ClientController.php',
  1979.                 "status" => 401,
  1980.             ], 401);
  1981.         }
  1982.         if ($clientTemp->getIdAudio() != $token->getIdAudio()) {
  1983.             return new Response(json_encode([
  1984.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1985.                 "status" => 404,
  1986.             ]), 404);
  1987.         }
  1988.         if ($request->query->get('audio')) {
  1989.             /** @var ActivityRepository */
  1990.             $activityRepo $this->getDoctrine()->getRepository(Rdv::class);
  1991.             if ($request->query->get('limit')) {
  1992.                 /** @var Rdv[] */
  1993.                 $rdvs $activityRepo
  1994.                     ->findLastsOldRdvsWithLimitTemp($request->query->get('limit'), $clientTemp->getId(), $request->query->get('audio'), new DateTime());
  1995.                 $rdvResult = new ArrayCollection();
  1996.             } else {
  1997.                 /** @var Rdv[] */
  1998.                 $rdvs $activityRepo
  1999.                     ->findOldRdvsTemp($clientTemp->getId(), $request->query->get('audio'), new DateTime());
  2000.                 $rdvResult = new ArrayCollection();
  2001.             }
  2002.             foreach ($rdvs as $rdv) {
  2003.                 if ($rdv->getIdEtat()->getId() != 1) {
  2004.                     continue;
  2005.                 }
  2006.                 /** @var AudioMotif */
  2007.                 $audioMotif $this->getDoctrine()
  2008.                     ->getRepository(AudioMotif::class)
  2009.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  2010.                 if (!$audioMotif) {
  2011.                     continue;
  2012.                 }
  2013.                 $duration '';
  2014.                 if (is_null($rdv->getDuration())) {
  2015.                     $duration $audioMotif->getDuration();
  2016.                 } else {
  2017.                     $duration $rdv->getDuration();
  2018.                 }
  2019.                 $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  2020.                 /** @var Rdv[] */
  2021.                 $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2022.                     ->findAllReviewsCentre($rdvCentre->getId());
  2023.                 $rdvItem = [
  2024.                     "id" => $rdv->getId(),
  2025.                     "motif_id" => $rdv->getIdMotif()->getId(),
  2026.                     "duration" => $duration,
  2027.                     "color" => $audioMotif->getColor(),
  2028.                     "audio_id" => $rdv->getIdAudio()->getId(),
  2029.                     "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2030.                     "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2031.                     "client_id_temp" => $rdv->getIdClientTemp()->getId(),
  2032.                     "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2033.                     "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2034.                     "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2035.                     "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2036.                     "testclient" => $rdv->getTestClient() ? [
  2037.                         "result" => $rdv->getTestClient()->getResultTonal(),
  2038.                         "date" => $rdv->getTestClient()->getDate(),
  2039.                         "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  2040.                     ] : null,
  2041.                     "name" => $rdvCentre->getName(),
  2042.                     "phone" => $rdvCentre->getPhone(),
  2043.                     "imgUrl" => $rdvCentre->getImgUrl(),
  2044.                     "address" => $rdvCentre->getAddress(),
  2045.                     "postale" => $rdvCentre->getPostale(),
  2046.                     "city" => $rdvCentre->getCity(),
  2047.                     "etat_id" => $rdvCentre->getId(),
  2048.                     "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2049.                     "nbrReview" => count($centreRdvs),
  2050.                     "acceptedCurrency" => "CB Chèque",
  2051.                     "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2052.                     "note" => $rdv->getNote(),
  2053.                     "comment" => $rdv->getComment(),
  2054.                     "review" => $rdv->getReview(),
  2055.                 ];
  2056.                 $rdvResult->add($rdvItem);
  2057.             }
  2058.         }
  2059.         if (count($rdvResult) > 0) {
  2060.             return new Response(json_encode(([
  2061.                 "rdv" => $rdvResult->toArray(),
  2062.                 "status" => 200,
  2063.             ])));
  2064.         } else {
  2065.             return new Response(json_encode(([
  2066.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  2067.                 'path' => 'src/Controller/RdvController.php',
  2068.                 "status" => 404,
  2069.             ])));
  2070.         }
  2071.     }
  2072.     /**
  2073.      * @Route("/rdvs/old/clientTemp/{id}/centre", name="getOldRdvsByClientTempIdByCentre", methods={"GET","HEAD"})
  2074.      */
  2075.     public function getOldRdvsByClientTempIdByCentre(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  2076.     {
  2077.         if (!$request->query->get('token')) {
  2078.             return new Response(json_encode([
  2079.                 "message" => "Pas de token n'a été spécifié",
  2080.                 "status" => 401,
  2081.             ]), 401);
  2082.         }
  2083.         $entityManager $this->getDoctrine()->getManager();
  2084.         /** @var Token */
  2085.         $token $this->getDoctrine()
  2086.             ->getRepository(Token::class)
  2087.             ->findOneBy(['token' => $request->query->get('token')]);
  2088.         if (!$token) {
  2089.             return new Response(json_encode([
  2090.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2091.                 "status" => 404,
  2092.             ]), 404);
  2093.         }
  2094.         // get token age
  2095.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2096.         // if the token if older than 7 days
  2097.         if ($dateDiff->7) {
  2098.             $entityManager->remove($token);
  2099.             $entityManager->flush();
  2100.             return $this->json([
  2101.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2102.                 'path' => 'src/Controller/ClientController.php',
  2103.                 "status" => 401,
  2104.             ], 401);
  2105.         }
  2106.         $audioCentre $this->getDoctrine()
  2107.             ->getRepository(AudioCentre::class)
  2108.             ->findOneBy(['id_audio' => $token->getIdAudio()]);
  2109.         // we add the multi-centre so we wil desable the autorisation 
  2110.         /*
  2111.         if ($clientTemp->getIdCentre() != $audioCentre->getIdCentre()) {
  2112.             return new Response(json_encode([
  2113.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2114.                 "status" => 404,
  2115.             ]), 404);
  2116.         }
  2117. */
  2118.         /** @var ActivityRepository */
  2119.         $activityRepo $this->getDoctrine()->getRepository(Rdv::class);
  2120.         if ($request->query->get('limit')) {
  2121.             /** @var Rdv[] */
  2122.             $rdvs $activityRepo
  2123.                 ->findLastsOldRdvsWithLimitTempByCentre($request->query->get('limit'), $clientTemp->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  2124.             $rdvResult = new ArrayCollection();
  2125.         } else {
  2126.             /** @var Rdv[] */
  2127.             $rdvs $activityRepo
  2128.                 ->findOldRdvsTempByCentre($clientTemp->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  2129.             $rdvResult = new ArrayCollection();
  2130.         }
  2131.         foreach ($rdvs as $rdv) {
  2132.             /*if ($rdv->getIdEtat()->getId() != 1) {
  2133.                 continue;
  2134.             }*/
  2135.             /** @var AudioMotif */
  2136.             $audioMotif $this->getDoctrine()
  2137.                 ->getRepository(AudioMotif::class)
  2138.                 ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  2139.             if (!$audioMotif) {
  2140.                 continue;
  2141.             }
  2142.             $duration '';
  2143.             if (is_null($rdv->getDuration())) {
  2144.                 $duration $audioMotif->getDuration();
  2145.             } else {
  2146.                 $duration $rdv->getDuration();
  2147.             }
  2148.             $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  2149.             /** @var Rdv[] */
  2150.             $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2151.                 ->findAllReviewsCentre($rdvCentre->getId());
  2152.             $rdvItem = [
  2153.                 "id" => $rdv->getId(),
  2154.                 "motif_id" => $rdv->getIdMotif()->getId(),
  2155.                 "duration" => $duration,
  2156.                 "color" => $audioMotif->getColor(),
  2157.                 "audio_id" => $rdv->getIdAudio()->getId(),
  2158.                 "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2159.                 "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2160.                 "client_id_temp" => $rdv->getIdClientTemp()->getId(),
  2161.                 "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2162.                 "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2163.                 "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2164.                 "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2165.                 "testclient" => $rdv->getTestClient() ? [
  2166.                     "result" => $rdv->getTestClient()->getResultTonal(),
  2167.                     "date" => $rdv->getTestClient()->getDate(),
  2168.                     "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  2169.                 ] : null,
  2170.                 "name" => $rdvCentre->getName(),
  2171.                 "phone" => $rdvCentre->getPhone(),
  2172.                 "imgUrl" => $rdvCentre->getImgUrl(),
  2173.                 "address" => $rdvCentre->getAddress(),
  2174.                 "postale" => $rdvCentre->getPostale(),
  2175.                 "city" => $rdvCentre->getCity(),
  2176.                 "etat_id" => $rdvCentre->getId(),
  2177.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2178.                 "nbrReview" => count($centreRdvs),
  2179.                 "acceptedCurrency" => "CB Chèque",
  2180.                 "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2181.                 "note" => $rdv->getNote(),
  2182.                 "comment" => $rdv->getComment(),
  2183.                 "review" => $rdv->getReview(),
  2184.                 "status" => $rdv->getIdEtat()->getLibelle()
  2185.             ];
  2186.             $rdvResult->add($rdvItem);
  2187.         }
  2188.         if (count($rdvResult) > 0) {
  2189.             return new Response(json_encode(([
  2190.                 "rdv" => $rdvResult->toArray(),
  2191.                 "status" => 200,
  2192.             ])));
  2193.         } else {
  2194.             return new Response(json_encode(([
  2195.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  2196.                 'path' => 'src/Controller/RdvController.php',
  2197.                 "status" => 404,
  2198.             ])));
  2199.         }
  2200.     }
  2201.     /**
  2202.      * @Route("/rdvs/clientTemp/{id}", name="getRdvsByClientTempID", methods={"GET","HEAD"})
  2203.      */
  2204.     public function getRdvsByClientTempID(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  2205.     {
  2206.         if (!$request->query->get('token')) {
  2207.             return new Response(json_encode([
  2208.                 "message" => "Pas de token n'a été spécifié",
  2209.                 "status" => 401,
  2210.             ]), 401);
  2211.         }
  2212.         $entityManager $this->getDoctrine()->getManager();
  2213.         /** @var Token */
  2214.         $token $this->getDoctrine()
  2215.             ->getRepository(Token::class)
  2216.             ->findOneBy(['token' => $request->query->get('token')]);
  2217.         if (!$token) {
  2218.             return new Response(json_encode([
  2219.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2220.                 "status" => 404,
  2221.             ]), 404);
  2222.         }
  2223.         // get token age
  2224.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2225.         // if the token if older than 7 days
  2226.         if ($dateDiff->7) {
  2227.             $entityManager->remove($token);
  2228.             $entityManager->flush();
  2229.             return $this->json([
  2230.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2231.                 'path' => 'src/Controller/ClientController.php',
  2232.                 "status" => 401,
  2233.             ], 401);
  2234.         }
  2235.         if ($clientTemp->getIdAudio() != $token->getIdAudio()) {
  2236.             return new Response(json_encode([
  2237.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2238.                 "status" => 404,
  2239.             ]), 404);
  2240.         }
  2241.         /** @var Rdv[] */
  2242.         $rdvs $this->getDoctrine()
  2243.             ->getRepository(Rdv::class)
  2244.             ->findBy(['id_client_temp' => $clientTemp->getId(), 'id_audio' => $token->getIdAudio()]);
  2245.         $rdvResult = new ArrayCollection();
  2246.         if ($request->query->get('old')) {
  2247.             $oldRdvResult = new ArrayCollection();
  2248.         }
  2249.         foreach ($rdvs as $rdv) {
  2250.             if ($rdv->getIdEtat()->getId() != null) {
  2251.                 if ($rdv->getIdEtat()->getId() == 1) {
  2252.                     /** @var AudioMotif */
  2253.                     $audioMotif $this->getDoctrine()
  2254.                         ->getRepository(AudioMotif::class)
  2255.                         ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $token->getIdAudio()]);
  2256.                     /** @var Rdv[] */
  2257.                     $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2258.                         ->findAllReviewsCentre($rdv->getIdCentre()->getId());
  2259.                     $duration '';
  2260.                     if (is_null($rdv->getDuration())) {
  2261.                         $duration $audioMotif->getDuration();
  2262.                     } else {
  2263.                         $duration $rdv->getDuration();
  2264.                     }
  2265.                     $rdvItem = [
  2266.                         "id" => $rdv->getId(),
  2267.                         "motif_id" => $rdv->getIdMotif()->getId(),
  2268.                         "duration" => $duration,
  2269.                         "color" => $audioMotif->getColor(),
  2270.                         "audio_id" => $rdv->getIdAudio()->getId(),
  2271.                         "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2272.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2273.                         "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  2274.                         "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2275.                         "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2276.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2277.                         "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2278.                         "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2279.                         "nbrReview" => count($centreRdvs),
  2280.                         "acceptedCurrency" => "CB Chèque",
  2281.                         "name" => $rdv->getIdCentre()->getName(),
  2282.                         "imgUrl" => $rdv->getIdCentre()->getImgUrl(),
  2283.                         "address" => $rdv->getIdCentre()->getAddress(),
  2284.                         "phone" => $rdv->getIdCentre()->getPhone(),
  2285.                         "etat_id" => $rdv->getIdEtat()->getId(),
  2286.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2287.                         "comment" => $rdv->getComment(),
  2288.                         "note" => $rdv->getNote(),
  2289.                         "review" => $rdv->getReview(),
  2290.                     ];
  2291.                     if ($rdv->getDate() >= new DateTime()) {
  2292.                         $rdvResult->add($rdvItem);
  2293.                     } else if ($request->query->get('old')) {
  2294.                         $oldRdvResult->add($rdvItem);
  2295.                     }
  2296.                 }
  2297.             }
  2298.         }
  2299.         if ($request->query->get('old')) {
  2300.             if (count($rdvResult) > || count($oldRdvResult) > 0) {
  2301.                 return new Response(json_encode(([
  2302.                     "rdv" => $rdvResult->toArray(),
  2303.                     "oldRdv" => $oldRdvResult->toArray(),
  2304.                     "status" => 200,
  2305.                 ])));
  2306.             } else {
  2307.                 return new Response(json_encode(([
  2308.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2309.                     'path' => 'src/Controller/RdvController.php',
  2310.                     "status" => 404,
  2311.                 ])));
  2312.             }
  2313.         } else {
  2314.             if (count($rdvResult) > 0) {
  2315.                 return new Response(json_encode(([
  2316.                     "content" => $rdvResult->toArray(),
  2317.                     "status" => 200,
  2318.                 ])));
  2319.             } else {
  2320.                 return new Response(json_encode(([
  2321.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2322.                     'path' => 'src/Controller/RdvController.php',
  2323.                     "status" => 404,
  2324.                 ])));
  2325.             }
  2326.         }
  2327.     }
  2328.     /**
  2329.      * @Route("/rdvs/clientTemp/{id}/centre", name="getRdvsByClientTempIDByCentre", methods={"GET","HEAD"})
  2330.      */
  2331.     public function getRdvsByClientTempIDByCentre(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  2332.     {
  2333.         if (!$request->query->get('token')) {
  2334.             return new Response(json_encode([
  2335.                 "message" => "Pas de token n'a été spécifié",
  2336.                 "status" => 401,
  2337.             ]), 401);
  2338.         }
  2339.         $entityManager $this->getDoctrine()->getManager();
  2340.         /** @var Token */
  2341.         $token $this->getDoctrine()
  2342.             ->getRepository(Token::class)
  2343.             ->findOneBy(['token' => $request->query->get('token')]);
  2344.         if (!$token) {
  2345.             return new Response(json_encode([
  2346.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2347.                 "status" => 404,
  2348.             ]), 404);
  2349.         }
  2350.         // get token age
  2351.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2352.         // if the token if older than 7 days
  2353.         if ($dateDiff->7) {
  2354.             $entityManager->remove($token);
  2355.             $entityManager->flush();
  2356.             return $this->json([
  2357.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2358.                 'path' => 'src/Controller/ClientController.php',
  2359.                 "status" => 401,
  2360.             ], 401);
  2361.         }
  2362.         $audioCentre $this->getDoctrine()
  2363.             ->getRepository(AudioCentre::class)
  2364.             ->findOneBy(['id_audio' => $token->getIdAudio()]);
  2365.         // we add the multi-centre so we wil desable the autorisation 
  2366.         /*    
  2367.         if ($clientTemp->getIdCentre() != $audioCentre->getIdCentre()) {
  2368.             return new Response(json_encode([
  2369.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2370.                 "status" => 404,
  2371.             ]), 404);
  2372.         }*/
  2373.         /** @var Rdv[] */
  2374.         $rdvs $this->getDoctrine()
  2375.             ->getRepository(Rdv::class)
  2376.             ->findBy(['id_client_temp' => $clientTemp->getId(), 'id_centre' => $audioCentre->getIdCentre()]);
  2377.         $rdvResult = new ArrayCollection();
  2378.         if ($request->query->get('old')) {
  2379.             $oldRdvResult = new ArrayCollection();
  2380.         }
  2381.         foreach ($rdvs as $rdv) {
  2382.             if ($rdv->getIdEtat()->getId() != null) {
  2383.                 if ($rdv->getIdEtat()->getId() != 6) {
  2384.                     // if ($rdv->getIdEtat()->getId() == 1) {
  2385.                     /** @var AudioMotif */
  2386.                     $audioMotif $this->getDoctrine()
  2387.                         ->getRepository(AudioMotif::class)
  2388.                         ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  2389.                     /** @var Rdv[] */
  2390.                     $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2391.                         ->findAllReviewsCentre($rdv->getIdCentre()->getId());
  2392.                     $duration '';
  2393.                     if (is_null($rdv->getDuration())) {
  2394.                         $duration $audioMotif->getDuration();
  2395.                     } else {
  2396.                         $duration $rdv->getDuration();
  2397.                     }
  2398.                     $rdvItem = [
  2399.                         "id" => $rdv->getId(),
  2400.                         "motif_id" => $rdv->getIdMotif()->getId(),
  2401.                         "duration" => $duration,
  2402.                         "color" => $audioMotif->getColor(),
  2403.                         "audio_id" => $rdv->getIdAudio()->getId(),
  2404.                         "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2405.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2406.                         "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  2407.                         "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2408.                         "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2409.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2410.                         "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2411.                         "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2412.                         "nbrReview" => count($centreRdvs),
  2413.                         "acceptedCurrency" => "CB Chèque",
  2414.                         "name" => $rdv->getIdCentre()->getName(),
  2415.                         "imgUrl" => $rdv->getIdCentre()->getImgUrl(),
  2416.                         "address" => $rdv->getIdCentre()->getAddress(),
  2417.                         "phone" => $rdv->getIdCentre()->getPhone(),
  2418.                         "etat_id" => $rdv->getIdEtat()->getId(),
  2419.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2420.                         "comment" => $rdv->getComment(),
  2421.                         "note" => $rdv->getNote(),
  2422.                         "review" => $rdv->getReview(),
  2423.                         "status" => $rdv->getIdEtat()->getLibelle()
  2424.                     ];
  2425.                     if ($rdv->getDate() >= new DateTime()) {
  2426.                         $rdvResult->add($rdvItem);
  2427.                     } else if ($request->query->get('old')) {
  2428.                         $oldRdvResult->add($rdvItem);
  2429.                     }
  2430.                 }
  2431.             }
  2432.         }
  2433.         if ($request->query->get('old')) {
  2434.             if (count($rdvResult) > || count($oldRdvResult) > 0) {
  2435.                 return new Response(json_encode(([
  2436.                     "rdv" => $rdvResult->toArray(),
  2437.                     "oldRdv" => $oldRdvResult->toArray(),
  2438.                     "status" => 200,
  2439.                 ])));
  2440.             } else {
  2441.                 return new Response(json_encode(([
  2442.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2443.                     'path' => 'src/Controller/RdvController.php',
  2444.                     "status" => 404,
  2445.                 ])));
  2446.             }
  2447.         } else {
  2448.             if (count($rdvResult) > 0) {
  2449.                 return new Response(json_encode(([
  2450.                     "content" => $rdvResult->toArray(),
  2451.                     "status" => 200,
  2452.                 ])));
  2453.             } else {
  2454.                 return new Response(json_encode(([
  2455.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2456.                     'path' => 'src/Controller/RdvController.php',
  2457.                     "status" => 404,
  2458.                 ])));
  2459.             }
  2460.         }
  2461.     }
  2462.     /**
  2463.      * @Route("/rdv", name="postRdv", methods={"POST"})
  2464.      */
  2465.     public function postRdv(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSmsAppointmentCallService $Callservice): Response
  2466.     {
  2467.         $data json_decode($request->getContent(), true);
  2468.         if (!isset($data["token"])) {
  2469.             return new Response(json_encode([
  2470.                 "message" => "Pas de token n'a été spécifié",
  2471.                 "status" => 401,
  2472.             ]), 401);
  2473.         }
  2474.         $entityManager $this->getDoctrine()->getManager();
  2475.         /** @var Token */
  2476.         $token $this->getDoctrine()
  2477.             ->getRepository(Token::class)
  2478.             ->findOneBy(['token' => $data["token"]]);
  2479.         if (!$token) {
  2480.             return new Response(json_encode([
  2481.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2482.                 "status" => 404,
  2483.             ]), 404);
  2484.         }
  2485.         // get token age
  2486.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2487.         // if the token if older than 7 days
  2488.         if ($dateDiff->7) {
  2489.             $entityManager->remove($token);
  2490.             $entityManager->flush();
  2491.             return $this->json([
  2492.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2493.                 'path' => 'src/Controller/ClientController.php',
  2494.                 "status" => 401,
  2495.             ], 401);
  2496.         }
  2497.         // makes the rdv
  2498.         $rdv = new Rdv();
  2499.         if ($token->getIdAudio()) {
  2500.             //if the token if for an audio
  2501.             $audio $token->getIdAudio();
  2502.             if ((isset($data["client_id"]))) {
  2503.                 $client $this->getDoctrine()
  2504.                     ->getRepository(Client::class)
  2505.                     ->findOneBy(['id' => $data["client_id"]]);
  2506.             } else {
  2507.                 $client $this->getDoctrine()
  2508.                     ->getRepository(ClientTemp::class)
  2509.                     ->findOneBy(['id' => $data["client_id_temp"]]);
  2510.             }
  2511.             if ($client == null) {
  2512.                 return new Response(json_encode(([
  2513.                     'message' => 'Error, no client found at this id',
  2514.                     'path' => 'src/Controller/RdvController.php',
  2515.                     "status" => 400,
  2516.                 ])), 400);
  2517.             }
  2518.         } elseif ($token->getIdClient()) {
  2519.             //if the token if for a client
  2520.             $client $token->getIdClient();
  2521.             /** @var ActivityRepository */
  2522.             $activityRepo $this->getDoctrine();
  2523.             /** @var TestClient */
  2524.             $testClient $activityRepo
  2525.                 ->getRepository(TestClient::class)
  2526.                 ->getLatestTestClient($client);
  2527.             // add the test to the rdv if the client had one
  2528.             if ($testClient)
  2529.             // add the test to the rdv if the test isn't already on another rdv
  2530.             {
  2531.                 if (!$testClient->getRdv()) {
  2532.                     $rdv->setTestClient($testClient);
  2533.                 }
  2534.             }
  2535.             /** @var Audio */
  2536.             $audio $this->getDoctrine()
  2537.                 ->getRepository(Audio::class)
  2538.                 ->findOneBy(['id' => $data["audio_id"]]);
  2539.             if (isset($data["proche_id"])) {
  2540.                 $proche $this->getDoctrine()
  2541.                     ->getRepository(Proches::class)
  2542.                     ->findOneBy(['id' => $data["proche_id"], "id_client" => $client]);
  2543.             }
  2544.             if (!$audio) {
  2545.                 return new Response(json_encode(([
  2546.                     'message' => "Erreur, pas d'audio n'a été trouvé à cette id.",
  2547.                     'path' => 'src/Controller/RdvController.php',
  2548.                 ])), 400);
  2549.             }
  2550.             /** @var ClientBlocked */
  2551.             $clientBlocked $this->getDoctrine()
  2552.                 ->getRepository(ClientBlocked::class)
  2553.                 ->findOneBy(["id_audio" => $audio"id_client" => $client]);
  2554.             if ($clientBlocked) {
  2555.                 return new Response(json_encode(([
  2556.                     'message' => 'Erreur, vous avez été bloqué par cette audioprothésiste.',
  2557.                     'path' => 'src/Controller/RdvController.php',
  2558.                 ])), 400);
  2559.             }
  2560.             // set the rdv test
  2561.         } else {
  2562.             return new Response(json_encode(([
  2563.                 'message' => "Erreur, ce token n'est pas celui d'un client ou audioprothèsiste.",
  2564.                 'path' => 'src/Controller/RdvController.php',
  2565.             ])), 400);
  2566.         }
  2567.         $rdv->setIdAudio($audio);
  2568.         if (isset($proche)) {
  2569.             $rdv->setIdProche($proche);
  2570.         }
  2571.         if (isset($data["client_id_temp"])) {
  2572.             $rdv->setIdClientTemp($client);
  2573.         } else {
  2574.             $rdv->setIdClient($client);
  2575.         }
  2576.         if (isset($data["isMyaudio"])) {
  2577.             $rdv->setIsMyaudio(true);
  2578.         }
  2579.         if (isset($data["isRdvLead"])) {
  2580.             $rdv->setIsRdvLp(true);
  2581.         }
  2582.         if (isset($data["isRdvRapide"])) {
  2583.             $rdv->setIsRdvRapide(true);
  2584.         }
  2585.         if (isset($data["duree"])) {
  2586.             $rdv->setDuration($data["duree"]);
  2587.         }
  2588.         if (isset($data["color"])) {
  2589.             $rdv->setColor($data["color"]);
  2590.         }
  2591.         if (isset($data["lead"])) {
  2592.             $lead $this->getDoctrine()
  2593.                 ->getRepository(LeadRdv::class)
  2594.                 ->find($data["lead"]);
  2595.             $lead->setRdv($rdv);
  2596.             $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'rdv_valider']);
  2597.             if ($leadStatus) {
  2598.                 $lead->setLeadStatus($leadStatus);
  2599.             }
  2600.         }
  2601.         /** @var Centre */
  2602.         if (isset($data["centre_id"])) {
  2603.             $centre $this->getDoctrine()
  2604.                 ->getRepository(Centre::class)
  2605.                 ->findOneBy(['id' => $data["centre_id"]]);
  2606.             if ($centre == null) {
  2607.                 return new Response(json_encode(([
  2608.                     'message' => 'Error, no centre found at this id',
  2609.                     'path' => 'src/Controller/RdvController.php',
  2610.                     "status" => 400,
  2611.                 ])), 400);
  2612.             }
  2613.             /** @var AudioCentre */
  2614.             $liaison $this->getDoctrine()
  2615.                 ->getRepository(AudioCentre::class)
  2616.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  2617.             if ($liaison == null) {
  2618.                 return new Response(json_encode(([
  2619.                     'message' => 'Error, audio isnt part of the centre',
  2620.                     'path' => 'src/Controller/RdvController.php',
  2621.                     "status" => 400,
  2622.                 ])), 400);
  2623.             }
  2624.             $rdv->setIdCentre($centre);
  2625.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  2626.             // tries to set the lieu if it's an audio indie
  2627.             $lieu $this->getDoctrine()
  2628.                 ->getRepository(Lieu::class)
  2629.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  2630.             if ($lieu == null) {
  2631.                 return new Response(json_encode(([
  2632.                     'message' => 'Error, no lieu found at this id',
  2633.                     'path' => 'src/Controller/RdvController.php',
  2634.                     "status" => 400,
  2635.                 ])), 400);
  2636.             }
  2637.             $rdv->setIdLieu($lieu);
  2638.         } else {
  2639.             return new Response(json_encode(([
  2640.                 'message' => 'Error, no lieu/centre id',
  2641.                 'path' => 'src/Controller/RdvController.php',
  2642.                 "status" => 400,
  2643.             ])), 400);
  2644.         }
  2645.         /** @var Motif */
  2646.         $motif $this->getDoctrine()
  2647.             ->getRepository(Motif::class)
  2648.             ->find($data["motif_id"]);
  2649.         if ($motif == null) {
  2650.             return new Response(json_encode(([
  2651.                 'message' => 'Error, no motif found at this id',
  2652.                 'path' => 'src/Controller/RdvController.php',
  2653.                 "status" => 400,
  2654.             ])), 400);
  2655.         }
  2656.         /** @var AudioMotif */
  2657.         $audioMotif $this->getDoctrine()
  2658.             ->getRepository(AudioMotif::class)
  2659.             ->findOneBy(["id_audio" => $audio->getId(), "id_motif" => $data["motif_id"]]);
  2660.         if ($audioMotif == null) {
  2661.             return new Response(json_encode(([
  2662.                 'message' => 'Error, no motif of this id found at this audio',
  2663.                 'path' => 'src/Controller/RdvController.php',
  2664.                 "status" => 400,
  2665.             ])), 400);
  2666.         }
  2667.         // remove the taken schedule by rdv to make sure there is no overlap
  2668.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  2669.         if (isset($data["note"])) {
  2670.             $rdv->setNote($data["note"]);
  2671.         }
  2672.         // test if the audio is available
  2673.         if ($audio->getIsIndie()) {
  2674.             if (isset($data["centre_id"])) {
  2675.                 if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  2676.                     return new Response(json_encode(([
  2677.                         'message' => 'Error, no horaire found for this audio',
  2678.                         'path' => 'src/Controller/RdvController.php',
  2679.                         "status" => 400,
  2680.                     ])), 400);
  2681.                 }
  2682.                 if ($publicFunction->calculScheduleFitDate($audio\DateTime::createFromFormat("d/m/Y H:i"$data["date"]), $audioMotif->getDuration(), $centre) == false) {
  2683.                     return new Response(json_encode(([
  2684.                         'message' => 'Error, no timestamp found at this time. Line n°' __LINE__,
  2685.                         'path' => 'src/Controller/RdvController.php',
  2686.                         "status" => 400,
  2687.                     ])), 400);
  2688.                 }
  2689.                 $remplacant_id $publicFunction->checkIfRemplacant($liaison->getHoraire(), $date);
  2690.             } else {
  2691.                 if ($lieu->getHoraire() == null || $lieu->getHoraire() == []) {
  2692.                     return new Response(json_encode(([
  2693.                         'message' => 'Error, no horaire found for this audio',
  2694.                         'path' => 'src/Controller/RdvController.php',
  2695.                         "status" => 400,
  2696.                     ])), 400);
  2697.                 }
  2698.                 if ($publicFunction->calculScheduleFitDate($audio\DateTime::createFromFormat("d/m/Y H:i"$data["date"]), $audioMotif->getDuration(), null$lieu) == false) {
  2699.                     return new Response(json_encode(([
  2700.                         'message' => 'Error, no timestamp found at this time. Line n°' __LINE__,
  2701.                         'path' => 'src/Controller/RdvController.php',
  2702.                         "status" => 400,
  2703.                     ])), 400);
  2704.                 }
  2705.                 $remplacant_id $publicFunction->checkIfRemplacant($lieu->getHoraire(), $date);
  2706.             }
  2707.         } else {
  2708.             if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  2709.                 return new Response(json_encode(([
  2710.                     'message' => 'Error, no horaire found for this audio',
  2711.                     'path' => 'src/Controller/RdvController.php',
  2712.                     "status" => 400,
  2713.                 ])), 400);
  2714.             }
  2715.             /*  if (!$publicFunction->calculScheduleFitDate($audio, \DateTime::createFromFormat("d/m/Y H:i", $data["date"]), $audioMotif->getDuration(), $centre))
  2716.                 return new Response(json_encode(([
  2717.                     'message' => "Error, no timestamp found at this time. Motif size: {$audioMotif->getDuration()} Line n°" . __LINE__,
  2718.                     'path' => 'src/Controller/RdvController.php',
  2719.                     "status" => 400,
  2720.                 ])), 400);*/
  2721.             $remplacant_id $publicFunction->checkIfRemplacant($liaison->getHoraire(), \DateTime::createFromFormat("d/m/Y H:i"$data["date"]));
  2722.         }
  2723.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  2724.         $existingRdv $this->getDoctrine()
  2725.             ->getRepository(Rdv::class)
  2726.             ->findOneBy([
  2727.                 'date' => $date,
  2728.                 'id_audio' => $audio,
  2729.                 'id_centre' => $rdv->getIdCentre() ?? null,
  2730.                 'id_lieu' => $rdv->getIdLieu()   ?? null,
  2731.             ]);
  2732.         if ($existingRdv) {
  2733.             return new Response(json_encode([
  2734.                 'message' => 'Un rendez-vous est déjà pris pour cette date et ce créneau.',
  2735.                 'status' => 400,
  2736.             ]), 400);
  2737.         }
  2738.         $rdv->setDate($date);
  2739.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  2740.         /** @var EtatRdv */
  2741.         $etat $this->getDoctrine()
  2742.             ->getRepository(EtatRdv::class)
  2743.             ->findOneBy(['id' => $data["etat_id"]]);
  2744.         if ($etat == null) {
  2745.             return new Response(json_encode(([
  2746.                 'message' => 'Error, no etat found at this id',
  2747.                 'path' => 'src/Controller/RdvController.php',
  2748.                 "status" => 400,
  2749.             ])), 400);
  2750.         }
  2751.         $rdv->setIdEtat($etat);
  2752.         $rdv->setIdMotif($motif);
  2753.         $rdv->setIsAbsence(0);
  2754.         $rdv->setCacher(0);
  2755.         if ($remplacant_id != -1) {
  2756.             $remplacant $this->getDoctrine()
  2757.                 ->getRepository(Remplacant::class)
  2758.                 ->find($remplacant_id);
  2759.             $rdv->setRemplacant($remplacant);
  2760.         }
  2761.         $entityManager $this->getDoctrine()->getManager();
  2762.         $entityManager->persist($rdv);
  2763.         $entityManager->flush();
  2764.         /// SMSEMAIL A décommenter pour autoriser l'envoi de sms / email à la création de rdv par l'audio / le client SMSEMAIL ///
  2765.         $date $rdv->getDate();
  2766.         $smsDate $date->format('d-m-Y H:i');
  2767.         $locale 'fr_FR';
  2768.         $formatter = new IntlDateFormatter(
  2769.             $locale,
  2770.             IntlDateFormatter::FULL,
  2771.             IntlDateFormatter::SHORT,
  2772.             null,
  2773.             IntlDateFormatter::GREGORIAN,
  2774.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  2775.         );
  2776.         $smsDateLongFormat $formatter->format($date);
  2777.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  2778.         $client->setIdCentre($rdv->getIdCentre());
  2779.         $client->setIdAudio($rdv->getIdAudio());
  2780.         $entityManager->persist($client);
  2781.         $entityManager->flush();
  2782.         // client notif mail Sms
  2783.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  2784.         $frenchDate ucfirst($frenchDate);
  2785.         $responses = [
  2786.             'rangeAge' => isset($data['rangeAge']) ? $data['rangeAge'] : null,
  2787.             'situations' => (isset($data['situations']) && !empty($data['situations'])) ? implode(", "$data['situations']) : null,
  2788.             'equipeAppareil' => isset($data['equipe']) ? $data['equipe'] : null,
  2789.             'durationEquipe' => isset($data['durationEquipe']) ? $data['durationEquipe'] : null,
  2790.             'bilanAuditif' => isset($data['bilanAuditif']) ? $data['bilanAuditif'] : null,
  2791.             'ordonance' => isset($data['ordonnance']) ? $data['ordonnance'] : null,
  2792.             'dateOrdonance' => isset($data['dateOrdonance']) ? $data['dateOrdonance'] : null,
  2793.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  2794.         ];
  2795.         $paramsSourceLead = [
  2796.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  2797.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  2798.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  2799.         ];
  2800.         $params = array(
  2801.             "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  2802.             "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  2803.             "date" => $smsDateLongFormat,
  2804.             "RdvDate" => $smsDateLongFormat,
  2805.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  2806.             "centerName" => $rdv->getIdCentre()->getName(),
  2807.             "prenom" => $client->getName(),
  2808.             "centerAddress" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  2809.             "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  2810.             'motif' => $rdv->getIdMotif()->getTitre(),
  2811.             "centerCity" => $rdv->getIdCentre()->getCity(),
  2812.             "audioName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  2813.             'titre' => "Votre rendez-vous est validé le " substr($smsDate010) . " à "  substr($smsDate1115),
  2814.             "position" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  2815.             "address" => $rdv->getIdCentre()->getAddress(),
  2816.             "postal" => $rdv->getIdCentre()->getPostale(),
  2817.             "city" => $rdv->getIdCentre()->getCity(),
  2818.             "clientEmail" => $client->getMail(),
  2819.             "clientPassword" => isset($data["passwordGenerated"]) ? $data["passwordGenerated"] : null,
  2820.             "clientAddress" => $client->getAddress(),
  2821.             "clientPostal" => $client->getPostal(),
  2822.             "clientCity" => $client->getCity(),
  2823.             "audioName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  2824.             "frenchDate" => $frenchDate,
  2825.             "heure" => substr($smsDate1115),
  2826.             "centerName" => $rdv->getIdCentre()->getName(),
  2827.             "audioMail" => $rdv->getIdAudio()->getMail(),
  2828.             "modifUrl" => "{$_ENV['BASE_client']}mes-rendez-vous",
  2829.         );
  2830.         $paramsPatient $params;
  2831.         $isNew false;
  2832.         if (isset($data["isLead"]) && isset($data["passwordGenerated"]) != null) {
  2833.             $subject "✅Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  2834.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject189);
  2835.             $isNew true;
  2836.         } else {
  2837.             $subject "Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  2838.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject181);
  2839.         }
  2840.         $sms "Votre RDV est validé le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'imprévu contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  2841.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  2842.         // audio Notif mail SMS
  2843.         $birthday $rdv->getIdClient()->getBirthdate();
  2844.         $params = array(
  2845.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  2846.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  2847.             "date" => substr($smsDate010),
  2848.             "heure" => substr($smsDate1115),
  2849.             "mail" => $client->getMail(),
  2850.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  2851.             'telClient' => $client->getPhone(),
  2852.             'phone' => $client->getPhone(),
  2853.             'clientCivilite' => $client->getCivilite(),
  2854.             'clientNom' => $client->getLastname(),
  2855.             'clientPrenom' => $client->getName(),
  2856.             'clientPostal' => $client->getPostal(),
  2857.             'clientMail' => $client->getMail(),
  2858.             'clientPhone' => $client->getPhone(),
  2859.             'motif' => $rdv->getIdMotif()->getTitre(),
  2860.             'birthdate' => $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
  2861.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  2862.             'centerName' => $rdv->getIdCentre()->getName(),
  2863.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  2864.             'centerCity' => $rdv->getIdCentre()->getCity(),
  2865.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  2866.             'idPatient' => $client->getId(),
  2867.             'proUrl' => "{$_ENV['BASE_logiciel']}",
  2868.             'frenchDate' => $frenchDate,
  2869.             'responses' => $responses,
  2870.         );
  2871.         $templateEmail 182;
  2872.         if (!empty($data['canMove'])) {
  2873.             $templateEmail 197;
  2874.         }
  2875.         $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  2876.         $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  2877.         if ($rdv->getIdAudio()->getConfirmRdvMail()) {
  2878.             $subject "✅Nouveau Rendez-vous My Audio le " $frenchDate " à " substr($smsDate1115);
  2879.             $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject$templateEmail);
  2880.         }
  2881.         if ($rdv->getIdAudio()->getConfirmRdvSms()) {
  2882.             $sms "Vous avez un nouveau RDV le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'aléas contactez votre patient " $client->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  2883.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  2884.         }
  2885.         // send notif to admin
  2886.         $paramsAdmin = array(
  2887.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  2888.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  2889.             "RdvDate" => substr($smsDate010),
  2890.             "heure" => substr($smsDate1115),
  2891.             "clientMail" => $client->getMail(),
  2892.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  2893.             'telClient' => $client->getPhone(),
  2894.             'clientNom' => $client->getLastname(),
  2895.             'clientPrenom' => $client->getName(),
  2896.             'clientCivilite' => $client->getCivilite(),
  2897.             'clientPostal' => $client->getPostal(),
  2898.             'clientPhone' => $client->getPhone(),
  2899.             'motif' => $rdv->getIdMotif()->getTitre(),
  2900.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  2901.             'centerName' => $rdv->getIdCentre()->getName(),
  2902.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  2903.             'centerCity' => $rdv->getIdCentre()->getCity(),
  2904.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  2905.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  2906.             'date' => substr($smsDate010),
  2907.             'urlApi' => "{$_ENV['BASE_API']}",
  2908.             'clientId' => $client->getId(),
  2909.             'centerId' => $rdv->getIdCentre()->getId(),
  2910.             'frenchDate' => $frenchDate,
  2911.             'responses' => $responses,
  2912.             'paramsSourceLead' => $paramsSourceLead
  2913.         );
  2914.         $subject "Nouveau RDV MA | RR - " $rdv->getIdCentre()->getName();
  2915.         $templateEmail 183;
  2916.         if (!empty($data['canMove'])) {
  2917.             $templateEmail 190;
  2918.         }
  2919.         if (!isset($data["isLead"])) {
  2920.             $publicFunction->sendEmail($paramsAdmin"lead.myaudio@gmail.com""my audio"$subject$templateEmail);
  2921.         }
  2922.         //$publicFunction->sendEmail($paramsAdmin,"testpation1254@yopmail.com","my audio", 'Nouveau RDV à My Audio Pro', $templateEmail);
  2923.         $publicFunction->sendEmail($paramsAdmin"contact@myaudio.fr""my audio"$subject$templateEmail);
  2924.         $publicFunction->sendEmail($paramsAdmin"lead.myaudio@gmail.com""my audio"$subject$templateEmail);
  2925.         // google calendar post
  2926.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  2927.             ->findBy(array('audio' => $audio->getId()));
  2928.         $data['rdv'] = $rdv->getId();
  2929.         if (isset($data['clientRdvLp']) && !empty($data['clientRdvLp'])) {
  2930.             $rdvLead $this->entityManager->getRepository(LeadRdv::class)->find($data['clientRdvLp']);
  2931.             if ($rdvLead) {
  2932.                 $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'rdv_valider']);
  2933.                 if ($leadStatus) {
  2934.                     $rdvLead->setLeadStatus($leadStatus);
  2935.                     $rdvLead->setRdv($rdv);
  2936.                     $this->entityManager->flush();
  2937.                 }
  2938.             }
  2939.         }
  2940.         foreach ($synchronisations as $synchronisation) {
  2941.             if (!$synchronisation->getIsDeleted()) {
  2942.                 $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  2943.                 $googleCalendar->createEvent($synchronisation$data);
  2944.             }
  2945.         }
  2946.         if (isset($data["isMyaudio"]) || isset($data["isRdvLead"]) || isset($data["isRdvRapide"])) {
  2947.             try {
  2948.                 $Callservice->handleCallCenterAfterRdv(
  2949.                     $rdv
  2950.                 );
  2951.                 $rdv->setIsNotificationRdvCallSent(1);
  2952.                 $this->entityManager->flush();
  2953.             } catch (\Exception $e) {
  2954.                 $this->logger->error("Erreur lors de l'appel de notification pour le RDV #{$rdv->getId()}: " $e->getMessage());
  2955.             }
  2956.         }
  2957.         return new Response(json_encode(([
  2958.             "id" => $rdv->getId(),
  2959.             "motif_id" => $rdv->getIdMotif()->getId(),
  2960.             "audio_id" => $rdv->getIdAudio()->getId(),
  2961.             "remplacant_id" => $remplacant_id == -null $remplacant_id,
  2962.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  2963.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  2964.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2965.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2966.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2967.             "testclient" => $rdv->getTestClient() ? [
  2968.                 "result" => $rdv->getTestClient()->getResultTonal(),
  2969.                 "date" => $rdv->getTestClient()->getDate(),
  2970.                 "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  2971.             ] : null,
  2972.             "duration" => $audioMotif->getDuration(),
  2973.             "consigne" => $audioMotif->getConsigne(),
  2974.             "etat_id" => $rdv->getIdEtat()->getId(),
  2975.             "date" => $rdv->getDate(),
  2976.             "comment" => $rdv->getComment(),
  2977.             "centerName" => $rdv->getIdCentre()->getName(),
  2978.             "review" => $rdv->getReview(),
  2979.             "note" => $rdv->getNote(),
  2980.             "status" => 200,
  2981.             "paramsPatient" => $paramsPatient,
  2982.             "isNew" => $isNew,
  2983.         ])));
  2984.     }
  2985.     /**
  2986.      * @Route("/rdv/{id}/trusteduser", name="contactTrustedUser", methods={"POST"})
  2987.      */
  2988.     public function contactTrustedUser(Request $requestPublicFunction $publicFunction)
  2989.     {
  2990.         $pastDate $rdv->getDate();
  2991.         $data json_decode($request->getContent(), true);
  2992.         $entityManager $this->getDoctrine()->getManager();
  2993.         if (!isset($data["token"])) {
  2994.             return new Response(json_encode([
  2995.                 "message" => "Pas de token n'a été spécifié",
  2996.                 "status" => 401,
  2997.             ]), 401);
  2998.         }
  2999.         /** @var Token */
  3000.         $token $this->getDoctrine()
  3001.             ->getRepository(Token::class)
  3002.             ->findOneBy(['token' => $data["token"]]);
  3003.         if (!$token) {
  3004.             return new Response(json_encode([
  3005.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  3006.                 "status" => 404,
  3007.             ]), 404);
  3008.         }
  3009.         // get token age
  3010.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  3011.         // if the token if older than 7 days
  3012.         if ($dateDiff->7) {
  3013.             $entityManager->remove($token);
  3014.             $entityManager->flush();
  3015.             return $this->json([
  3016.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  3017.                 'path' => 'src/Controller/ClientController.php',
  3018.                 "status" => 401,
  3019.             ], 401);
  3020.         }
  3021.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  3022.             return new Response(json_encode([
  3023.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  3024.                 "status" => 404,
  3025.             ]), 404);
  3026.         }
  3027.         if (isset($data["date"])) {
  3028.             // remove the taken schedule by rdv to make sure there is no overlap
  3029.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  3030.             $audioMotif $this->getDoctrine()
  3031.                 ->getRepository(AudioMotif::class)
  3032.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  3033.             if ($audioMotif == null) {
  3034.                 return new Response(json_encode(([
  3035.                     'message' => 'Error, no motif of this id found at this audio',
  3036.                     'path' => 'src/Controller/RdvController.php',
  3037.                     "status" => 400,
  3038.                 ])), 400);
  3039.             }
  3040.             if ($rdv->getIdAudio()->getIsIndie()) {
  3041.                 if ($rdv->getIdCentre()) {
  3042.                     // regular centre audio indie
  3043.                     /** @var AudioCentre */
  3044.                     $liaison $this->getDoctrine()
  3045.                         ->getRepository(AudioCentre::class)
  3046.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  3047.                     if ($liaison == null) {
  3048.                         return new Response(json_encode(([
  3049.                             'message' => 'Error, audio isnt part of the centre',
  3050.                             'path' => 'src/Controller/RdvController.php',
  3051.                             "status" => 400,
  3052.                         ])), 400);
  3053.                     }
  3054.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  3055.                         return new Response(json_encode(([
  3056.                             'message' => 'Error, no horaire found for this audio',
  3057.                             'path' => 'src/Controller/RdvController.php',
  3058.                             "status" => 400,
  3059.                         ])), 400);
  3060.                     }
  3061.                     // if ($publicFunction->calculScheduleFitDate($liaison->getHoraire(), $rdv->getIdAudio(), $date, $audioMotif->getDuration(), $rdv->getIdCentre()) == false) {
  3062.                     //     return new Response(json_encode(([
  3063.                     //         'message' => 'Error, no timestamp found at this time',
  3064.                     //         'path' => 'src/Controller/RdvController.php',
  3065.                     //         "status" => 400,
  3066.                     //     ])),400);
  3067.                     // }
  3068.                 } else {
  3069.                     // lieu audio indie
  3070.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  3071.                         return new Response(json_encode(([
  3072.                             'message' => 'Error, no horaire found for this audio',
  3073.                             'path' => 'src/Controller/RdvController.php',
  3074.                             "status" => 400,
  3075.                         ])), 400);
  3076.                     }
  3077.                     // if ($publicFunction->calculScheduleFitDate($rdv->getIdLieu()->getHoraire(), $rdv->getIdAudio(), $date, $audioMotif->getDuration(), null, $rdv->getIdLieu()) == false) {
  3078.                     //     return new Response(json_encode(([
  3079.                     //         'message' => 'Error, no timestamp found at this time',
  3080.                     //         'path' => 'src/Controller/RdvController.php',
  3081.                     //         "status" => 400,
  3082.                     //     ])),400);
  3083.                     // }
  3084.                 }
  3085.             } else {
  3086.                 // regular centre
  3087.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  3088.                     return new Response(json_encode(([
  3089.                         'message' => 'Error, no horaire found for this audio',
  3090.                         'path' => 'src/Controller/RdvController.php',
  3091.                         "status" => 400,
  3092.                     ])), 400);
  3093.                 }
  3094.                 // if ($publicFunction->calculScheduleFitDate($rdv->getIdCentre()->getHoraire(), $rdv->getIdAudio(), $date, $audioMotif->getDuration(), $rdv->getIdCentre()) == false) {
  3095.                 //     return new Response(json_encode(([
  3096.                 //         'message' => 'Error, no timestamp found at this time',
  3097.                 //         'path' => 'src/Controller/RdvController.php',
  3098.                 //         "status" => 400,
  3099.                 //     ])),400);
  3100.                 // }
  3101.             }
  3102.             $rdv->setDate($date);
  3103.         }
  3104.         $date $rdv->getDate();
  3105.         $smsDate $date->format('d-m-Y H:i');
  3106.         $oldDate $pastDate->format('d-m-Y H:i');
  3107.         $publicFunction->sendEmail("MyAudio <noreply@myaudio.fr>"$rdv->getIdClient()->getIdPersonneConfiance()->getMail(), "My Audio: Confirmation RDV""<p>Le RDV de votre proche est validé le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'aléa contactez le centre " $rdv->getIdCentre()->getPhone() . " pour modifier sa consultation.</p>");
  3108.         return new Response(json_encode(([
  3109.             "id" => $rdv->getId(),
  3110.             "status" => 200,
  3111.         ])));
  3112.     }
  3113.     /**
  3114.      * @Route("/rdv/{id}", name="editRdvByID", methods={"PUT"})
  3115.      */
  3116.     public function editRdvByID(PublicFunction $publicFunctionRdv $rdvRequest $requestGoogleCalendarService $googleCalendarRdvSmsService $rdvSms): Response
  3117.     {
  3118.         $pastDate $rdv->getDate();
  3119.         $pastDuration $rdv->getDuration();
  3120.         $data json_decode($request->getContent(), true);
  3121.         $entityManager $this->getDoctrine()->getManager();
  3122.         if (!isset($data["token"])) {
  3123.             return new Response(json_encode([
  3124.                 "message" => "Pas de token n'a été spécifié",
  3125.                 "status" => 401,
  3126.             ]), 401);
  3127.         }
  3128.         /** @var Token */
  3129.         $token $this->getDoctrine()
  3130.             ->getRepository(Token::class)
  3131.             ->findOneBy(['token' => $data["token"]]);
  3132.         if (!$token) {
  3133.             return new Response(json_encode([
  3134.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  3135.                 "status" => 404,
  3136.             ]), 404);
  3137.         }
  3138.         // get token age
  3139.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  3140.         // if the token if older than 7 days
  3141.         if ($dateDiff->7) {
  3142.             $entityManager->remove($token);
  3143.             $entityManager->flush();
  3144.             return $this->json([
  3145.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  3146.                 'path' => 'src/Controller/ClientController.php',
  3147.                 "status" => 401,
  3148.             ], 401);
  3149.         }
  3150.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  3151.             return new Response(json_encode([
  3152.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  3153.                 "status" => 404,
  3154.             ]), 404);
  3155.         }
  3156.         if (isset($data["etat_id"])) {
  3157.             $etat $this->getDoctrine()
  3158.                 ->getRepository(EtatRdv::class)
  3159.                 ->findOneBy(['id' => $data["etat_id"]]);
  3160.             if ($etat == null) {
  3161.                 return new Response(json_encode(([
  3162.                     'message' => 'Error, no etat found at this id',
  3163.                     'path' => 'src/Controller/TrustedUserController.php',
  3164.                     "status" => 400,
  3165.                 ])), 400);
  3166.             }
  3167.             $rdv->setIdEtat($etat);
  3168.         }
  3169.         if (isset($data["audio_id"])) {
  3170.             $audio $this->getDoctrine()
  3171.                 ->getRepository(Audio::class)
  3172.                 ->findOneBy(['id' => $data["audio_id"]]);
  3173.             if ($audio == null) {
  3174.                 return new Response(json_encode(([
  3175.                     'message' => 'Error, no audio found at this id',
  3176.                     'path' => 'src/Controller/TrustedUserController.php',
  3177.                     "status" => 400,
  3178.                 ])), 400);
  3179.             }
  3180.             $rdv->setIdAudio($audio);
  3181.         }
  3182.         if (isset($data["motif_id"])) {
  3183.             $motif $this->getDoctrine()
  3184.                 ->getRepository(Motif::class)
  3185.                 ->find($data["motif_id"]);
  3186.             if ($motif == null) {
  3187.                 return new Response(json_encode(([
  3188.                     'message' => 'Error, no motif found at this id',
  3189.                     'path' => 'src/Controller/TrustedUserController.php',
  3190.                     "status" => 400,
  3191.                 ])), 400);
  3192.             }
  3193.             $rdv->setIdMotif($motif);
  3194.         }
  3195.         if (isset($data["client_id"])) {
  3196.             $client $this->getDoctrine()
  3197.                 ->getRepository(Client::class)
  3198.                 ->findOneBy(['id' => $data["client_id"]]);
  3199.             if ($client == null) {
  3200.                 return new Response(json_encode(([
  3201.                     'message' => 'Error, no client found at this id',
  3202.                     'path' => 'src/Controller/TrustedUserController.php',
  3203.                     "status" => 400,
  3204.                 ])), 400);
  3205.             }
  3206.             $rdv->setIdClient($client);
  3207.         }
  3208.         // set client status
  3209.         if (isset($data["client_status_id"])) {
  3210.             $status $this->getDoctrine()
  3211.                 ->getRepository(ClientStatus::class)
  3212.                 ->findOneBy(['id' => $data["client_status_id"]]);
  3213.             if ($status == null) {
  3214.                 return new Response(json_encode(([
  3215.                     'message' => 'Error, no status found at this id',
  3216.                     'path' => 'src/Controller/TrustedUserController.php',
  3217.                     "status" => 400,
  3218.                 ])), 400);
  3219.             }
  3220.             $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  3221.             $client->setClientStatus($status);
  3222.             $client->setLastUpdateStatus(new \DateTimeImmutable);
  3223.         }
  3224.         if (isset($data["date"])) {
  3225.             $submittedDate $data['date'] ?? null;
  3226.             $newDate \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  3227.             $currentDate $rdv->getDate();
  3228.             if (!$currentDate || $currentDate->format('d/m/Y H:i') !== $newDate->format('d/m/Y H:i')) {
  3229.                 $rdv->setDateOldRdv($currentDate);
  3230.             }
  3231.             // remove the taken schedule by rdv to make sure there is no overlap
  3232.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  3233.             $dateInput \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  3234.             $audioMotif $this->getDoctrine()
  3235.                 ->getRepository(AudioMotif::class)
  3236.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  3237.             if ($audioMotif == null) {
  3238.                 return new Response(json_encode(([
  3239.                     'message' => 'Error, no motif of this id found at this audio',
  3240.                     'path' => 'src/Controller/RdvController.php',
  3241.                     "status" => 400,
  3242.                 ])), 400);
  3243.             }
  3244.             if ($rdv->getIdAudio()->getIsIndie()) {
  3245.                 if ($rdv->getIdCentre()) {
  3246.                     // regular centre audio indie
  3247.                     /** @var AudioCentre */
  3248.                     $liaison $this->getDoctrine()
  3249.                         ->getRepository(AudioCentre::class)
  3250.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  3251.                     if ($liaison == null) {
  3252.                         return new Response(json_encode(([
  3253.                             'message' => 'Error, audio isnt part of the centre',
  3254.                             'path' => 'src/Controller/RdvController.php',
  3255.                             "status" => 400,
  3256.                         ])), 400);
  3257.                     }
  3258.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  3259.                         return new Response(json_encode(([
  3260.                             'message' => 'Error, no horaire found for this audio',
  3261.                             'path' => 'src/Controller/RdvController.php',
  3262.                             "status" => 400,
  3263.                         ])), 400);
  3264.                     }
  3265.                 } else {
  3266.                     // lieu audio indie
  3267.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  3268.                         return new Response(json_encode(([
  3269.                             'message' => 'Error, no horaire found for this audio',
  3270.                             'path' => 'src/Controller/RdvController.php',
  3271.                             "status" => 400,
  3272.                         ])), 400);
  3273.                     }
  3274.                 }
  3275.             } else {
  3276.                 // regular centre
  3277.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  3278.                     return new Response(json_encode(([
  3279.                         'message' => 'Error, no horaire found for this audio',
  3280.                         'path' => 'src/Controller/RdvController.php',
  3281.                         "status" => 400,
  3282.                     ])), 400);
  3283.                 }
  3284.             }
  3285.             $rdv->setDate($date);
  3286.         }
  3287.         if (isset($data["comment"]) && $token->getIdClient()) {
  3288.             $rdv->setComment($data["comment"]);
  3289.         }
  3290.         if (isset($data["review"]) && $token->getIdClient()) {
  3291.             $rdv->setReview($data["review"]);
  3292.         }
  3293.         if (isset($data["note"])) {
  3294.             $rdv->setNote($data["note"]);
  3295.         }
  3296.         if (isset($data["duree"])) {
  3297.             $rdv->setDuration($data["duree"]);
  3298.         }
  3299.         ////// SMSEMAIL A décommenter pour activer l'envoi de SMS + MAIL pour modification annulation de RDV, coté audio / client SMSEMAIL ////
  3300.         $date $rdv->getDate();
  3301.         $smsDate $date->format('d-m-Y H:i');
  3302.         $oldDate $pastDate->format('d-m-Y H:i');
  3303.         $locale 'fr_FR';
  3304.         $formatter = new IntlDateFormatter(
  3305.             $locale,
  3306.             IntlDateFormatter::FULL,
  3307.             IntlDateFormatter::SHORT,
  3308.             null,
  3309.             IntlDateFormatter::GREGORIAN,
  3310.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  3311.         );
  3312.         $smsDateLongFormat $formatter->format($date);
  3313.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  3314.         $frenchDate ucfirst($frenchDate);
  3315.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  3316.         // notif client
  3317.         if ($rdv->getIdEtat()->getId() != 2) {
  3318.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  3319.                 if ($data["sms"]) {
  3320.                     $params = array(
  3321.                         "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  3322.                         "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  3323.                         "date" => $smsDateLongFormat,
  3324.                         "heure" => substr($smsDate1115),
  3325.                         "motif" => $rdv->getIdMotif()->getTitre(),
  3326.                         "centerName" => $rdv->getIdCentre()->getName(),
  3327.                         "centerAddress" => $rdv->getIdCentre()->getAddress(),
  3328.                         "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  3329.                         "audioMail" => $rdv->getIdAudio()->getMail(),
  3330.                         "centerPhone" => $rdv->getIdCentre()->getPhone(),
  3331.                         "centerCity" => $rdv->getIdCentre()->getCity(),
  3332.                         "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  3333.                         'titre' => 'Votre rendez-vous est modifié pour le',
  3334.                         'frenchDate' => $frenchDate,
  3335.                     );
  3336.                     $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  3337.                     $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  3338.                     $sms "Votre RDV est modifié pour le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'imprévu contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  3339.                     $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  3340.                 }
  3341.             }
  3342.         }
  3343.         //     //// == suppression
  3344.         else if ($rdv->getIdEtat()->getId() == 2) {
  3345.             // delete google agenda event
  3346.             $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  3347.                 ->findBy(array('rdv' => $rdv));
  3348.             foreach ($rdvEvents as $rdvEvent) {
  3349.                 $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  3350.                 if ($googleCalendar) {
  3351.                     $googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
  3352.                     $entityManager->remove($rdvEvent);
  3353.                     $entityManager->flush();
  3354.                 }
  3355.             }
  3356.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  3357.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {                   
  3358.             $params = array(
  3359.                 "date" => substr($smsDate010),
  3360.                 "lien" => "{$_ENV['BASE_client']}search",
  3361.                 "heure" => substr($smsDate1115),
  3362.                 "patientName" => $client->getLastName(),
  3363.                 'titre' => 'Votre rendez-vous est annulé :',
  3364.                 'centerName' => $rdv->getIdCentre()->getName(),
  3365.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  3366.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  3367.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  3368.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  3369.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  3370.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  3371.                 'motif' => $rdv->getIdMotif()->getTitre(),
  3372.             );
  3373.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  3374.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  3375.             if ($data["sms"]) {
  3376.                 $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  3377.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  3378.             }
  3379.             //}
  3380.         }
  3381.         // set center
  3382.         if (isset($data["centre_id"])) {
  3383.             $entityManager $this->getDoctrine()->getManager();
  3384.             $centreId $data["centre_id"];
  3385.             $centre $entityManager->getRepository(Centre::class)->find($centreId);
  3386.             if (!$centre) {
  3387.                 return $this->json([
  3388.                     'message' => 'Error, no Centre found with this ID',
  3389.                     'path' => 'src/Controller/YourController.php',
  3390.                 ]);
  3391.             }
  3392.             $rdv->setIdCentre($centre);
  3393.         }
  3394.         $rdv->setGoogleAgendaImported(false);
  3395.         //notif Audio
  3396.         if ($rdv->getIdEtat()->getId() != 2) {
  3397.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  3398.                 if ($data["sms"]) {
  3399.                     $params = array(
  3400.                         "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  3401.                         "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  3402.                         "date" => substr($smsDate010),
  3403.                         "frenchDate" => $frenchDate,
  3404.                         "heure" => substr($smsDate1115),
  3405.                         'motif' => $rdv->getIdMotif()->getTitre(),
  3406.                         'clientPhone' => $client->getPhone(),
  3407.                         'clientNom' => $client->getLastname(),
  3408.                         'clientPrenom' => $client->getName(),
  3409.                         'clientCivilite' => $client->getCivilite(),
  3410.                         'clientPostal' => $client->getPostal(),
  3411.                         'clientMail' => $client->getMail(),
  3412.                         'centerName' => $rdv->getIdCentre()->getName(),
  3413.                         'centerPostal' => $rdv->getIdCentre()->getPostale(),
  3414.                         'centerCity' => $rdv->getIdCentre()->getCity(),
  3415.                         'centerAddress' => $rdv->getIdCentre()->getAddress(),
  3416.                         'idPatient' => $client->getId(),
  3417.                         'proUrl' => "{$_ENV['BASE_logiciel']}",
  3418.                         'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  3419.                         'titre' => 'Votre rendez-vous est modifié pour le :'
  3420.                     );
  3421.                     $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  3422.                     $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  3423.                     if ($rdv->getIdAudio()->getModifRdvMail()) {
  3424.                         $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  3425.                         $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  3426.                     }
  3427.                     if ($rdv->getIdAudio()->getModifRdvSms()) {
  3428.                         // we ignore the sms send to the audio for the case he modify the rdv (so lets commented)
  3429.                         $sms "Votre RDV est modifié pour le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'imprévu contacter votre patient " $client->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  3430.                         //$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $phoneAudio);
  3431.                     }
  3432.                 }
  3433.             }
  3434.         } else if ($rdv->getIdEtat()->getId() == 2) {
  3435.             if ($data["sms"]) {
  3436.                 $params = array(
  3437.                     "date" => substr($smsDate010),
  3438.                     "lien" => "{$_ENV['BASE_client']}search",
  3439.                     "heure" => substr($smsDate1115),
  3440.                     "patientName" => $client->getLastName(),
  3441.                     'titre' => 'Votre rendez-vous est annulé :',
  3442.                     'centerName' => $rdv->getIdCentre()->getName(),
  3443.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  3444.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  3445.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  3446.                     'centerPhone' => $rdv->getIdCentre()->getPhone(),
  3447.                     'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  3448.                     'audioMail' => $rdv->getIdAudio()->getMail(),
  3449.                     'motif' => $rdv->getIdMotif()->getTitre(),
  3450.                 );
  3451.                 $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  3452.                 $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  3453.                 if ($rdv->getIdAudio()->getModifRdvMail()) {
  3454.                     $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  3455.                     $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject188);
  3456.                 }
  3457.                 if ($rdv->getIdAudio()->getModifRdvSms()) {
  3458.                     $sms "Votre RDV du " substr($oldDate010) . " à " substr($oldDate1115) . "a été annulé, vous pouvez contacter votre patient pour fixer un autre RDV:" $client->getPhone() . " pour fixer un autre RDV.\nNe pas répondre.";
  3459.                    // $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $phoneAudio);
  3460.                 }
  3461.             }
  3462.         }
  3463.         $entityManager->flush();
  3464.         if ((isset($data["prenom_patient"]))  || (isset($data["nom_patient"]))  || (isset($data["birthday_patient"]))  || (isset($data["mail_patient"]))  || (isset($data["portable_patient"]))  || (isset($data["fixe_patient"]))) {
  3465.             if (is_null($rdv->getIdClientTemp())) {
  3466.                 $clientRDV $this->getDoctrine()
  3467.                     ->getRepository(Client::class)
  3468.                     ->findOneBy(['id' => $rdv->getIdClient()->getId()]);
  3469.                 $clientRDV->setName($data["prenom_patient"]);
  3470.                 $clientRDV->setLastname($data["nom_patient"]);
  3471.                 $clientRDV->setMail($data["mail_patient"]);
  3472.                 $clientRDV->setPhone($data["portable_patient"]);
  3473.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  3474.             } else {
  3475.                 $clientRDV $this->getDoctrine()
  3476.                     ->getRepository(ClientTemp::class)
  3477.                     ->findOneBy(['id' => $rdv->getIdClientTemp()->getId()]);
  3478.                 $clientRDV->setName($data["prenom_patient"]);
  3479.                 $clientRDV->setLastname($data["nom_patient"]);
  3480.                 $clientRDV->setMail($data["mail_patient"]);
  3481.                 $clientRDV->setPhone($data["portable_patient"]);
  3482.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  3483.             }
  3484.             if (!empty($data["birthday_patient"])) {
  3485.                 $birth \DateTime::createFromFormat("Y-m-d"$data["birthday_patient"]);
  3486.                 $clientRDV->setBirthdate($birth);
  3487.             }
  3488.             $entityManager->flush();
  3489.         }
  3490.         if (is_null($rdv->getIdClient())) {
  3491.             $prenom_patient $rdv->getIdClientTemp()->getName();
  3492.             $nom_patient $rdv->getIdClientTemp()->getLastname();
  3493.             $mail_patient $rdv->getIdClientTemp()->getMail();
  3494.             $portable_patient $rdv->getIdClientTemp()->getPhone();
  3495.             $fixe_patient $rdv->getIdClientTemp()->getPhoneFixe();
  3496.             $birthday $rdv->getIdClientTemp()->getBirthdate();
  3497.         } elseif (is_null($rdv->getIdClientTemp())) {
  3498.             $prenom_patient =  $rdv->getIdClient()->getName();
  3499.             $nom_patient $rdv->getIdClient()->getLastname();
  3500.             $mail_patient $rdv->getIdClient()->getMail();
  3501.             $portable_patient $rdv->getIdClient()->getPhone();
  3502.             $fixe_patient $rdv->getIdClient()->getPhoneFixe();
  3503.             $birthday $rdv->getIdClient()->getBirthdate();
  3504.         } else {
  3505.             $prenom_patient "";
  3506.             $nom_patient "";
  3507.             $mail_patient "";
  3508.             $portable_patient "";
  3509.             $fixe_patient "";
  3510.             $birthday "";
  3511.         }
  3512.         /* generate sms notif on update */
  3513.         // update sms notification     
  3514.         $rdvSms->updateRdvSms($rdv);
  3515.         // google calendar update
  3516.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  3517.             ->findBy(array('audio' => $rdv->getIdAudio()));
  3518.         $data['rdv'] = $rdv->getId();
  3519.         if ($rdv->getIdClient() !== null) {
  3520.             $data["client_id"] = $rdv->getIdClient()->getId();
  3521.         }
  3522.         if ($rdv->getIdClientTemp() !== null) {
  3523.             $data["client_id_temp"] = $rdv->getIdClientTemp()->getId();
  3524.         }
  3525.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  3526.             ->findBy(array('rdv' => $rdv));
  3527.         foreach ($rdvEvents as $rdvEvent) {
  3528.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  3529.             $googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  3530.         }
  3531.         $synchronisationCosium $this->getDoctrine()->getRepository(SynchronisationCosium::class)->findOneBy(["audio" => $rdv->getIdAudio()->getId()]);
  3532.         $cosiumCenter $this->getDoctrine()->getRepository(CosiumCenter::class)->findOneBy(["synchronisationCosium" => $synchronisationCosium"center" => $rdv->getIdCentre()]);
  3533.         if ($cosiumCenter) {
  3534.             $this->clientCosiumService->deleteRdv($synchronisationCosium$rdv);
  3535.             $this->clientCosiumService->createAgenda($synchronisationCosium$rdv$cosiumCenter);
  3536.         }
  3537.         return new Response(json_encode(([
  3538.             "id" => $rdv->getId(),
  3539.             "motif_id" => $rdv->getIdMotif()->getId(),
  3540.             "motif_libelle" => $rdv->getIdMotif()->getTitre(),
  3541.             "audio_id" => $rdv->getIdAudio()->getId(),
  3542.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  3543.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  3544.             "fullName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  3545.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  3546.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  3547.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  3548.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  3549.             "centre_name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : null,
  3550.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  3551.             "etat_id" => $rdv->getIdEtat()->getId(),
  3552.             "date" => $rdv->getDate(),
  3553.             "comment" => $rdv->getComment(),
  3554.             "note" => $rdv->getNote(),
  3555.             "review" => $rdv->getReview(),
  3556.             "clientEtatId" => $client->getClientStatus() ? $client->getClientStatus()->getId() : 0,
  3557.             "prenom_patient" => $prenom_patient,
  3558.             "nom_patient" => $nom_patient,
  3559.             "mail_patient" => $mail_patient,
  3560.             "portable_patient" => $portable_patient,
  3561.             "fixe_patient" => $fixe_patient,
  3562.             "birthday" => $birthday,
  3563.             "status" => 200,
  3564.         ])));
  3565.     }
  3566.     /**
  3567.      * @Route("/rdv-by-patient/{id}", name="editRdvByIDFromPatient", methods={"PUT"})
  3568.      */
  3569.     public function editRdvByIDFromPatient(PublicFunction $publicFunctionRdv $rdvRequest $request): Response
  3570.     {
  3571.         $pastDate $rdv->getDate();
  3572.         $pastDuration $rdv->getDuration();
  3573.         $data json_decode($request->getContent(), true);
  3574.         $entityManager $this->getDoctrine()->getManager();
  3575.         if (!isset($data["token"])) {
  3576.             return new Response(json_encode([
  3577.                 "message" => "Pas de token n'a été spécifié",
  3578.                 "status" => 401,
  3579.             ]), 401);
  3580.         }
  3581.         /** @var Token */
  3582.         $token $this->getDoctrine()
  3583.             ->getRepository(Token::class)
  3584.             ->findOneBy(['token' => $data["token"]]);
  3585.         if (!$token) {
  3586.             return new Response(json_encode([
  3587.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  3588.                 "status" => 404,
  3589.             ]), 404);
  3590.         }
  3591.         // get token age
  3592.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  3593.         // if the token if older than 7 days
  3594.         if ($dateDiff->7) {
  3595.             $entityManager->remove($token);
  3596.             $entityManager->flush();
  3597.             return $this->json([
  3598.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  3599.                 'path' => 'src/Controller/ClientController.php',
  3600.                 "status" => 401,
  3601.             ], 401);
  3602.         }
  3603.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  3604.             return new Response(json_encode([
  3605.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  3606.                 "status" => 404,
  3607.             ]), 404);
  3608.         }
  3609.         if (isset($data["etat_id"])) {
  3610.             $etat $this->getDoctrine()
  3611.                 ->getRepository(EtatRdv::class)
  3612.                 ->findOneBy(['id' => $data["etat_id"]]);
  3613.             if ($etat == null) {
  3614.                 return new Response(json_encode(([
  3615.                     'message' => 'Error, no etat found at this id',
  3616.                     'path' => 'src/Controller/TrustedUserController.php',
  3617.                     "status" => 400,
  3618.                 ])), 400);
  3619.             }
  3620.             $rdv->setIdEtat($etat);
  3621.         }
  3622.         if (isset($data["audio_id"])) {
  3623.             $audio $this->getDoctrine()
  3624.                 ->getRepository(Audio::class)
  3625.                 ->findOneBy(['id' => $data["audio_id"]]);
  3626.             if ($audio == null) {
  3627.                 return new Response(json_encode(([
  3628.                     'message' => 'Error, no audio found at this id',
  3629.                     'path' => 'src/Controller/TrustedUserController.php',
  3630.                     "status" => 400,
  3631.                 ])), 400);
  3632.             }
  3633.             $rdv->setIdAudio($audio);
  3634.         }
  3635.         if (isset($data["motif_id"])) {
  3636.             $motif $this->getDoctrine()
  3637.                 ->getRepository(Motif::class)
  3638.                 ->find($data["motif_id"]);
  3639.             if ($motif == null) {
  3640.                 return new Response(json_encode(([
  3641.                     'message' => 'Error, no motif found at this id',
  3642.                     'path' => 'src/Controller/TrustedUserController.php',
  3643.                     "status" => 400,
  3644.                 ])), 400);
  3645.             }
  3646.             $rdv->setIdMotif($motif);
  3647.         }
  3648.         if (isset($data["client_id"])) {
  3649.             $client $this->getDoctrine()
  3650.                 ->getRepository(Client::class)
  3651.                 ->findOneBy(['id' => $data["client_id"]]);
  3652.             if ($client == null) {
  3653.                 return new Response(json_encode(([
  3654.                     'message' => 'Error, no client found at this id',
  3655.                     'path' => 'src/Controller/TrustedUserController.php',
  3656.                     "status" => 400,
  3657.                 ])), 400);
  3658.             }
  3659.             $rdv->setIdClient($client);
  3660.         }
  3661.         if (isset($data["date"])) {
  3662.             // remove the taken schedule by rdv to make sure there is no overlap
  3663.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  3664.             $dateInput \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  3665.             $audioMotif $this->getDoctrine()
  3666.                 ->getRepository(AudioMotif::class)
  3667.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  3668.             if ($audioMotif == null) {
  3669.                 return new Response(json_encode(([
  3670.                     'message' => 'Error, no motif of this id found at this audio',
  3671.                     'path' => 'src/Controller/RdvController.php',
  3672.                     "status" => 400,
  3673.                 ])), 400);
  3674.             }
  3675.             if ($rdv->getIdAudio()->getIsIndie()) {
  3676.                 if ($rdv->getIdCentre()) {
  3677.                     // regular centre audio indie
  3678.                     /** @var AudioCentre */
  3679.                     $liaison $this->getDoctrine()
  3680.                         ->getRepository(AudioCentre::class)
  3681.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  3682.                     if ($liaison == null) {
  3683.                         return new Response(json_encode(([
  3684.                             'message' => 'Error, audio isnt part of the centre',
  3685.                             'path' => 'src/Controller/RdvController.php',
  3686.                             "status" => 400,
  3687.                         ])), 400);
  3688.                     }
  3689.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  3690.                         return new Response(json_encode(([
  3691.                             'message' => 'Error, no horaire found for this audio',
  3692.                             'path' => 'src/Controller/RdvController.php',
  3693.                             "status" => 400,
  3694.                         ])), 400);
  3695.                     }
  3696.                 } else {
  3697.                     // lieu audio indie
  3698.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  3699.                         return new Response(json_encode(([
  3700.                             'message' => 'Error, no horaire found for this audio',
  3701.                             'path' => 'src/Controller/RdvController.php',
  3702.                             "status" => 400,
  3703.                         ])), 400);
  3704.                     }
  3705.                 }
  3706.             } else {
  3707.                 // regular centre
  3708.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  3709.                     return new Response(json_encode(([
  3710.                         'message' => 'Error, no horaire found for this audio',
  3711.                         'path' => 'src/Controller/RdvController.php',
  3712.                         "status" => 400,
  3713.                     ])), 400);
  3714.                 }
  3715.             }
  3716.             $rdv->setDate($date);
  3717.         }
  3718.         if (isset($data["comment"]) && $token->getIdClient()) {
  3719.             $rdv->setComment($data["comment"]);
  3720.         }
  3721.         if (isset($data["review"]) && $token->getIdClient()) {
  3722.             $rdv->setReview($data["review"]);
  3723.         }
  3724.         if (isset($data["note"])) {
  3725.             $rdv->setNote($data["note"]);
  3726.         }
  3727.         if (isset($data["duree"])) {
  3728.             $rdv->setDuration($data["duree"]);
  3729.         }
  3730.         ////// SMSEMAIL A décommenter pour activer l'envoi de SMS + MAIL pour modification annulation de RDV, coté audio / client SMSEMAIL ////
  3731.         $date $rdv->getDate();
  3732.         $smsDate $date->format('d-m-Y H:i');
  3733.         $oldDate $pastDate->format('d-m-Y H:i');
  3734.         $locale 'fr_FR';
  3735.         $formatter = new IntlDateFormatter(
  3736.             $locale,
  3737.             IntlDateFormatter::FULL,
  3738.             IntlDateFormatter::SHORT,
  3739.             null,
  3740.             IntlDateFormatter::GREGORIAN,
  3741.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  3742.         );
  3743.         $smsDateLongFormat $formatter->format($date);
  3744.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  3745.         $frenchDate ucfirst($frenchDate);
  3746.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  3747.         // notif client
  3748.         if ($rdv->getIdEtat()->getId() != 2) {
  3749.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  3750.                 $params = array(
  3751.                     "lienModifier" => "{$_ENV['BASE_client']}mes-rendez-vous",
  3752.                     "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  3753.                     "date" => $smsDateLongFormat,
  3754.                     "heure" => substr($smsDate1115),
  3755.                     "motif" => $rdv->getIdMotif()->getTitre(),
  3756.                     "centerName" => $rdv->getIdCentre()->getName(),
  3757.                     "centerAddress" => $rdv->getIdCentre()->getAddress(),
  3758.                     "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  3759.                     "audioMail" => $rdv->getIdAudio()->getMail(),
  3760.                     "centerPhone" => $rdv->getIdCentre()->getPhone(),
  3761.                     "centerCity" => $rdv->getIdCentre()->getCity(),
  3762.                     "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  3763.                     'titre' => 'Votre rendez-vous est modifié pour le',
  3764.                     'frenchDate' => $frenchDate,
  3765.                 );
  3766.                 $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  3767.                 $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  3768.                 $sms "Votre RDV est modifié pour le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'imprévu contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  3769.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  3770.             }
  3771.         }
  3772.         //     //// == suppression
  3773.         else if ($rdv->getIdEtat()->getId() == 2) {
  3774.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  3775.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {                   
  3776.             $params = array(
  3777.                 "date" => substr($smsDate010),
  3778.                 "lien" => "{$_ENV['BASE_client']}audioprothesiste/{$rdv->getIdCentre()->getCity()}/{$rdv->getIdCentre()->getPostale()}/{$rdv->getIdCentre()->getName()}/prise-de-rdv-audioprothesiste-rapide/{$rdv->getIdCentre()->getId()}",
  3779.                 "heure" => substr($smsDate1115),
  3780.                 "patientName" => $client->getLastName(),
  3781.                 'titre' => 'Votre rendez-vous est annulé :',
  3782.                 'centerName' => $rdv->getIdCentre()->getName(),
  3783.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  3784.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  3785.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  3786.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  3787.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  3788.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  3789.                 'motif' => $rdv->getIdMotif()->getTitre(),
  3790.             );
  3791.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  3792.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject203);
  3793.             $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  3794.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  3795.             //}
  3796.         }
  3797.         // set center
  3798.         if (isset($data["centre_id"])) {
  3799.             $entityManager $this->getDoctrine()->getManager();
  3800.             $centreId $data["centre_id"];
  3801.             $centre $entityManager->getRepository(Centre::class)->find($centreId);
  3802.             if (!$centre) {
  3803.                 return $this->json([
  3804.                     'message' => 'Error, no Centre found with this ID',
  3805.                     'path' => 'src/Controller/YourController.php',
  3806.                 ]);
  3807.             }
  3808.             $rdv->setIdCentre($centre);
  3809.         }
  3810.         $rdv->setGoogleAgendaImported(false);
  3811.         //notif Audio
  3812.         if ($rdv->getIdEtat()->getId() != 2) {
  3813.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  3814.                 $params = array(
  3815.                     "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  3816.                     "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  3817.                     "date" => $pastDate->format("y-m-d"),
  3818.                     "heure" => $pastDate->format("H:i"),
  3819.                     'clientPhone' => $client->getPhone(),
  3820.                     'clientCivilite' => $client->getCivilite(),
  3821.                     'clientNom' => $client->getLastname(),
  3822.                     'clientPrenom' => $client->getName(),
  3823.                     'clientPostal' => $client->getPostal(),
  3824.                     'clientMail' => $client->getMail(),
  3825.                     "birthdate" => $rdv->getIdClient()->getBirthdate()->format("y-m-d"),
  3826.                     "mail" => $rdv->getIdClient()->getMail(),
  3827.                     "phone" => $rdv->getIdClient()->getPhone(),
  3828.                     "motif" => $rdv->getIdMotif()->getTitre(),
  3829.                     "address" => $rdv->getIdCentre()->getAddress(),
  3830.                     "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getLastName() . ' ' $rdv->getIdAudio()->getName(),
  3831.                     "newRdvDate" => substr($smsDate010),
  3832.                     "newRdvHour" => substr($smsDate1115),
  3833.                     "centerName" => $rdv->getIdCentre()->getName(),
  3834.                     "centerAddress" => $rdv->getIdCentre()->getAddress(),
  3835.                     "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  3836.                     'titre' => "Modification de Rendez-vous My Audio de {$rdv->getIdClient()->getLastname()}",
  3837.                     "urlPro" => "{$_ENV['BASE_logiciel']}",
  3838.                     "idPatient" => $rdv->getIdClient()->getId(),
  3839.                 );
  3840.                 $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  3841.                 $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  3842.                 if ($rdv->getIdAudio()->getModifRdvMail()) {
  3843.                     $subject "🔀 Rendez-vous My Audio modifié par " $client->getCivilite() . " " $client->getName() . " " $client->getLastname();
  3844.                     $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject185);
  3845.                 }
  3846.                 $subjectMyAudio "🔀 Le patient " $client->getCivilite() . " " $client->getName() . " " $client->getLastname() . "  a modifié son rendez-vous My Audio";
  3847.                 $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subjectMyAudio204);
  3848.                 if ($rdv->getIdAudio()->getModifRdvSms()) {
  3849.                     $sms "Votre RDV est modifié pour le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'imprévu contacter votre patient " $client->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  3850.                     $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  3851.                 }
  3852.             }
  3853.         } else if ($rdv->getIdEtat()->getId() == 2) {
  3854.             $params = array(
  3855.                 "date" => substr($smsDate010),
  3856.                 "heure" => substr($smsDate1115),
  3857.                 "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  3858.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  3859.                 "motif" => $rdv->getIdMotif()->getTitre(),
  3860.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  3861.                 "centerPostal" => $rdv->getIdCentre()->getPostale(),
  3862.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  3863.                 "centerName" => $rdv->getIdCentre()->getName(),
  3864.                 "clientNom" => $rdv->getIdClient()->getLastname(),
  3865.                 "clientPrenom" => $rdv->getIdClient()->getName(),
  3866.                 "clientMail" => $rdv->getIdClient()->getMail(),
  3867.                 "clientPhone" => $rdv->getIdClient()->getPhone(),
  3868.                 'titre' => "Annulation du Rendez-vous avec le patient {$rdv->getIdClient()->getLastname()}",
  3869.                 "proUrl" => "{$_ENV['BASE_logiciel']}",
  3870.                 "idPatient" => $rdv->getIdClient()->getId(),
  3871.             );
  3872.             $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  3873.             $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  3874.             if ($rdv->getIdAudio()->getModifRdvMail()) {
  3875.                 $subject "❌ Annulation du rendez-vous par le patient " $client->getCivilite() . " " $client->getName() . " " $client->getLastname();
  3876.                 $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject187);
  3877.             }
  3878.             $subject "❌ Annulation du rendez-vous par le patient " $client->getCivilite() . " " $client->getName() . " " $client->getLastname();
  3879.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject195);
  3880.             if ($rdv->getIdAudio()->getModifRdvSms()) {
  3881.                 $sms "Votre RDV du " substr($oldDate010) . " à " substr($oldDate1115) . "a été annulé, vous pouvez contacter votre patient pour fixer un autre RDV:" $client->getPhone() . " pour fixer un autre RDV.\nNe pas répondre.";
  3882.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  3883.             }
  3884.         }
  3885.         $entityManager->flush();
  3886.         if ((isset($data["prenom_patient"]))  || (isset($data["nom_patient"]))  || (isset($data["birthday_patient"]))  || (isset($data["mail_patient"]))  || (isset($data["portable_patient"]))  || (isset($data["fixe_patient"]))) {
  3887.             $birth \DateTime::createFromFormat("Y-m-d"$data["birthday_patient"]);
  3888.             if (is_null($rdv->getIdClientTemp())) {
  3889.                 $clientRDV $this->getDoctrine()
  3890.                     ->getRepository(Client::class)
  3891.                     ->findOneBy(['id' => $rdv->getIdClient()->getId()]);
  3892.                 $clientRDV->setName($data["prenom_patient"]);
  3893.                 $clientRDV->setLastname($data["nom_patient"]);
  3894.                 $clientRDV->setBirthdate($birth);
  3895.                 $clientRDV->setMail($data["mail_patient"]);
  3896.                 $clientRDV->setPhone($data["portable_patient"]);
  3897.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  3898.             } else {
  3899.                 $clientRDV $this->getDoctrine()
  3900.                     ->getRepository(ClientTemp::class)
  3901.                     ->findOneBy(['id' => $rdv->getIdClientTemp()->getId()]);
  3902.                 $clientRDV->setName($data["prenom_patient"]);
  3903.                 $clientRDV->setLastname($data["nom_patient"]);
  3904.                 $clientRDV->setBirthdate($birth);
  3905.                 $clientRDV->setMail($data["mail_patient"]);
  3906.                 $clientRDV->setPhone($data["portable_patient"]);
  3907.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  3908.             }
  3909.             $entityManager->flush();
  3910.         }
  3911.         if (is_null($rdv->getIdClient())) {
  3912.             $prenom_patient $rdv->getIdClientTemp()->getName();
  3913.             $nom_patient $rdv->getIdClientTemp()->getLastname();
  3914.             $mail_patient $rdv->getIdClientTemp()->getMail();
  3915.             $portable_patient $rdv->getIdClientTemp()->getPhone();
  3916.             $fixe_patient $rdv->getIdClientTemp()->getPhoneFixe();
  3917.             $birthday $rdv->getIdClientTemp()->getBirthdate();
  3918.         } elseif (is_null($rdv->getIdClientTemp())) {
  3919.             $prenom_patient =  $rdv->getIdClient()->getName();
  3920.             $nom_patient $rdv->getIdClient()->getLastname();
  3921.             $mail_patient $rdv->getIdClient()->getMail();
  3922.             $portable_patient $rdv->getIdClient()->getPhone();
  3923.             $fixe_patient $rdv->getIdClient()->getPhoneFixe();
  3924.             $birthday $rdv->getIdClient()->getBirthdate();
  3925.         } else {
  3926.             $prenom_patient "";
  3927.             $nom_patient "";
  3928.             $mail_patient "";
  3929.             $portable_patient "";
  3930.             $fixe_patient "";
  3931.             $birthday "";
  3932.         }
  3933.         return new Response(json_encode(([
  3934.             "id" => $rdv->getId(),
  3935.             "motif_id" => $rdv->getIdMotif()->getId(),
  3936.             "motif_libelle" => $rdv->getIdMotif()->getTitre(),
  3937.             "audio_id" => $rdv->getIdAudio()->getId(),
  3938.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  3939.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  3940.             "fullName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  3941.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  3942.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  3943.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  3944.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  3945.             "centre_name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : null,
  3946.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  3947.             "etat_id" => $rdv->getIdEtat()->getId(),
  3948.             "date" => $rdv->getDate(),
  3949.             "comment" => $rdv->getComment(),
  3950.             "note" => $rdv->getNote(),
  3951.             "review" => $rdv->getReview(),
  3952.             "prenom_patient" => $prenom_patient,
  3953.             "nom_patient" => $nom_patient,
  3954.             "mail_patient" => $mail_patient,
  3955.             "portable_patient" => $portable_patient,
  3956.             "fixe_patient" => $fixe_patient,
  3957.             "birthday" => $birthday,
  3958.             "status" => 200,
  3959.         ])));
  3960.     }
  3961.     /**
  3962.      * @Route("/rdv/{id}/supp", name="suppRdvByID", methods={"PUT"})
  3963.      */
  3964.     public function suppRdvByID(PublicFunction $publicFunctionRdv $rdvRequest $requestGoogleCalendarService $googleCalendarRdvSmsService $rdvSms): Response
  3965.     {
  3966.         $pastDate $rdv->getDate();
  3967.         $data json_decode($request->getContent(), true);
  3968.         $entityManager $this->getDoctrine()->getManager();
  3969.         if (!isset($data["token"])) {
  3970.             return new Response(json_encode([
  3971.                 "message" => "Pas de token n'a été spécifié",
  3972.                 "status" => 401,
  3973.             ]), 401);
  3974.         }
  3975.         /** @var Token */
  3976.         $token $this->getDoctrine()
  3977.             ->getRepository(Token::class)
  3978.             ->findOneBy(['token' => $data["token"]]);
  3979.         if (!$token) {
  3980.             return new Response(json_encode([
  3981.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  3982.                 "status" => 404,
  3983.             ]), 404);
  3984.         }
  3985.         // get token age
  3986.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  3987.         // if the token if older than 7 days
  3988.         if ($dateDiff->7) {
  3989.             $entityManager->remove($token);
  3990.             $entityManager->flush();
  3991.             return $this->json([
  3992.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  3993.                 'path' => 'src/Controller/ClientController.php',
  3994.                 "status" => 401,
  3995.             ], 401);
  3996.         }
  3997.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  3998.             return new Response(json_encode([
  3999.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  4000.                 "status" => 404,
  4001.             ]), 404);
  4002.         }
  4003.         // delete google agenda event
  4004.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  4005.             ->findBy(array('rdv' => $rdv));
  4006.         //dd($rdvEvents);
  4007.         $synchronisationCosium $this->getDoctrine()->getRepository(SynchronisationCosium::class)->findOneBy(["audio" => $rdv->getIdAudio()->getId()]);
  4008.         $cosiumCenter $this->getDoctrine()->getRepository(CosiumCenter::class)->findBy(["synchronisationCosium" => $synchronisationCosium"center" => $rdv->getIdCentre()]);
  4009.         if ($cosiumCenter) {
  4010.             $this->clientCosiumService->deleteRdv($synchronisationCosium$rdv);
  4011.         }
  4012.         foreach ($rdvEvents as $rdvEvent) {
  4013.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  4014.             $googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
  4015.             $entityManager->remove($rdvEvent);
  4016.             $entityManager->flush();
  4017.         }
  4018.         $etat $this->getDoctrine()
  4019.             ->getRepository(EtatRdv::class)
  4020.             ->findOneBy(['id' => 2]);
  4021.         if ($etat == null) {
  4022.             return new Response(json_encode(([
  4023.                 'message' => 'Error, no etat found at this id',
  4024.                 'path' => 'src/Controller/TrustedUserController.php',
  4025.                 "status" => 400,
  4026.             ])), 400);
  4027.         }
  4028.         $rdv->setIdEtat($etat);
  4029.         $rdv->setCacher(1);
  4030.         ////// SMSEMAIL A décommenter pour activer l'envoi de SMS + MAIL pour modification annulation de RDV, coté audio / client SMSEMAIL ////
  4031.         $date $rdv->getDate();
  4032.         $smsDate $date->format('d-m-Y H:i');
  4033.         $oldDate $pastDate->format('d-m-Y H:i');
  4034.         $locale 'fr_FR';
  4035.         $formatter = new IntlDateFormatter(
  4036.             $locale,
  4037.             IntlDateFormatter::FULL,
  4038.             IntlDateFormatter::SHORT,
  4039.             null,
  4040.             IntlDateFormatter::GREGORIAN,
  4041.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  4042.         );
  4043.         $smsDateLongFormat $formatter->format($date);
  4044.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  4045.         $frenchDate ucfirst($frenchDate);
  4046.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  4047.         // notif client
  4048.         if ($rdv->getIdEtat()->getId() != 2) {
  4049.             $params = array(
  4050.                 "lienModifier" => "{$_ENV['BASE_client']}mes-rendez-vous",
  4051.                 "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  4052.                 "date" => $smsDateLongFormat,
  4053.                 "heure" => substr($smsDate1115),
  4054.                 "motif" => $rdv->getIdMotif()->getTitre(),
  4055.                 "centerName" => $rdv->getIdCentre()->getName(),
  4056.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  4057.                 "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  4058.                 "audioMail" => $rdv->getIdAudio()->getMail(),
  4059.                 "centerPhone" => $rdv->getIdCentre()->getPhone(),
  4060.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  4061.                 "clientEmail" => $client->getMail(),
  4062.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  4063.                 'titre' => 'Votre rendez-vous est modifié pour le',
  4064.                 'frenchDate' => $frenchDate
  4065.             );
  4066.             $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  4067.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject205);
  4068.             $sms "Votre RDV est modifié pour le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'imprévu contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  4069.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  4070.             // creer un mail de notif pour myAudio + créé le template LP | MA | RR - Modification du RDV - Centre Auditif - MyAudio
  4071.             $subjectMyaudio "Rendez-vous My Audio a été modifié par l'audioprothésiste " $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName();
  4072.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$client->getName() . ' ' $client->getLastName(), $subjectMyaudio206);
  4073.         }
  4074.         //     //// == suppression
  4075.         else if ($rdv->getIdEtat()->getId() == 2) {
  4076.             $params = array(
  4077.                 "date" => substr($smsDate010),
  4078.                 "lien" => "{$_ENV['BASE_client']}search",
  4079.                 "heure" => substr($smsDate1115),
  4080.                 "patientName" => $client->getLastName() . ' ' $client->getName(),
  4081.                 'titre' => 'Votre rendez-vous est annulé :',
  4082.                 'centerName' => $rdv->getIdCentre()->getName(),
  4083.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4084.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  4085.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4086.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4087.                 "clientEmail" => $client->getMail() ?? '',
  4088.                 "clientPhone" => $client->getPhone() ?? '',
  4089.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4090.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  4091.                 'motif' => $rdv->getIdMotif()->getTitre(),
  4092.             );
  4093.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  4094.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  4095.             $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  4096.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  4097.             // creer un mail de notif pour myAudio + créé le template LP | MA | RR - Annlation du RDV - Centre Auditif - MyAudio
  4098.             $subjectMyaudio $rdv->getIdCentre()->getName() . " a annulé un rendez-vous My Audio avec " $client->getName() . ' ' $client->getLastName();
  4099.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$client->getName() . ' ' $client->getLastName(), $subjectMyaudio207);
  4100.         }
  4101.         //notif Audio
  4102.         if ($rdv->getIdEtat()->getId() != 2) {
  4103.             $params = array(
  4104.                 "lienModifier" => "{$_ENV['BASE_logiciel']}rdv",
  4105.                 "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  4106.                 "date" => substr($smsDate010),
  4107.                 "frenchDate" => $frenchDate,
  4108.                 "heure" => substr($smsDate1115),
  4109.                 'motif' => $rdv->getIdMotif()->getTitre(),
  4110.                 'clientPhone' => $client->getPhone(),
  4111.                 'clientNom' => $client->getLastname(),
  4112.                 'clientPrenom' => $client->getName(),
  4113.                 'clientCivilite' => $client->getCivilite(),
  4114.                 'clientPostal' => $client->getPostal(),
  4115.                 'clientMail' => $client->getMail(),
  4116.                 'centerName' => $rdv->getIdCentre()->getName(),
  4117.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4118.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  4119.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4120.                 'idPatient' => $client->getId(),
  4121.                 'proUrl' => "{$_ENV['BASE_logiciel']}",
  4122.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4123.                 'titre' => 'Votre rendez-vous est modifié pour le :'
  4124.             );
  4125.             $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  4126.             $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  4127.             if ($rdv->getIdAudio()->getModifRdvMail()) {
  4128.                 $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  4129.                 $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  4130.             }
  4131.             if ($rdv->getIdAudio()->getModifRdvSms()) {
  4132.                 $sms "Votre RDV est modifié pour le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'imprévu contacter votre patient " $client->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  4133.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  4134.             }
  4135.         } else if ($rdv->getIdEtat()->getId() == 2) {
  4136.             /* $params = array(  
  4137.                     "date" => substr($smsDate, 0, 10),
  4138.                     "lien"=> "{$_ENV['BASE_client']}search",
  4139.                     "heure" =>substr($smsDate, 11, 15),
  4140.                     "patientName" => $client->getLastName(),
  4141.                     'titre' => 'Votre rendez-vous est annulé :',
  4142.                     'centerName' => $rdv->getIdCentre()->getName(),
  4143.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4144.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  4145.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4146.                     'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4147.                     'audioproName' => $rdv->getIdAudio()->getCivilite().' '. $rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(),                    
  4148.                     'audioMail' => $rdv->getIdAudio()->getMail(),
  4149.                     'motif' => $rdv->getIdMotif()->getTitre(),
  4150.                 );
  4151.                 $subject = "Rendez-vous My Audio annulé avec " . $rdv->getIdCentre()->getName();
  4152.                 $publicFunction->sendEmail($params, $rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(), $subject, 188 );
  4153.                 $sms = "Votre RDV du " . substr($oldDate, 0, 10) . " à " . substr($oldDate, 11, 15) . "a été annulé, vous pouvez contacter votre patient pour fixer un autre RDV:" . $client->getPhone() . " pour fixer un autre RDV.\nNe pas répondre.";
  4154.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $rdv->getIdAudio()->getPhone());
  4155.                 */
  4156.         }
  4157.         // delete sms notification     
  4158.         $rdvSms->deleteAssociatedRdvSms($rdv);
  4159.         // delete client device
  4160.         /*$clientDevice = $this->getDoctrine()->getRepository(ClientDevice::class)->findOneBy(['rdv' => $rdv]);
  4161. if($clientDevice)
  4162. {
  4163. if ($client instanceof Client) {
  4164.     $nextRdvs = $this->getDoctrine()
  4165.         ->getRepository(Rdv::class)
  4166.         ->findBy([
  4167.             "id_client" => $rdv->getIdClient(),
  4168.             "id_motif" => ['106', '107', '108', '109'] 
  4169.         ]);
  4170.         $client->setClientStatus(null);
  4171. } elseif ($client instanceof ClientTemp) {
  4172.  $nextRdvs = $this->getDoctrine()
  4173.         ->getRepository(Rdv::class)
  4174.         ->findBy([
  4175.             "id_client_temp" => $rdv->getIdClientTemp(),
  4176.             "id_motif" => ['106', '107', '108', '109'] 
  4177.         ]);
  4178.         $client->setClientStatus(null);
  4179.     } 
  4180.     $locale = 'fr_FR';
  4181.     $fmt = new IntlDateFormatter($locale, IntlDateFormatter::FULL, IntlDateFormatter::NONE);
  4182.     $fmt->setPattern("EEEE dd MMMM yyyy"); 
  4183.     if($nextRdvs){
  4184.     $params = array(  
  4185.                 "title" => "Affectation de votre appareil et programmation de vos rendez-vous",
  4186.                 "centerName" => "{$rdv->getIdCentre()->getName()}",
  4187.                 "audioName" => "{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastName()}",
  4188.                 "centerAddress" => "{$rdv->getIdCentre()->getAddress()}",
  4189.                 "device" => "{$clientDevice->getDevice()->getModel()}",
  4190.                 "ears" => "{$clientDevice->getSettingDevice()->getName()}",
  4191.                 "rdvOneDate" => "{$fmt->format($nextRdvs['0']->getDate())}",
  4192.                 "rdvOneHour" => "{$nextRdvs['0']->getDate()->format('H:i')}",
  4193.                 "rdvTwoDate" => "{$fmt->format($nextRdvs['1']->getDate())}",
  4194.                 "rdvTwoHour" => "{$nextRdvs['1']->getDate()->format('H:i')}",
  4195.                 "rdvThreeDate" => "{$fmt->format($nextRdvs['2']->getDate())}",
  4196.                 "rdvThreeHour" => "{$nextRdvs['2']->getDate()->format('H:i')}",
  4197.                 "rdvFourDate" => "{$fmt->format($nextRdvs['3']->getDate())}",
  4198.                 "rdvFourHour" => "{$nextRdvs['3']->getDate()->format('H:i')}",
  4199.             );
  4200.     
  4201.             $publicFunction->sendEmail($params, $client->getMail(), $client->getName().' '.$client->getLastName(), "Annulation de vos prochains RDV", 162 );
  4202.         }
  4203.     foreach($nextRdvs as $rdv)
  4204.     {
  4205.         $entityManager->remove($rdv);
  4206.     }
  4207.     $entityManager->persist($client);
  4208.     $entityManager->remove($clientDevice);
  4209.     $entityManager->flush();
  4210. }*/
  4211.         $entityManager->flush();
  4212.         return new Response(json_encode(([
  4213.             "id" => $rdv->getId(),
  4214.             "motif_id" => $rdv->getIdMotif()->getId(),
  4215.             "motif_libelle" => $rdv->getIdMotif()->getTitre(),
  4216.             "audio_id" => $rdv->getIdAudio()->getId(),
  4217.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  4218.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  4219.             "fullName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  4220.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  4221.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  4222.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  4223.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  4224.             "centre_name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : null,
  4225.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  4226.             "etat_id" => $rdv->getIdEtat()->getId(),
  4227.             "date" => $rdv->getDate(),
  4228.             "comment" => $rdv->getComment(),
  4229.             "note" => $rdv->getNote(),
  4230.             "review" => $rdv->getReview(),
  4231.             "status" => 200,
  4232.         ])));
  4233.     }
  4234.     /**
  4235.      * @Route("/rdv/calendar", name="postRdvCalendar", methods={"POST"})
  4236.      */
  4237.     public function postRdvCalendar(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSms): Response
  4238.     {
  4239.         $data json_decode($request->getContent(), true);
  4240.         if (!isset($data["token"])) {
  4241.             return new Response(json_encode([
  4242.                 "message" => "Pas de token n'a été spécifié",
  4243.                 "status" => 401,
  4244.             ]), 401);
  4245.         }
  4246.         $entityManager $this->getDoctrine()->getManager();
  4247.         /** @var Token */
  4248.         $token $this->getDoctrine()
  4249.             ->getRepository(Token::class)
  4250.             ->findOneBy(['token' => $data["token"]]);
  4251.         if (!$token) {
  4252.             return new Response(json_encode([
  4253.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4254.                 "status" => 404,
  4255.             ]), 404);
  4256.         }
  4257.         // get token age
  4258.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4259.         // if the token if older than 7 days
  4260.         if ($dateDiff->7) {
  4261.             $entityManager->remove($token);
  4262.             $entityManager->flush();
  4263.             return $this->json([
  4264.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4265.                 'path' => 'src/Controller/ClientController.php',
  4266.                 "status" => 401,
  4267.             ], 401);
  4268.         }
  4269.         // makes the rdv
  4270.         $rdv = new Rdv();
  4271.         if ($token->getIdAudio()) {
  4272.             //if the token if for an audio
  4273.             $audio $token->getIdAudio();
  4274.             if ((isset($data["client_id"]))) {
  4275.                 $client $this->getDoctrine()
  4276.                     ->getRepository(Client::class)
  4277.                     ->findOneBy(['id' => $data["client_id"]]);
  4278.             } else {
  4279.                 $client $this->getDoctrine()
  4280.                     ->getRepository(ClientTemp::class)
  4281.                     ->findOneBy(['id' => $data["client_id_temp"]]);
  4282.             }
  4283.             if ($client == null) {
  4284.                 return new Response(json_encode(([
  4285.                     'message' => 'Error, no client found at this id',
  4286.                     'path' => 'src/Controller/RdvController.php',
  4287.                     "status" => 400,
  4288.                 ])), 400);
  4289.             }
  4290.         } elseif ($token->getIdClient()) {
  4291.             //if the token if for a client
  4292.             $client $token->getIdClient();
  4293.             /** @var Audio */
  4294.             $audio $this->getDoctrine()
  4295.                 ->getRepository(Audio::class)
  4296.                 ->findOneBy(['id' => $data["audio_id"]]);
  4297.             if (isset($data["proche_id"])) {
  4298.                 $proche $this->getDoctrine()
  4299.                     ->getRepository(Proches::class)
  4300.                     ->findOneBy(['id' => $data["proche_id"], "id_client" => $client]);
  4301.             }
  4302.             if ($audio == null) {
  4303.                 return new Response(json_encode(([
  4304.                     'message' => 'Error, no audio found at this id',
  4305.                     'path' => 'src/Controller/RdvController.php',
  4306.                     "status" => 400,
  4307.                 ])), 400);
  4308.             }
  4309.         } else {
  4310.             return new Response(json_encode(([
  4311.                 'message' => 'Error, token is not an audio token',
  4312.                 'path' => 'src/Controller/RdvController.php',
  4313.                 "status" => 400,
  4314.             ])), 400);
  4315.         }
  4316.         $rdv->setIdAudio($audio);
  4317.         if (isset($proche)) {
  4318.             $rdv->setIdProche($proche);
  4319.         }
  4320.         if (isset($data["client_id_temp"])) {
  4321.             $rdv->setIdClientTemp($client);
  4322.         } else {
  4323.             $rdv->setIdClient($client);
  4324.         }
  4325.         $rdv->setCacher(0);
  4326.         /** @var Centre */
  4327.         if (isset($data["centre_id"])) {
  4328.             $centre $this->getDoctrine()
  4329.                 ->getRepository(Centre::class)
  4330.                 ->findOneBy(['id' => $data["centre_id"]]);
  4331.             if ($centre == null) {
  4332.                 return new Response(json_encode(([
  4333.                     'message' => 'Error, no centre found at this id',
  4334.                     'path' => 'src/Controller/RdvController.php',
  4335.                     "status" => 400,
  4336.                 ])), 400);
  4337.             }
  4338.             /** @var AudioCentre */
  4339.             $liaison $this->getDoctrine()
  4340.                 ->getRepository(AudioCentre::class)
  4341.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  4342.             if ($liaison == null) {
  4343.                 return new Response(json_encode(([
  4344.                     'message' => 'Error, audio isnt part of the centre',
  4345.                     'path' => 'src/Controller/RdvController.php',
  4346.                     "status" => 400,
  4347.                 ])), 400);
  4348.             }
  4349.             $rdv->setIdCentre($centre);
  4350.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  4351.             // tries to set the lieu if it's an audio indie
  4352.             $lieu $this->getDoctrine()
  4353.                 ->getRepository(Lieu::class)
  4354.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  4355.             if ($lieu == null) {
  4356.                 return new Response(json_encode(([
  4357.                     'message' => 'Error, no lieu found at this id',
  4358.                     'path' => 'src/Controller/RdvController.php',
  4359.                     "status" => 400,
  4360.                 ])), 400);
  4361.             }
  4362.             $rdv->setIdLieu($lieu);
  4363.         } else {
  4364.             return new Response(json_encode(([
  4365.                 'message' => 'Error, no lieu/centre id',
  4366.                 'path' => 'src/Controller/RdvController.php',
  4367.                 "status" => 400,
  4368.             ])), 400);
  4369.         }
  4370.         /** @var Motif */
  4371.         $motif $this->getDoctrine()
  4372.             ->getRepository(Motif::class)
  4373.             ->find($data["motif_id"]);
  4374.         if ($motif == null) {
  4375.             return new Response(json_encode(([
  4376.                 'message' => 'Error, no motif found at this id',
  4377.                 'path' => 'src/Controller/RdvController.php',
  4378.                 "status" => 400,
  4379.             ])), 400);
  4380.         }
  4381.         /** @var AudioMotif */
  4382.         $audioMotif $this->getDoctrine()
  4383.             ->getRepository(AudioMotif::class)
  4384.             ->findOneBy(["id_audio" => $audio->getId(), "id_motif" => $data["motif_id"]]);
  4385.         if ($audioMotif == null) {
  4386.             return new Response(json_encode(([
  4387.                 'message' => 'Error, no motif of this id found at this audio',
  4388.                 'path' => 'src/Controller/RdvController.php',
  4389.                 "status" => 400,
  4390.             ])), 400);
  4391.         }
  4392.         // remove the taken schedule by rdv to make sure there is no overlap
  4393.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4394.         if (isset($data["note"])) {
  4395.             $rdv->setNote($data["note"]);
  4396.         }
  4397.         // test if the audio is available
  4398.         /*   if (isset($data["lieu_id"]) && $audio->getIsIndie()){
  4399.             if ($publicFunction->calculScheduleFitDate($audio, $date, $audioMotif->getDuration(), null, $lieu) == false) {
  4400.                 return new Response(json_encode(([
  4401.                     'message' => 'Error, no timestamp found at this time',
  4402.                     'path' => 'src/Controller/RdvController.php',
  4403.                     "status" => 400,
  4404.                 ])), 400);
  4405.             }
  4406.         } else {
  4407.             if ($publicFunction->calculScheduleFitDate($audio, $date, $audioMotif->getDuration(), $centre , null) == true) {
  4408.                 return new Response(json_encode(([
  4409.                     'message' => 'Error, no timestamp found at this time',
  4410.                     'path' => 'src/Controller/RdvController.php',
  4411.                     "status" => 400,
  4412.                 ])), 400);
  4413.             }
  4414.         }*/
  4415.         $rdv->setDate($date);
  4416.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  4417.         /** @var EtatRdv */
  4418.         $etat $this->getDoctrine()
  4419.             ->getRepository(EtatRdv::class)
  4420.             ->findOneBy(['id' => $data["etat_id"]]);
  4421.         if ($etat == null) {
  4422.             return new Response(json_encode(([
  4423.                 'message' => 'Error, no etat found at this id',
  4424.                 'path' => 'src/Controller/RdvController.php',
  4425.                 "status" => 400,
  4426.             ])), 400);
  4427.         }
  4428.         $rdv->setIdEtat($etat);
  4429.         $rdv->setIdMotif($motif);
  4430.         $rdv->setDuration($data["duree"]);
  4431.         $rdv->setIsAbsence($data["is_absence"]);
  4432.         $entityManager $this->getDoctrine()->getManager();
  4433.         $entityManager->persist($rdv);
  4434.         $entityManager->flush();
  4435.         $date $rdv->getDate();
  4436.         $smsDate $date->format('d-m-Y H:i');
  4437.         $locale 'fr_FR';
  4438.         $formatter = new IntlDateFormatter(
  4439.             $locale,
  4440.             IntlDateFormatter::FULL,
  4441.             IntlDateFormatter::SHORT,
  4442.             null,
  4443.             IntlDateFormatter::GREGORIAN,
  4444.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  4445.         );
  4446.         $smsDateLongFormat $formatter->format($date);
  4447.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  4448.         // client notif mail Sms
  4449.         // we send parametre for the trait methid
  4450.         //$params = $this->emailNotificationService->prepareEmailParams($user);
  4451.         // send email notifcation
  4452.         //$this->emailNotificationService->sendEmail($params, 'admin@example.com', 'Nouvelle inscription à My Audio Pro', 1);
  4453.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  4454.         $frenchDate ucfirst($frenchDate);
  4455.         $params = array(
  4456.             "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  4457.             "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  4458.             "date" => $smsDateLongFormat,
  4459.             "prenom" => $client->getName(),
  4460.             //"heure" => $smsDatee,
  4461.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  4462.             "centerName" => $rdv->getIdCentre()->getName(),
  4463.             "centerAddress" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  4464.             "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  4465.             "centerCity" => $rdv->getIdCentre()->getCity(),
  4466.             "motif" => $rdv->getIdMotif()->getTitre(),
  4467.             "RdvDate" => substr($smsDate010) . " à "  substr($smsDate1115),
  4468.             "audioName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  4469.             "clientMail" => $client->getMail(),
  4470.             "clientPhone" => $client->getPhone(),
  4471.             'titre' => "Votre rendez-vous est validé le " substr($smsDate010) . " à "  substr($smsDate1115),
  4472.             "address" => $rdv->getIdCentre()->getAddress(),
  4473.             "postal" => $rdv->getIdCentre()->getPostale(),
  4474.             "city" => $rdv->getIdCentre()->getCity(),
  4475.             "clientEmail" => $client->getMail(),
  4476.             "clientPassword" => isset($data["passwordGenerated"]) ? $data["passwordGenerated"] : null,
  4477.             "clientAddress" => $client->getAddress(),
  4478.             "clientPostal" => $client->getPostal(),
  4479.             "clientCity" => $client->getCity(),
  4480.             "audioName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  4481.             "frenchDate" => $frenchDate,
  4482.             "heure" => substr($smsDate1115),
  4483.             "centerName" => $rdv->getIdCentre()->getName(),
  4484.             "audioMail" => $rdv->getIdAudio()->getMail(),
  4485.             "modifUrl" => "{$_ENV['BASE_client']}mes-rendez-vous",
  4486.         );
  4487.         $subject "Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  4488.         $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject181);
  4489.         $sms "Votre RDV est validé le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'imprévu contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  4490.         // $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone());
  4491.         // audio Notif mail SMS
  4492.         /* $params = array(  
  4493.                         "lienModifer" =>"{$_ENV['BASE_logiciel']}rdv",
  4494.                         "lienAnnule"=> "{$_ENV['BASE_logiciel']}rdv",
  4495.                         "date" => substr($smsDate, 0, 10),
  4496.                         "heure" =>substr($smsDate, 11, 15),
  4497.                         'motif' => $rdv->getIdMotif()->getTitre(),
  4498.                         'clientPhone'=> $client->getPhone(),
  4499.                         'clientNom' =>$client->getLastname(),
  4500.                         'clientPrenom' =>$client->getName(),
  4501.                         'clientCivilite' => $client->getCivilite(),
  4502.                         'clientPostal' => $client->getPostal(),
  4503.                         'clientMail' => $client->getMail(),
  4504.                         'centerName' => $rdv->getIdCentre()->getName(),
  4505.                         'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4506.                         'centerCity' => $rdv->getIdCentre()->getCity(),
  4507.                         'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4508.                         'idPatient' => $client->getId(),
  4509.                         'proUrl' => "{$_ENV['BASE_logiciel']}",
  4510.                         'audioproName' => $rdv->getIdAudio()->getCivilite().' '.$rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(),
  4511.                         'titre' => 'Votre rendez-vous est modifié pour le :'
  4512.                     );
  4513.         $subject = "🔀 Rendez-vous My Audio modifié du ". $frenchDate . " à " . substr($smsDate, 11, 15);
  4514.         $publicFunction->sendEmail($params, $rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(), $subject, 186 );
  4515.         $sms = "Vous avez un nouveau RDV le " . substr($smsDate, 0, 10) . " à " . substr($smsDate, 11, 15) . ", en cas d'aléas contactez votre patient " . $client->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  4516.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $rdv->getIdAudio()->getPhone());*/
  4517.         // google calendar post
  4518.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  4519.             ->findBy(array('audio' => $audio->getId()));
  4520.         $data['rdv'] = $rdv->getId();
  4521.         $synchronisationCosium $this->getDoctrine()->getRepository(SynchronisationCosium::class)->findOneBy(["audio" => $audio->getId()]);
  4522.         $cosiumCenter $this->getDoctrine()->getRepository(CosiumCenter::class)->findOneBy(["synchronisationCosium" => $synchronisationCosium"center" => $rdv->getIdCentre()]);
  4523.         if ($cosiumCenter) {
  4524.             $this->clientCosiumService->createAgenda($synchronisationCosium$rdv$cosiumCenter);
  4525.         }
  4526.         foreach ($synchronisations as $synchronisation) {
  4527.             if (!$synchronisation->getIsDeleted()) {
  4528.                 try {
  4529.                     $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  4530.                     $googleCalendar->createEvent($synchronisation$data);
  4531.                 } catch (\Exception $e) {
  4532.                     error_log('Error refreshing access token or creating event: ' $e->getMessage());
  4533.                 }
  4534.             }
  4535.         }
  4536.         // create schedule notification sms
  4537.         $rdvSms->storeRdvSmsNotifications($rdv);
  4538.         if ($rdv->getClientDevice()) {
  4539.             $nextRdv $this->getDoctrine()
  4540.                 ->getRepository(Rdv::class)
  4541.                 ->find($rdv->getClientDevice()->getRdv()->getId());
  4542.             if ($nextRdv->getIdClientTemp()) {
  4543.                 $nextRdvs $this->getDoctrine()
  4544.                     ->getRepository(Rdv::class)
  4545.                     ->findBy([
  4546.                         "id_client_temp" => $nextRdv->getIdClientTemp(),
  4547.                         "id_motif" => ['106''107''108''109']
  4548.                     ]);
  4549.             } else {
  4550.                 $nextRdvs $this->getDoctrine()
  4551.                     ->getRepository(Rdv::class)
  4552.                     ->findBy([
  4553.                         "id_client" => $nextRdv->getIdClient(),
  4554.                         "id_motif" => ['106''107''108''109']
  4555.                     ]);
  4556.             }
  4557.             $mappedNextRdvs array_map(function ($rdv) {
  4558.                 return [
  4559.                     'id' => $rdv->getId(),
  4560.                     'date' => $rdv->getDate()->format('d-m-Y'),
  4561.                     'hours' => $rdv->getDate()->format('H:i'),
  4562.                     'duration' => $rdv->getDuration(),
  4563.                     "motif_id" => $rdv->getIdMotif()->getId(),
  4564.                     "motif_titre" => $rdv->getIdMotif()->getTitre(),
  4565.                     "duration" => $rdv->getDuration(),
  4566.                 ];
  4567.             }, $nextRdvs);
  4568.         }
  4569.         return new Response(json_encode(([
  4570.             "id" => $rdv->getId(),
  4571.             "motif_id" => $rdv->getIdMotif()->getId(),
  4572.             "audio_id" => $rdv->getIdAudio()->getId(),
  4573.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  4574.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  4575.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  4576.             "centerName" => $rdv->getIdCentre()->getName(),
  4577.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  4578.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  4579.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  4580.             "duration" => $data["duree"],
  4581.             "etat_id" => $rdv->getIdEtat()->getId(),
  4582.             "date" => $rdv->getDate(),
  4583.             "clientEtatId" => $client->getClientStatus() ? $client->getClientStatus()->getId() : 0,
  4584.             "isClient" => ($client instanceof Client) ? 0,
  4585.             "device" => $rdv->getClientDevice() ? [
  4586.                 "isDevice" => true,
  4587.                 "deviceID" => $rdv->getClientDevice()->getDevice()->getId(),
  4588.                 "clientDeviceID" => $rdv->getClientDevice()->getId(),
  4589.                 "deviceModel" => $rdv->getClientDevice()->getDevice()->getModel(),
  4590.                 "settingName" => $rdv->getClientDevice()->getSettingDevice()->getName(),
  4591.                 "settingDeviceId" => $rdv->getClientDevice()->getSettingDevice()->getSlug(),
  4592.                 "settingSlug" => $rdv->getClientDevice()->getSettingDevice()->getSlug(),
  4593.                 "nextRdvs" => $mappedNextRdvs
  4594.             ] : [
  4595.                 "isDevice" => false
  4596.             ],
  4597.             "comment" => $rdv->getComment(),
  4598.             "review" => $rdv->getReview(),
  4599.             "note" => $rdv->getNote(),
  4600.             "status" => 200,
  4601.         ])));
  4602.     }
  4603.     /**
  4604.      * @Route("/rdv/absence", name="postAbsenceCalendar", methods={"POST"})
  4605.      */
  4606.     public function postAbsenceCalendar(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendar): Response
  4607.     {
  4608.         $data json_decode($request->getContent(), true);
  4609.         if (!isset($data["token"])) {
  4610.             return new Response(json_encode([
  4611.                 "message" => "Pas de token n'a été spécifié",
  4612.                 "status" => 401,
  4613.             ]), 401);
  4614.         }
  4615.         $entityManager $this->getDoctrine()->getManager();
  4616.         /** @var Token */
  4617.         $token $this->getDoctrine()
  4618.             ->getRepository(Token::class)
  4619.             ->findOneBy(['token' => $data["token"]]);
  4620.         if (!$token) {
  4621.             return new Response(json_encode([
  4622.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4623.                 "status" => 404,
  4624.             ]), 404);
  4625.         }
  4626.         // get token age
  4627.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4628.         // if the token if older than 7 days
  4629.         if ($dateDiff->7) {
  4630.             $entityManager->remove($token);
  4631.             $entityManager->flush();
  4632.             return $this->json([
  4633.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4634.                 'path' => 'src/Controller/ClientController.php',
  4635.                 "status" => 401,
  4636.             ], 401);
  4637.         }
  4638.         // makes the rdv
  4639.         $rdv = new Rdv();
  4640.         $audio $token->getIdAudio();
  4641.         $rdv->setIdAudio($audio);
  4642.         /** @var Centre */
  4643.         if (isset($data["centre_id"])) {
  4644.             $centre $this->getDoctrine()
  4645.                 ->getRepository(Centre::class)
  4646.                 ->findOneBy(['id' => $data["centre_id"]]);
  4647.             if ($centre == null) {
  4648.                 return new Response(json_encode(([
  4649.                     'message' => 'Error, no centre found at this id',
  4650.                     'path' => 'src/Controller/RdvController.php',
  4651.                     "status" => 400,
  4652.                 ])), 400);
  4653.             }
  4654.             /** @var AudioCentre */
  4655.             $liaison $this->getDoctrine()
  4656.                 ->getRepository(AudioCentre::class)
  4657.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  4658.             if ($liaison == null) {
  4659.                 return new Response(json_encode(([
  4660.                     'message' => 'Error, audio isnt part of the centre',
  4661.                     'path' => 'src/Controller/RdvController.php',
  4662.                     "status" => 400,
  4663.                 ])), 400);
  4664.             }
  4665.             $rdv->setIdCentre($centre);
  4666.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  4667.             // tries to set the lieu if it's an audio indie
  4668.             $lieu $this->getDoctrine()
  4669.                 ->getRepository(Lieu::class)
  4670.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  4671.             if ($lieu == null) {
  4672.                 return new Response(json_encode(([
  4673.                     'message' => 'Error, no lieu found at this id',
  4674.                     'path' => 'src/Controller/RdvController.php',
  4675.                     "status" => 400,
  4676.                 ])), 400);
  4677.             }
  4678.             $rdv->setIdLieu($lieu);
  4679.         } else {
  4680.             return new Response(json_encode(([
  4681.                 'message' => 'Error, no lieu/centre id',
  4682.                 'path' => 'src/Controller/RdvController.php',
  4683.                 "status" => 400,
  4684.             ])), 400);
  4685.         }
  4686.         // remove the taken schedule by rdv to make sure there is no overlap
  4687.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4688.         $rdv->setDate($date);
  4689.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  4690.         /** @var EtatRdv */
  4691.         $etat $this->getDoctrine()
  4692.             ->getRepository(EtatRdv::class)
  4693.             ->findOneBy(['id' => $data["etat_id"]]);
  4694.         if ($etat == null) {
  4695.             return new Response(json_encode(([
  4696.                 'message' => 'Error, no etat found at this id',
  4697.                 'path' => 'src/Controller/RdvController.php',
  4698.                 "status" => 400,
  4699.             ])), 400);
  4700.         }
  4701.         $rdv->setIdEtat($etat);
  4702.         $rdv->setDuration($data["duree"]);
  4703.         $rdv->setIsAbsence($data["is_absence"]);
  4704.         $rdv->setMotifAbsence($data["motif"]);
  4705.         $rdv->setColor($data["color"]);
  4706.         $rdv->setNote($data["note"]);
  4707.         $rdv->setCacher(0);
  4708.         $entityManager $this->getDoctrine()->getManager();
  4709.         $entityManager->persist($rdv);
  4710.         $entityManager->flush();
  4711.         // create google calendar absence event
  4712.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  4713.             ->findBy(array('audio' => $audio->getId()));
  4714.         $data['rdv'] = $rdv->getId();
  4715.         $data['motif_absence'] = $rdv->getMotifAbsence() !== '' $rdv->getMotifAbsence() : "Absence";
  4716.         //        dd($data);
  4717.         foreach ($synchronisations as $synchronisation) {
  4718.             if (!$synchronisation->getIsDeleted()) {
  4719.                 try {
  4720.                     $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  4721.                     $googleCalendar->createAbsenceEvent($synchronisation$data);
  4722.                 } catch (\Google\Service\Exception $e) {
  4723.                     if ($e->getCode() === 403 && str_contains($e->getMessage(), 'insufficientPermissions')) {
  4724.                         error_log("Skipped synchronisation ID {$synchronisation->getId()} due to insufficient permissions.");
  4725.                         continue;
  4726.                     }
  4727.                     throw $e;
  4728.                 }
  4729.             }
  4730.         }
  4731.         return new Response(json_encode(([
  4732.             "id" => $rdv->getId(),
  4733.             "audio_id" => $rdv->getIdAudio()->getId(),
  4734.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  4735.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  4736.             "duration" => $data["duree"],
  4737.             "etat_id" => $rdv->getIdEtat()->getId(),
  4738.             "date" => $rdv->getDate(),
  4739.             "status" => 200,
  4740.         ])));
  4741.     }
  4742.     /**
  4743.      * @Route("/rdv/{id}/absence", name="puttAbsenceCalendar", methods={"PUT"})
  4744.      */
  4745.     public function putAbsenceCalendar(Request $requestRdv $rdvPublicFunction $publicFunctionGoogleCalendarService $googleCalendar): Response
  4746.     {
  4747.         $data json_decode($request->getContent(), true);
  4748.         if (!isset($data["token"])) {
  4749.             return new Response(json_encode([
  4750.                 "message" => "Pas de token n'a été spécifié",
  4751.                 "status" => 401,
  4752.             ]), 401);
  4753.         }
  4754.         $entityManager $this->getDoctrine()->getManager();
  4755.         /** @var Token */
  4756.         $token $this->getDoctrine()
  4757.             ->getRepository(Token::class)
  4758.             ->findOneBy(['token' => $data["token"]]);
  4759.         if (!$token) {
  4760.             return new Response(json_encode([
  4761.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4762.                 "status" => 404,
  4763.             ]), 404);
  4764.         }
  4765.         // get token age
  4766.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4767.         // if the token if older than 7 days
  4768.         if ($dateDiff->7) {
  4769.             $entityManager->remove($token);
  4770.             $entityManager->flush();
  4771.             return $this->json([
  4772.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4773.                 'path' => 'src/Controller/ClientController.php',
  4774.                 "status" => 401,
  4775.             ], 401);
  4776.         }
  4777.         // remove the taken schedule by rdv to make sure there is no overlap
  4778.         if (isset($data["date"])) {
  4779.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4780.             $rdv->setDate($date);
  4781.         }
  4782.         if (isset($data["duree"])) {
  4783.             $rdv->setDuration($data["duree"]);
  4784.         }
  4785.         if (isset($data["motif"])) {
  4786.             $rdv->setMotifAbsence($data["motif"]);
  4787.         }
  4788.         if (isset($data["color"])) {
  4789.             $rdv->setColor($data["color"]);
  4790.         }
  4791.         if (isset($data["note"])) {
  4792.             $rdv->setNote($data["note"]);
  4793.         }
  4794.         $entityManager $this->getDoctrine()->getManager();
  4795.         $entityManager->flush();
  4796.         $data['rdv'] = $rdv->getId();
  4797.         $data['motif_absence'] = $rdv->getMotifAbsence() !== '' $rdv->getMotifAbsence() : "Absence";
  4798.         $data['note'] = $rdv->getNote();
  4799.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  4800.             ->findBy(array('rdv' => $rdv));
  4801.         foreach ($rdvEvents as $rdvEvent) {
  4802.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  4803.             $googleCalendar->updateAbsenceEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  4804.         }
  4805.         return new Response(json_encode(([
  4806.             "id" => $rdv->getId(),
  4807.             "audio_id" => $rdv->getIdAudio()->getId(),
  4808.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  4809.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  4810.             "duration" => $rdv->getDuration(),
  4811.             "etat_id" => $rdv->getIdEtat()->getId(),
  4812.             "date" => $rdv->getDate(),
  4813.             "status" => 200,
  4814.         ])));
  4815.     }
  4816.     /**
  4817.      * @Route("/rdv/{id}/calendar", name="editRdvCalendarByID", methods={"PUT"})
  4818.      */
  4819.     public function editRdvCalendarByID(SmsHandler $smsHandlerRdv $rdvRequest $requestGoogleCalendarService $googleCalendarPublicFunction $publicFunctionRdvSmsService $rdvSms): Response
  4820.     {
  4821.         $pastDate $rdv->getDate();
  4822.         $data json_decode($request->getContent(), true);
  4823.         $entityManager $this->getDoctrine()->getManager();
  4824.         if (!isset($data["token"])) {
  4825.             return new Response(json_encode([
  4826.                 "message" => "Pas de token n'a été spécifié",
  4827.                 "status" => 401,
  4828.             ]), 401);
  4829.         }
  4830.         /** @var Token */
  4831.         $token $this->getDoctrine()
  4832.             ->getRepository(Token::class)
  4833.             ->findOneBy(['token' => $data["token"]]);
  4834.         if (!$token) {
  4835.             return new Response(json_encode([
  4836.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4837.                 "status" => 404,
  4838.             ]), 404);
  4839.         }
  4840.         // get token age
  4841.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4842.         // if the token if older than 7 days
  4843.         if ($dateDiff->7) {
  4844.             $entityManager->remove($token);
  4845.             $entityManager->flush();
  4846.             return $this->json([
  4847.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4848.                 'path' => 'src/Controller/ClientController.php',
  4849.                 "status" => 401,
  4850.             ], 401);
  4851.         }
  4852.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  4853.             return new Response(json_encode([
  4854.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  4855.                 "status" => 404,
  4856.             ]), 404);
  4857.         }
  4858.         if (isset($data["etat_id"])) {
  4859.             $etat $this->getDoctrine()
  4860.                 ->getRepository(EtatRdv::class)
  4861.                 ->findOneBy(['id' => $data["etat_id"]]);
  4862.             if ($etat == null) {
  4863.                 return new Response(json_encode(([
  4864.                     'message' => 'Error, no etat found at this id',
  4865.                     'path' => 'src/Controller/TrustedUserController.php',
  4866.                     "status" => 400,
  4867.                 ])), 400);
  4868.             }
  4869.             $rdv->setIdEtat($etat);
  4870.         }
  4871.         if (isset($data["audio_id"])) {
  4872.             $audio $this->getDoctrine()
  4873.                 ->getRepository(Audio::class)
  4874.                 ->findOneBy(['id' => $data["audio_id"]]);
  4875.             if ($audio == null) {
  4876.                 return new Response(json_encode(([
  4877.                     'message' => 'Error, no audio found at this id',
  4878.                     'path' => 'src/Controller/TrustedUserController.php',
  4879.                     "status" => 400,
  4880.                 ])), 400);
  4881.             }
  4882.             $rdv->setIdAudio($audio);
  4883.         }
  4884.         if (isset($data["motif_id"])) {
  4885.             $motif $this->getDoctrine()
  4886.                 ->getRepository(Motif::class)
  4887.                 ->find($data["motif_id"]);
  4888.             if ($motif == null) {
  4889.                 return new Response(json_encode(([
  4890.                     'message' => 'Error, no motif found at this id',
  4891.                     'path' => 'src/Controller/TrustedUserController.php',
  4892.                     "status" => 400,
  4893.                 ])), 400);
  4894.             }
  4895.             $rdv->setIdMotif($motif);
  4896.         }
  4897.         if (isset($data["client_id"])) {
  4898.             $client $this->getDoctrine()
  4899.                 ->getRepository(Client::class)
  4900.                 ->findOneBy(['id' => $data["client_id"]]);
  4901.             if ($client == null) {
  4902.                 return new Response(json_encode(([
  4903.                     'message' => 'Error, no client found at this id',
  4904.                     'path' => 'src/Controller/TrustedUserController.php',
  4905.                     "status" => 400,
  4906.                 ])), 400);
  4907.             }
  4908.             $rdv->setIdClient($client);
  4909.         }
  4910.         if (isset($data["date"])) {
  4911.             // remove the taken schedule by rdv to make sure there is no overlap
  4912.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4913.             $audioMotif $this->getDoctrine()
  4914.                 ->getRepository(AudioMotif::class)
  4915.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  4916.             if ($audioMotif == null) {
  4917.                 return new Response(json_encode(([
  4918.                     'message' => 'Error, no motif of this id found at this audio',
  4919.                     'path' => 'src/Controller/RdvController.php',
  4920.                     "status" => 400,
  4921.                 ])), 400);
  4922.             }
  4923.             if ($rdv->getIdAudio()->getIsIndie()) {
  4924.                 if ($rdv->getIdCentre()) {
  4925.                     // regular centre audio indie
  4926.                     /** @var AudioCentre */
  4927.                     $liaison $this->getDoctrine()
  4928.                         ->getRepository(AudioCentre::class)
  4929.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  4930.                     if ($liaison == null) {
  4931.                         return new Response(json_encode(([
  4932.                             'message' => 'Error, audio isnt part of the centre',
  4933.                             'path' => 'src/Controller/RdvController.php',
  4934.                             "status" => 400,
  4935.                         ])), 400);
  4936.                     }
  4937.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  4938.                         return new Response(json_encode(([
  4939.                             'message' => 'Error, no horaire found for this audio',
  4940.                             'path' => 'src/Controller/RdvController.php',
  4941.                             "status" => 400,
  4942.                         ])), 400);
  4943.                     }
  4944.                 } else {
  4945.                     // lieu audio indie
  4946.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  4947.                         return new Response(json_encode(([
  4948.                             'message' => 'Error, no horaire found for this audio',
  4949.                             'path' => 'src/Controller/RdvController.php',
  4950.                             "status" => 400,
  4951.                         ])), 400);
  4952.                     }
  4953.                 }
  4954.             } else {
  4955.                 // regular centre
  4956.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  4957.                     return new Response(json_encode(([
  4958.                         'message' => 'Error, no horaire found for this audio',
  4959.                         'path' => 'src/Controller/RdvController.php',
  4960.                         "status" => 400,
  4961.                     ])), 400);
  4962.                 }
  4963.             }
  4964.             $rdv->setDate($date);
  4965.         }
  4966.         if (isset($data["comment"]) && $token->getIdClient()) {
  4967.             $rdv->setComment($data["comment"]);
  4968.         }
  4969.         if (isset($data["review"]) && $token->getIdClient()) {
  4970.             $rdv->setReview($data["review"]);
  4971.         }
  4972.         if (isset($data["note"])) {
  4973.             $rdv->setNote($data["note"]);
  4974.         }
  4975.         $entityManager->flush();
  4976.         $date $rdv->getDate();
  4977.         $smsDate $date->format('d-m-Y H:i');
  4978.         $oldDate $pastDate->format('d-m-Y H:i');
  4979.         $locale 'fr_FR';
  4980.         $formatter = new IntlDateFormatter(
  4981.             $locale,
  4982.             IntlDateFormatter::FULL,
  4983.             IntlDateFormatter::SHORT,
  4984.             null,
  4985.             IntlDateFormatter::GREGORIAN,
  4986.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  4987.         );
  4988.         $smsDateLongFormat $formatter->format($date);
  4989.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  4990.         $frenchDate ucfirst($frenchDate);
  4991.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  4992.         // notif client
  4993.         if ($rdv->getIdEtat()->getId() != 2) {
  4994.             $params = array(
  4995.                 "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  4996.                 "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  4997.                 "date" => $smsDateLongFormat,
  4998.                 "heure" => substr($smsDate1115),
  4999.                 "motif" => $rdv->getIdMotif()->getTitre(),
  5000.                 "centerName" => $rdv->getIdCentre()->getName(),
  5001.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  5002.                 "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  5003.                 "audioMail" => $rdv->getIdAudio()->getMail(),
  5004.                 "centerPhone" => $rdv->getIdCentre()->getPhone(),
  5005.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  5006.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  5007.                 'titre' => 'Votre rendez-vous est modifié pour le',
  5008.                 'frenchDate' => $frenchDate,
  5009.             );
  5010.             $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  5011.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  5012.             if ($data["sms"]) {
  5013.                 $sms "Votre RDV est modifié pour le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'imprévu contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  5014.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  5015.             }
  5016.         }
  5017.         //     //// == suppression
  5018.         else if ($rdv->getIdEtat()->getId() == 2) {
  5019.             $params = array(
  5020.                 "date" => substr($smsDate010),
  5021.                 "lien" => "{$_ENV['BASE_client']}search",
  5022.                 "heure" => substr($smsDate1115),
  5023.                 "patientName" => $client->getLastName(),
  5024.                 'titre' => 'Votre rendez-vous est annulé :',
  5025.                 'centerName' => $rdv->getIdCentre()->getName(),
  5026.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5027.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  5028.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5029.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  5030.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  5031.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  5032.                 'motif' => $rdv->getIdMotif()->getTitre(),
  5033.             );
  5034.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  5035.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  5036.             if ($data["sms"]) {
  5037.                 $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  5038.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  5039.             }
  5040.         }
  5041.         //notif Audio
  5042.         if ($rdv->getIdEtat()->getId() != 2) {
  5043.             if ($data["sms"]) {
  5044.                 $params = array(
  5045.                     "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  5046.                     "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  5047.                     "date" => substr($smsDate010),
  5048.                     "frenchDate" => $frenchDate,
  5049.                     "heure" => substr($smsDate1115),
  5050.                     'motif' => $rdv->getIdMotif()->getTitre(),
  5051.                     'clientPhone' => $client->getPhone(),
  5052.                     'clientNom' => $client->getLastname(),
  5053.                     'clientPrenom' => $client->getName(),
  5054.                     'clientCivilite' => $client->getCivilite(),
  5055.                     'clientPostal' => $client->getPostal(),
  5056.                     'clientMail' => $client->getMail(),
  5057.                     'centerName' => $rdv->getIdCentre()->getName(),
  5058.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5059.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  5060.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5061.                     'idPatient' => $client->getId(),
  5062.                     'proUrl' => "{$_ENV['BASE_logiciel']}",
  5063.                     'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  5064.                     'titre' => 'Votre rendez-vous est modifié pour le :'
  5065.                 );
  5066.                 $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  5067.                 $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  5068.                 if ($rdv->getIdAudio()->getModifRdvMail()) {
  5069.                     $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  5070.                     $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  5071.                 }
  5072.                 if ($rdv->getIdAudio()->getModifRdvSms()) {
  5073.                     $sms "Votre RDV est modifié pour le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'imprévu contacter votre patient " $client->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  5074.                    // $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $phoneAudio);
  5075.                 }
  5076.             }
  5077.         } else if ($rdv->getIdEtat()->getId() == 2) {
  5078.             if ($data["sms"]) {
  5079.                 $params = array(
  5080.                     "date" => substr($smsDate010),
  5081.                     "lien" => "{$_ENV['BASE_client']}search",
  5082.                     "heure" => substr($smsDate1115),
  5083.                     "patientName" => $client->getLastName(),
  5084.                     'titre' => 'Votre rendez-vous est annulé :',
  5085.                     'centerName' => $rdv->getIdCentre()->getName(),
  5086.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5087.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  5088.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5089.                     'centerPhone' => $rdv->getIdCentre()->getPhone(),
  5090.                     'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  5091.                     'audioMail' => $rdv->getIdAudio()->getMail(),
  5092.                     'motif' => $rdv->getIdMotif()->getTitre(),
  5093.                 );
  5094.                 $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  5095.                 $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  5096.                 if ($rdv->getIdAudio()->getModifRdvMail()) {
  5097.                     $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  5098.                     $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject188);
  5099.                 }
  5100.                 if ($rdv->getIdAudio()->getModifRdvSms()) {
  5101.                     $sms "Votre RDV du " substr($oldDate010) . " à " substr($oldDate1115) . "a été annulé, vous pouvez contacter votre patient pour fixer un autre RDV:" $client->getPhone() . " pour fixer un autre RDV.\nNe pas répondre.";
  5102.                     //$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $phoneAudio);
  5103.                 }
  5104.             }
  5105.         }
  5106.         /* generate sms notif on update */
  5107.         // update sms notification     
  5108.         $rdvSms->updateRdvSms($rdv);
  5109.         // google calendar update
  5110.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  5111.             ->findBy(array('audio' => $rdv->getIdAudio()));
  5112.         $data['rdv'] = $rdv->getId();
  5113.         $data['motif_id'] = $rdv->getIdMotif();
  5114.         $data['note'] = $rdv->getNote();
  5115.         if ($rdv->getIdClient() !== null) {
  5116.             $data["client_id"] = $rdv->getIdClient()->getId();
  5117.         }
  5118.         if ($rdv->getIdClientTemp() !== null) {
  5119.             $data["client_id_temp"] = $rdv->getIdClientTemp()->getId();
  5120.         }
  5121.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  5122.             ->findBy(array('rdv' => $rdv));
  5123.         foreach ($rdvEvents as $rdvEvent) {
  5124.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  5125.             $googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  5126.         }
  5127.         return new Response(json_encode(([
  5128.             "id" => $rdv->getId(),
  5129.             "motif_id" => $rdv->getIdMotif()->getId(),
  5130.             "audio_id" => $rdv->getIdAudio()->getId(),
  5131.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  5132.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  5133.             "fullName" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  5134.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  5135.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  5136.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  5137.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  5138.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  5139.             "centre_id" => $rdv->getIdCentre()->getId(),
  5140.             "centerName" => $rdv->getIdCentre()->getName(),
  5141.             "etat_id" => $rdv->getIdEtat()->getId(),
  5142.             "date" => $rdv->getDate(),
  5143.             "comment" => $rdv->getComment(),
  5144.             "note" => $rdv->getNote(),
  5145.             "review" => $rdv->getReview(),
  5146.             "status" => 200,
  5147.         ])));
  5148.     }
  5149.     /**
  5150.      * @Route("/rdv/{id}/absence", name="deletetAbsenceCalendar", methods={"DELETE"})
  5151.      */
  5152.     public function deletetAbsenceCalendar(Request $requestRdv $rdvGoogleCalendarService $googleCalendar): Response
  5153.     {
  5154.         $data json_decode($request->getContent(), true);
  5155.         if (!isset($data["token"])) {
  5156.             return new Response(json_encode([
  5157.                 "message" => "Pas de token n'a été spécifié",
  5158.                 "status" => 401,
  5159.             ]), 401);
  5160.         }
  5161.         $entityManager $this->getDoctrine()->getManager();
  5162.         /** @var Token */
  5163.         $token $this->getDoctrine()
  5164.             ->getRepository(Token::class)
  5165.             ->findOneBy(['token' => $data["token"]]);
  5166.         if (!$token) {
  5167.             return new Response(json_encode([
  5168.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  5169.                 "status" => 404,
  5170.             ]), 404);
  5171.         }
  5172.         // get token age
  5173.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  5174.         // if the token if older than 7 days
  5175.         if ($dateDiff->7) {
  5176.             $entityManager->remove($token);
  5177.             $entityManager->flush();
  5178.             return $this->json([
  5179.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  5180.                 'path' => 'src/Controller/ClientController.php',
  5181.                 "status" => 401,
  5182.             ], 401);
  5183.         }
  5184.         // delete google agenda event
  5185.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  5186.             ->findBy(array('rdv' => $rdv));
  5187.         //dd($rdvEvents);
  5188.         foreach ($rdvEvents as $rdvEvent) {
  5189.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  5190.             $googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
  5191.             $entityManager->remove($rdvEvent);
  5192.             $entityManager->flush();
  5193.         }
  5194.         $entityManager->remove($rdv);
  5195.         $entityManager->flush();
  5196.         return new Response(json_encode(([
  5197.             "message" => "Absence Supprime",
  5198.             "status" => 200,
  5199.         ])));
  5200.     }
  5201.     /**
  5202.      * @Route("/rdvs/facturation/rdv", name="getMyRDV", methods={"GET"})
  5203.      */
  5204.     public function getMyRDV(Request $request): Response
  5205.     {
  5206.         /* $date = new DateTime();
  5207.         $minutes_to_add = 10;
  5208.         $date->add(new DateInterval('PT' . $minutes_to_add . 'M'));
  5209.         $date->setTimezone(new DateTimeZone('Europe/Paris'));
  5210.         $currentDate = $date->format('Y-m-d H:i:00');
  5211.         $toSend = $this->getDoctrine()->getRepository(Rdv::class)
  5212.             ->findRdvsIn10Mins($currentDate); 
  5213.         */
  5214.     }
  5215.     /**
  5216.      * @Route("/rdvs/facturation/lead", name="getMyLead", methods={"GET"})
  5217.      */
  5218.     public function getMyLead(Request $request): Response {}
  5219.     /**
  5220.      * @Route("/rdvs/total-count", name="getRdvCount", methods={"GET"})
  5221.      */
  5222.     public function getRdvCount(Request $request): Response
  5223.     {
  5224.         $rdvs $this->getDoctrine()->getRepository(Rdv::class)->findAll();
  5225.         return new Response(count($rdvs));
  5226.     }
  5227.     /**
  5228.      * @Route("/admin/update-relance/{id}", name="admin_update_relance", methods={"POST"})
  5229.      */
  5230.     public function updateRelance(Request $requestLeadRdv $leadEntityManagerInterface $em): JsonResponse
  5231.     {
  5232.         $data json_decode($request->getContent(), true);
  5233.         $relanceCount $data['relanceCount'] ?? null;
  5234.         if ($relanceCount !== null) {
  5235.             $lead->setRelanceCallCount((int)$relanceCount);
  5236.             $em->flush();
  5237.             return new JsonResponse(['success' => true]);
  5238.         }
  5239.         return new JsonResponse(['success' => false], 400);
  5240.     }
  5241.     /**
  5242.      * @Route("/rdv/lead", name="postLeadRdv", methods={"POST"})
  5243.      */
  5244.     public function postLeadRdv(Request $requestEntityManagerInterface $entityManagerPublicFunction $publicFunctionGoogleCalendarService $googleCalendar): Response
  5245.     {
  5246.         $data json_decode($request->getContent(), true);
  5247.         $today = new DateTime();
  5248.         try {
  5249.             $client null;
  5250.             // Gestion du client via token ou création
  5251.             if (!empty($data['clientToken'])) {
  5252.                 $token $entityManager->getRepository(Token::class)->findOneBy(['token' => $data['clientToken']]);
  5253.                 $client $token $token->getIdClient() : null;
  5254.             } elseif (!empty($data['client'])) {
  5255.                 $clientData $this->createOrGetClient($data['client']);
  5256.                 $client $entityManager->getRepository(Client::class)->find($clientData['id']);
  5257.             }
  5258.             if (!$client) {
  5259.                 return $this->json(["status" => 400"message" => "Client non trouvé ou invalide"], 400);
  5260.             }
  5261.             // Création du rendez-vous LeadRdv
  5262.             $rdvLead = new LeadRdv();
  5263.             $rdvLead->setClient($client);
  5264.             if (isset($data['titleLead'])) {
  5265.                 $rdvLead->setTitleLead($data['titleLead']);
  5266.             }
  5267.             if (isset($data['rangeAge'])) {
  5268.                 $rdvLead->setRangeAge($data['rangeAge']);
  5269.             }
  5270.             if (isset($data['situations'])) {
  5271.                 $rdvLead->setSituationsGene($data['situations']);
  5272.             }
  5273.             if (isset($data['equipe'])) {
  5274.                 $rdvLead->setEquipeAppareil($data['equipe']);
  5275.             }
  5276.             if (isset($data['durationEquipe'])) {
  5277.                 $rdvLead->setDurationEquipeAppareil($data['durationEquipe']);
  5278.             }
  5279.             if (isset($data['bilanAuditif'])) {
  5280.                 $rdvLead->setBilanAuditif($data['bilanAuditif']);
  5281.             }
  5282.             if (isset($data['ordonance'])) {
  5283.                 $rdvLead->setOrdonance($data['ordonance']);
  5284.             }
  5285.             if (isset($data['dateOrdonance'])) {
  5286.                 $rdvLead->setDateOrdonance($data['dateOrdonance']);
  5287.             }
  5288.             if (isset($data['canMove'])) {
  5289.                 $rdvLead->setCanMove($data['canMove']);
  5290.             }
  5291.             if (isset($data['traffic_source'])) {
  5292.                 $rdvLead->setTrafficSource($data['traffic_source']);
  5293.             }
  5294.             if (isset($data['article_name'])) {
  5295.                 $rdvLead->setTrafficLpVersion($data['article_name']);
  5296.             }
  5297.             if (isset($data['lp_version'])) {
  5298.                 $rdvLead->setTrafficArticleName($data['lp_version']);
  5299.             }
  5300.             if (isset($data['isNewLp'])) {
  5301.                 $rdvLead->setIsNewLp($data['isNewLp']);
  5302.                 $leadStatus $entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'demande_contact']);
  5303.                 if ($leadStatus) {
  5304.                     $rdvLead->setLeadStatus($leadStatus);
  5305.                 }
  5306.             }
  5307.             $rdvLead->setDate($today);
  5308.             if (!empty($data['audio'])) {
  5309.                 $audio $entityManager->getRepository(Audio::class)->find($data['audio']);
  5310.                 if ($audio) {
  5311.                     $rdvLead->setAudio($audio);
  5312.                 }
  5313.             }
  5314.             if ($client->getPostal()) {
  5315.                 $centerCount $this->getMatchingCentresCount($client->getPostal());
  5316.                 $rdvLead->setCentersCount($centerCount);
  5317.                 if ($centerCount == 0) {
  5318.                     $leadStatus $entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'hors_zone']);
  5319.                     if ($leadStatus) {
  5320.                         $rdvLead->setLeadStatus($leadStatus);
  5321.                     }
  5322.                 }
  5323.             }
  5324.             // Création du Token
  5325.             $tokenString $publicFunction->generateRandomString(30);
  5326.             $token = (new Token())
  5327.                 ->setCreationDate(new DateTime())
  5328.                 ->setToken($tokenString)
  5329.                 ->setIdClient($client);
  5330.             $entityManager->persist($rdvLead);
  5331.             $entityManager->persist($token);
  5332.             $entityManager->flush();
  5333.             return $this->json([
  5334.                 "id" => $client->getId(),
  5335.                 "idRdvLead" => $rdvLead->getId(),
  5336.                 "name" => $client->getName(),
  5337.                 "lastname" => $client->getLastname(),
  5338.                 "token" => $tokenString,
  5339.                 "code" => $clientData['password'],
  5340.                 "postalCode" => $client->getPostal() ?? null,
  5341.                 "status" => 200,
  5342.             ]);
  5343.         } catch (\Exception $e) {
  5344.             return $this->json(["status" => 500"message" => $e->getMessage()], 500);
  5345.         }
  5346.     }
  5347.     /**
  5348.      * @Route("/testGenerateVoice", name="testGenerateVoice", methods={"GET"})
  5349.      */
  5350.     public function testGenerateVoice(AppointmentCallService $service): Response
  5351.     {
  5352.         $rdv $this->entityManager->getRepository(Rdv::class)->find(6653);
  5353.         $lead $this->entityManager->getRepository(LeadRdv::class)->find(496);
  5354.         // $service->handleCallCenterAfterRdv(
  5355.         //     $rdv
  5356.         // );
  5357.         // $service->handleReminderCallToPatient(
  5358.         //     $rdv
  5359.         // );
  5360.         // $service->handleReminderCallToPatientOneHourBefore(
  5361.         //     $rdv
  5362.         // );
  5363.         // $service->handleCallToPatientAfterRdv(
  5364.         //     $rdv
  5365.         // );
  5366.         // $service->handleFollowupCall15Days($rdv);
  5367.         $service->handleNewLeadCall($lead"+33743393532");
  5368.         // $service->handleFollowupCall31Days($rdv);
  5369.         return new Response(json_encode([
  5370.             "status" => 200,
  5371.         ]), 200, ['Content-Type' => 'application/json']);
  5372.     }
  5373.     /**
  5374.      * Private method to create a new client or get existing one by phone
  5375.      */
  5376.     private function createOrGetClient(array $data): array
  5377.     {
  5378.         $clientRepository $this->entityManager->getRepository(Client::class);
  5379.         // check sur le mail et phone
  5380.         $existingClient $clientRepository->findOneBy(['mail' => $data['email']]);
  5381.         if ($existingClient) {
  5382.             if ($existingClient->getPostal() !== $data['postalCode']) {
  5383.                 $existingClient->setPostal($data['postalCode']);
  5384.                 $this->entityManager->persist($existingClient);
  5385.                 $this->entityManager->flush();
  5386.             }
  5387.             return ['id' => $existingClient->getId(), 'password' => 'Votre mot de passe'];
  5388.         }
  5389.         $randomPassword $this->generateRandomPassword(12);
  5390.         $client = new Client();
  5391.         $client->setLastname($data['lastname']);
  5392.         $client->setBirthdate(null);
  5393.         $client->setName($data['firstname']);
  5394.         $client->setPhone($data['phone']);
  5395.         $client->setMail($data['email']);
  5396.         $client->setSignupDate(new \DateTime());
  5397.         $client->setPassword(password_hash($randomPasswordPASSWORD_DEFAULT));
  5398.         $client->setPostal($data['postalCode']);
  5399.         $client->setAddress($data['address'] ?? null);
  5400.         $client->setCity($data['city'] ?? null);
  5401.         $client->setDesactivate(false);
  5402.         if (isset($data['civilite'])) {
  5403.             $civilite = ($data['civilite'] === 'Homme') ? 'Monsieur' 'Madame';
  5404.             $client->setCivilite($civilite);
  5405.         }
  5406.         $this->entityManager->persist($client);
  5407.         $this->entityManager->flush();
  5408.         return ['id' => $client->getId(), 'password' => $randomPassword];
  5409.     }
  5410.     private function generateRandomPassword($length 10): string
  5411.     {
  5412.         return bin2hex(random_bytes($length 2));
  5413.     }
  5414.     private function getMatchingCentresCount($clientPostal): int
  5415.     {
  5416.         // Récupérer les coordonnées GPS du code postal du client
  5417.         $clientCoordinates $this->entityManager
  5418.             ->getRepository(RegionDepartment::class)
  5419.             ->findOneBy(['codePostal' => $clientPostal]);
  5420.         $clientLat $clientCoordinates $clientCoordinates->getLatitude() : null;
  5421.         $clientLon $clientCoordinates $clientCoordinates->getLongitude() : null;
  5422.         $centres $this->entityManager->getRepository(Centre::class)->findAll();
  5423.         $count 0;
  5424.         foreach ($centres as $centre) {
  5425.             if ($centre->getZoneKm()) {
  5426.                 $latitude $centre->getLatitude();
  5427.                 $longitude $centre->getLongitude();
  5428.                 $radius $centre->getZoneKm();
  5429.                 $postals $this->entityManager->getRepository(RegionDepartment::class)->findPostalsWithinRadius($latitude$longitude$radius);
  5430.                 $postalCodes array_values(array_unique(array_column($postals'code_postal')));
  5431.                 if (in_array($clientPostal$postalCodes)) {
  5432.                     $count++;
  5433.                 }
  5434.             }
  5435.         }
  5436.         return $count;
  5437.     }
  5438.     /**
  5439.      * @Route("/rdv/send-map", name="getRdvMap", methods={"POST"})
  5440.      */
  5441.     public function sendEmailWithMap(Request $requestPublicFunction $publicFunction): Response
  5442.     {
  5443.         $data json_decode($request->getContent(), true);
  5444.         $mail "";
  5445.         $name "";
  5446.         $centre "";
  5447.         if (isset($data['clientToken'])) {
  5448.             $token $this->getDoctrine()->getRepository(Token::class)->findOneBy(['token' => $data['clientToken']]);
  5449.             $client $token->getIdClient();
  5450.             $mail $client->getMail();
  5451.             $name $client->getLastname() . " " $client->getName();
  5452.             $centre $this->getDoctrine()->getRepository(Centre::class)->findOneBy(['id' => $data['centre']['id']]);
  5453.         } else {
  5454.             $mail $data['email'];
  5455.             $name $data['name'];
  5456.         }
  5457.         $locale 'fr_FR';
  5458.         $dateTime DateTime::createFromFormat('d/m/Y H:i'$data['date']);
  5459.         if ($dateTime) {
  5460.             $fmt = new IntlDateFormatter($localeIntlDateFormatter::FULLIntlDateFormatter::NONE);
  5461.             $fmt->setPattern("EEEE dd MMMM");
  5462.             $formattedDate ucfirst($fmt->format($dateTime));
  5463.         } else {
  5464.             $formattedDate "Date invalide";
  5465.         }
  5466.         $params = [
  5467.             'date' => $data['date'],
  5468.             'time' => $data['time'],
  5469.             'frenchDate' => $formattedDate,
  5470.             'clientAddress' => $data['address'],
  5471.             'centerName' => $centre->getName(),
  5472.             'centerAddress' => $centre->getAddress(),
  5473.             'centerPostal' => $centre->getPostale(),
  5474.             'centerCity' => $centre->getCity(),
  5475.             'start' => $data['start'],
  5476.             'end' => $data['end'],
  5477.             'urlApi' => "{$_ENV['BASE_client']}",
  5478.         ];
  5479.         $publicFunction->sendEmail($params$mail$name"Votre Rendez-vous My Audio"198);
  5480.         return new Response(json_encode([
  5481.             "status" => 200,
  5482.             "params" => $params,
  5483.         ]), 200, ['Content-Type' => 'application/json']);
  5484.     }
  5485.     /**
  5486.      * @Route("/rdv/cantmove", name="notifCantMove", methods={"POST"})
  5487.      */
  5488.     public function notifCantMove(Request $requestPublicFunction $publicFunction): Response
  5489.     {
  5490.         $data json_decode($request->getContent(), true);
  5491.         $email "lead.myaudio@gmail.com";
  5492.         $centre "";
  5493.         $type "My Audio";
  5494.         $details "";
  5495.         $picto "❌";
  5496.         $ordo "sans ordo";
  5497.         $subject "";
  5498.         if (isset($data['ordonance'])) {
  5499.             if ($data["ordonance"] == "oui") {
  5500.                 $ordo "avec ordo";
  5501.             }
  5502.         } else {
  5503.             $ordo "";
  5504.         }
  5505.         if (isset($data['centre'])) {
  5506.             $centre $data['centre'];
  5507.             $subject $picto " Lead - demande de contact ne pouvant pas se déplacer " $data['postal'] . " " $ordo;
  5508.         } else {
  5509.             $centre "";
  5510.             $type "Hors Zone";
  5511.             $details "Pas de centre dans la zone";
  5512.             $subject $picto " Lead Hors Zone " $data['postal'] . " " $ordo " ne pouvant pas se déplacer";
  5513.         }
  5514.         $responses = [
  5515.             'rangeAge' => isset($data['rangeAge']) ? $data['rangeAge'] : null,
  5516.             'situations' => isset($data['situations']) ? $data['situations'] : null,
  5517.             'equipeAppareil' => isset($data['equipe']) ? $data['equipe'] : null,
  5518.             'durationEquipe' => isset($data['durationEquipe']) ? $data['durationEquipe'] : null,
  5519.             'bilanAuditif' => isset($data['bilanAuditif']) ? $data['bilanAuditif'] : null,
  5520.             'ordonance' => isset($data['ordonance']) ? $data['ordonance'] : null,
  5521.             'dateOrdonance' => isset($data['dateOrdonance']) ? $data['dateOrdonance'] : null,
  5522.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  5523.         ];
  5524.         $department $this->getDepartmentFromPostalCode($data['address']);
  5525.         $data['departmentCode'] = $department['departmentCode'];
  5526.         $data['departmentName'] = $department['departmentName'];
  5527.         $data['regionName'] = $department['regionName'];
  5528.         $data['city'] = $department['city'];
  5529.         $params = [
  5530.             'date' => $data['date'],
  5531.             'time' => $data['time'],
  5532.             'address' => $data['address'],
  5533.             'centre' => $centre,
  5534.             'type' => $type,
  5535.             'details' => $details,
  5536.             'responses' => $responses,
  5537.             'name' => $data['name'],
  5538.             'civilite' => $data['civilite'],
  5539.             'nom' => $data['firstname'],
  5540.             'prenom' => $data['lastname'],
  5541.             'codePostal' => $data['address'],
  5542.             'telephone' => $data['phone'],
  5543.             'email' => $data['email'],
  5544.             'departement' => $data['departmentName'],
  5545.             'ville' => $data['city'],
  5546.             'region' => $data['regionName'],
  5547.             'trangeAge' => isset($data['rangAge']) ? $data['rangAge'] : null,
  5548.             'situationVecu' => isset($data['situations']) ? implode(', '$data['situations']) : null,
  5549.             'dejaEquipe' => isset($data['equipeAppareil']) ? $data['equipeAppareil'] : null,
  5550.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  5551.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  5552.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  5553.         ];
  5554.         $publicFunction->sendEmail($params$email$data['name'], $subject208);
  5555.         return new Response(json_encode([
  5556.             "status" => 200,
  5557.         ]), 200, ['Content-Type' => 'application/json']);
  5558.     }
  5559.     /**
  5560.      * @Route("/rdv/cantmove/v2", name="notifCantMoveV2", methods={"POST"})
  5561.      */
  5562.     public function notifCantMoveV2(Request $requestPublicFunction $publicFunction): Response
  5563.     {
  5564.         $data json_decode($request->getContent(), true);
  5565.         $email "lead.myaudio@gmail.com";
  5566.         $centre "";
  5567.         $type "My Audio";
  5568.         $details "";
  5569.         $picto "❌";
  5570.         $subject "";
  5571.         $audio "";
  5572.         $subject $picto " Lead ne pouvant pas se déplacer";
  5573.         $department $this->getDepartmentFromPostalCode($data['address']);
  5574.         $data['departmentCode'] = $department['departmentCode'];
  5575.         $data['departmentName'] = $department['departmentName'];
  5576.         $data['regionName'] = $department['regionName'];
  5577.         $data['city'] = $department['city'];
  5578.         $password "";
  5579.         $params = [
  5580.             'name' => $data['name'],
  5581.             'civilite' => $data['civilite'],
  5582.             'nom' => $data['firstname'],
  5583.             'prenom' => $data['lastname'],
  5584.             'codePostal' => $data['address'],
  5585.             'telephone' => $data['phone'],
  5586.             'email' => $data['email'],
  5587.             'password' => $data['clientSecretCookie'],
  5588.             'trancheAge' => isset($data['rangAge']) ? $data['rangAge'] : null,
  5589.             'situationVecu' => isset($data['situations']) ? implode(', '$data['situations']) : null,
  5590.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  5591.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  5592.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  5593.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  5594.             'urlLogin' => "{$_ENV['BASE_client']}login"
  5595.         ];
  5596.         // Send email to MyAudio
  5597.         $publicFunction->sendEmail($params$email$data['name'], $subject220);
  5598.         $publicFunction->sendEmail($params'contact@myaudio.fr'$data['name'], $subject220);
  5599.         // Send email to patient
  5600.         $params = [
  5601.             'clientEmail' => $data['email'],
  5602.             'clientPassword' => $data['clientSecretCookie'],
  5603.             'rdv' => "https://www.myaudio.fr/search",
  5604.             'urlLogin' => "{$_ENV['BASE_client']}login"
  5605.         ];
  5606.         $publicFunction->sendEmail($params$data['email'], $data['name'], 'Rendez-vous My Audio - En cours de traitement'219);
  5607.         $rdvLead $this->entityManager->getRepository(LeadRdv::class)->find($data['clientRdvLp']);
  5608.         if ($rdvLead) {
  5609.             $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'cant_move']);
  5610.             if ($leadStatus) {
  5611.                 $rdvLead->setLeadStatus($leadStatus);
  5612.                 $this->entityManager->flush();
  5613.             }
  5614.         }
  5615.         return new Response(json_encode([
  5616.             "status" => 200,
  5617.         ]), 200, ['Content-Type' => 'application/json']);
  5618.     }
  5619.     /**
  5620.      * @Route("/rdv/notiflead", name="notifLead", methods={"POST"})
  5621.      */
  5622.     public function notifLeadRdv(Request $requestPublicFunction $publicFunction): Response
  5623.     {
  5624.         $data json_decode($request->getContent(), true);
  5625.         $email "lead.myaudio@gmail.com";
  5626.         $centre "";
  5627.         $type "My Audio";
  5628.         $details "";
  5629.         $picto "❌";
  5630.         $ordo "sans ordo";
  5631.         $subject "";
  5632.         $name "";
  5633.         $postal "";
  5634.         $emailPatient "";
  5635.         if (isset($data['clientToken']) && !empty($data['clientToken'])) {
  5636.             $token $this->getDoctrine()->getRepository(Token::class)->findOneBy(['token' => $data['clientToken']]);
  5637.             $client $token->getIdClient();
  5638.             $name $client->getLastname() . " " $client->getName();
  5639.             $postal $client->getPostal();
  5640.             $emailPatient $client->getMail();
  5641.         } else {
  5642.             if (isset($data['postal'])) {
  5643.                 $postal $data['postal'];
  5644.             }
  5645.             if (isset($data['name'])) {
  5646.                 $name $data['name'];
  5647.             }
  5648.             if (isset($data['email'])) {
  5649.                 $email $data['email'];
  5650.             }
  5651.             if (isset($data['email'])) {
  5652.                 $emailPatient $data['email'];
  5653.             }
  5654.         }
  5655.         if (isset($data["ordonance"])) {
  5656.             if ($data["ordonance"] == "oui") {
  5657.                 $ordo "avec ordo";
  5658.             }
  5659.         }
  5660.         if (isset($data['centre'])) {
  5661.             $centre $data['centre'];
  5662.             $picto "✅";
  5663.             $subject $picto " Lead booké " $postal " " $ordo;
  5664.         } else {
  5665.             $centre "";
  5666.             $type "Hors Zone";
  5667.             $details "Pas de centre dans la zone";
  5668.             $subject $picto " Lead Hors Zone " $postal " " $ordo;
  5669.         }
  5670.         $responses = [
  5671.             'rangeAge' => isset($data['rangeAge']) ? $data['rangeAge'] : null,
  5672.             'situations' => isset($data['situations']) ? $data['situations'] : null,
  5673.             'equipeAppareil' => isset($data['equipe']) ? $data['equipe'] : null,
  5674.             'durationEquipe' => isset($data['durationEquipe']) ? $data['durationEquipe'] : null,
  5675.             'bilanAuditif' => isset($data['bilanAuditif']) ? $data['bilanAuditif'] : null,
  5676.             'ordonance' => isset($data['ordonance']) ? $data['ordonance'] : null,
  5677.             'dateOrdonance' => isset($data['dateOrdonance']) ? $data['dateOrdonance'] : null,
  5678.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  5679.         ];
  5680.         $params = [
  5681.             'date' => $data['date'],
  5682.             'time' => $data['time'],
  5683.             'address' => $data['address'],
  5684.             'centre' => $centre,
  5685.             'type' => $type,
  5686.             'details' => $details,
  5687.             'responses' => $responses,
  5688.             'name' => $name,
  5689.             'email' => $emailPatient,
  5690.         ];
  5691.         $publicFunction->sendEmail($params$email$name$subject180);
  5692.         return new Response(json_encode([
  5693.             "status" => 200,
  5694.             "params" => $params,
  5695.             "responses" => $responses
  5696.         ]), 200, ['Content-Type' => 'application/json']);
  5697.     }
  5698.     /**
  5699.      *  Met à jour l'état d'un rendez-vous.
  5700.      *
  5701.      * Cette fonction permet de modifier l'état d'un rendez-vous en fonction des données envoyées
  5702.      * via une requête PUT. Elle effectue plusieurs vérifications, notamment :
  5703.      * - La présence et la validité du token d'authentification.
  5704.      * - L'existence du rendez-vous et du nouvel état.
  5705.      * - L'expiration du token (plus de 7 jours).
  5706.      * 
  5707.      * Si le rendez-vous est marqué comme "Absence injustifiée" (état ID 3), un email et un SMS sont envoyés
  5708.      * au client et à l'équipe MyAudio pour les informer.
  5709.      * 
  5710.      * @Route("api/save-etat-rdv", name="saveEtatRdv", methods={"PUT"})
  5711.      */
  5712.     public function saveEtatRdv(Request $requestPublicFunction $publicFunction): Response
  5713.     {
  5714.         $entityManager $this->getDoctrine()->getManager();
  5715.         $data json_decode($request->getContent(), true);
  5716.         if (!$data['token']) {
  5717.             return new Response(json_encode([
  5718.                 "message" => "Pas de token n'a été spécifié",
  5719.                 "status" => 401,
  5720.             ]), 401);
  5721.         }
  5722.         /** @var Token */
  5723.         $token $this->getDoctrine()
  5724.             ->getRepository(Token::class)
  5725.             ->findOneBy(['token' => $data['token'], 'id_audio' => $data['audio']]);
  5726.         if (!$token) {
  5727.             return new Response(json_encode([
  5728.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  5729.                 "status" => 404,
  5730.             ]), 404);
  5731.         }
  5732.         // get token age
  5733.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  5734.         // if the token if older than 7 days
  5735.         if ($dateDiff->7) {
  5736.             $entityManager->remove($token);
  5737.             $entityManager->flush();
  5738.             return $this->json([
  5739.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  5740.                 'path' => 'src/Controller/ClientController.php',
  5741.                 "status" => 401,
  5742.             ], 401);
  5743.         }
  5744.         $rdv $this->getDoctrine()->getRepository(Rdv::class)->find($data['rdv']);
  5745.         if (!$rdv) {
  5746.             return new Response(json_encode([
  5747.                 "message" => "Rdv not found.",
  5748.                 "status" => 404,
  5749.             ]), 404);
  5750.         }
  5751.         $rdvEtat $this->getDoctrine()
  5752.             ->getRepository(EtatRdv::class)
  5753.             ->find($data['etat']);
  5754.         if (!$rdvEtat) {
  5755.             return new Response(json_encode([
  5756.                 "message" => "Rdv etat not found.",
  5757.                 "status" => 404,
  5758.             ]), 404);
  5759.         }
  5760.         $rdv->setIdEtat($rdvEtat);
  5761.         $entityManager->flush();
  5762.         $encodedNomDuCentre rawurlencode($rdv->getIdCentre()->getName());
  5763.         $urlApi "audioprothesiste/{$rdv->getIdCentre()->getCity()}/{$rdv->getIdCentre()->getPostale()}/{$encodedNomDuCentre}/prise-de-rdvaudioprothesiste-rapide/{$rdv->getIdCentre()->getId()}";
  5764.         if ($rdvEtat->getId() == 3) {
  5765.             // Send email to client
  5766.             $date $rdv->getDate();
  5767.             $smsDate $date->format('d-m-Y H:i');
  5768.             $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  5769.             $params = array(
  5770.                 "date" => substr($smsDate010),
  5771.                 "lien" => "{$_ENV['BASE_client']}$urlApi,
  5772.                 "heure" => substr($smsDate1115),
  5773.                 'centerName' => $rdv->getIdCentre()->getName() ?? '',
  5774.                 'centerPostal' => $rdv->getIdCentre()->getPostale() ?? '',
  5775.                 'centerCity' => $rdv->getIdCentre()->getCity() ?? '',
  5776.                 'centerAddress' => $rdv->getIdCentre()->getAddress() ?? '',
  5777.                 'centerPhone' => $rdv->getIdCentre()->getPhone() ?? '',
  5778.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName() ?? '',
  5779.                 'audioMail' => $rdv->getIdAudio()->getMail() ?? '',
  5780.             );
  5781.             $subject "Vous avez manqué votre rendez-vous MyAudio avec " $rdv->getIdCentre()->getName();
  5782.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject214);
  5783.             // Send sms to client
  5784.             $sms "Vous avez manqué un RDV My Audio le " substr($smsDate010) . " à " substr($smsDate1115) . " dans votre centre auditif. Contactez le centre dès que possible : " $rdv->getIdCentre()->getPhone();
  5785.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  5786.             // Send email to MyAudio
  5787.             $date $rdv->getDate();
  5788.             $smsDate $date->format('d-m-Y H:i');
  5789.             $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  5790.             $params = array(
  5791.                 "date" => substr($smsDate010),
  5792.                 "lien" => "{$_ENV['BASE_client']}search",
  5793.                 "heure" => substr($smsDate1115),
  5794.                 'centerName' => $rdv->getIdCentre()->getName() ?? '',
  5795.                 'centerPostal' => $rdv->getIdCentre()->getPostale() ?? '',
  5796.                 'centerCity' => $rdv->getIdCentre()->getCity() ?? '',
  5797.                 'centerAddress' => $rdv->getIdCentre()->getAddress() ?? '',
  5798.                 'centerPhone' => $rdv->getIdCentre()->getPhone() ?? '',
  5799.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName() ?? '',
  5800.                 'audioMail' => $rdv->getIdAudio()->getMail() ?? '',
  5801.                 'clientName' => $client->getName() . ' ' $client->getLastName() ?? '',
  5802.                 'clientMail' => $client->getMail() ?? '',
  5803.                 'clientPhone' => $client->getPhone() ?? '',
  5804.             );
  5805.             $subject "Le patient " $client->getName() . ' ' $client->getLastName() . " a manqué son rendez-vous MyAudio avec le centre " $rdv->getIdCentre()->getName();
  5806.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$client->getName() . ' ' $client->getLastName(), $subject215);
  5807.         }
  5808.         return new Response(json_encode([
  5809.             "message" => "rdvEtat has been successfully updated",
  5810.             "status" => 200,
  5811.         ]));
  5812.     }
  5813.     /**
  5814.      * 
  5815.      * @Route("api/send-email/clientnotcompletebook", name="askToContact", methods={"POST"})
  5816.      */
  5817.     public function askToContact(Request $requestPublicFunction $publicFunction): Response
  5818.     {
  5819.         $data json_decode($request->getContent(), true);
  5820.         $staticToken "3f3a8b74f3e5b2d0c4917f5f9a7c07efb1a0f1e5e8c907ec9c4e9df129e3125e9";
  5821.         $token $data['token'] ?? null;
  5822.         if ($token !== $staticToken) {
  5823.             return new JsonResponse(
  5824.                 [
  5825.                     'status' => 'error',
  5826.                     'code' => 'unauthorized',
  5827.                     'message' => 'Unauthorized access.'
  5828.                 ],
  5829.                 JsonResponse::HTTP_UNAUTHORIZED
  5830.             );
  5831.         }
  5832.         $params = [
  5833.             'clientCivilite' => isset($data['civilite']) ? $data['civilite'] : 'Pas indiqué',
  5834.             'clientNom' => isset($data['firstname']) ? $data['firstname'] : null,
  5835.             'clientPrenom' => isset($data['lastname']) ? $data['lastname'] : null,
  5836.             'clientPostal' => isset($data['postalCode']) ? $data['postalCode'] : null,
  5837.             'clientPhone' => isset($data['phone']) ? $data['phone'] : null,
  5838.             'clientMail' => isset($data['email']) ? $data['email'] : null,
  5839.             'password' => isset($data['clientSecretCookie']) ? $data['clientSecretCookie'] : null,
  5840.             'rangeAge' => isset($data['trancheAge']) ? $data['trancheAge'] : null,
  5841.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  5842.             'situations' => isset($data['situations']) ? implode(', '$data['situations']) : null,
  5843.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  5844.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  5845.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  5846.         ];
  5847.         $templateEmailMyAudio 223;
  5848.         if (!empty($data['centre'])) {
  5849.             $centre $data['centre'];
  5850.             $audio $centre['audio'][0];
  5851.             $params['centerName'] = $centre['name'] ?? null;
  5852.             $params['centerPostal'] = $centre['postale'] ?? null;
  5853.             $params['centerCity'] = $centre['city'] ?? null;
  5854.             $params['centerAddress'] = $centre['address'] ?? null;
  5855.             $params['centerPhone'] = $centre['phone'] ?? null;
  5856.             $params['audioproName'] = $audio['civilite'] . ' ' $audio['lastname'] . ' ' $audio['name'] ?? null;
  5857.             $templateEmailMyAudio 222;
  5858.         }
  5859.         // Email to My Audio
  5860.         $email "lead.myaudio@gmail.com";
  5861.         $subject "Demande de contact -  Nouveau Lead À Contacter Hors Zone";
  5862.         $publicFunction->sendEmail($params$email$data['name'], $subject$templateEmailMyAudio);
  5863.         $publicFunction->sendEmail($params'contact@myaudio.fr'$data['name'], $subject$templateEmailMyAudio);
  5864.         $coordinates $this->getCoordinatesFromPostalCode($data['postalCode']);
  5865.         $latitude $coordinates['latitude'];
  5866.         $longitude $coordinates['longitude'];
  5867.         $params = [
  5868.             'email' => isset($data['email']) ? $data['email'] : null,
  5869.             'password' => isset($data['clientSecretCookie']) ? $data['clientSecretCookie'] : null,
  5870.             "lienRdv" => "{$_ENV['BASE_client']}search?latitude={$latitude}&longitude={$longitude}&ville={$data['postalCode']}",
  5871.         ];
  5872.         // Email to Client
  5873.         $subject "My Audio - Confirmation de demande de contact";
  5874.         $publicFunction->sendEmail($params$data['email'], $data['name'], $subject221);
  5875.         $sms "Votre demande validée ! Un spécialiste vous répondra rapidement et vous orientera vers un centre auditif proche. Contactez-nous au 01.89.71.61.09";
  5876.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$data['phone']);
  5877.         if (isset($data['clientRdvLp'])) {
  5878.             $rdvLead $this->entityManager->getRepository(LeadRdv::class)->find($data['clientRdvLp']);
  5879.             if ($rdvLead) {
  5880.                 $rdvLead->setSendAskToContact(1);
  5881.                 $rdvLead->setCountAskToContact(($rdvLead->getCountAskToContact() ?? 0) + 1);
  5882.                 $this->entityManager->flush();
  5883.                 $this->sendWhatsApp($data$rdvLead);
  5884.             }
  5885.         }
  5886.         return new Response(json_encode([
  5887.             "message" => "Email ask for contact send with success",
  5888.             "status" => 200,
  5889.         ]));
  5890.     }
  5891.     private function sendWhatsApp($data$lead): void
  5892.     {
  5893.         $adminUrl $this->adminUrlGenerator
  5894.             ->setDashboard(DashboardController::class)
  5895.             ->setController(LeadRdvCrudController::class)
  5896.             ->setAction('detail')
  5897.             ->setEntityId($lead->getId())
  5898.             ->generateUrl();
  5899.         $relativeUrl parse_url($adminUrlPHP_URL_PATH) . '?' parse_url($adminUrlPHP_URL_QUERY);
  5900.         // Supprimer le slash en trop s’il y en a un au début
  5901.         $relativeUrl ltrim($relativeUrl'/');
  5902.         // 🧑‍🤝‍🧑 Tableau des destinataires
  5903.         $destinataires = [
  5904.             '33611879183'// Numéro 1
  5905.             '33667597626'// Numéro 2
  5906.             '447884128220'// Numéro 3
  5907.         ];
  5908.         foreach ($destinataires as $numero) {
  5909.             $this->whatsapp->sendTemplateMessage(
  5910.                 $numero,  // Numéro de téléphone du destinataire
  5911.                 'lead_notif_myaudio',  // Nom du template WhatsApp
  5912.                 [
  5913.                     'body' => [
  5914.                         ['parameter_name' => 'nom_client''text' => $data['firstname'] . ' ' $data['lastname']],  // {{nom_client}}
  5915.                         ['parameter_name' => 'email_client''text' => $data['email'] ?? ' '],  // {{email_client}}
  5916.                         ['parameter_name' => 'telephone_client''text' => $data['phone'] ?? ' '],  // {{telephone_client}}
  5917.                         ['parameter_name' => 'date_lead''text' => $lead->getDate()->format('d/m/Y H:i')],  // {{date_lead}}
  5918.                         ['parameter_name' => 'code_postal''text' => $data['postalCode'] ?? ' '],  // {{code_postal}}
  5919.                         ['parameter_name' => 'nombre_centres''text' => $lead->getCentersCount() ?? '0'],  // {{nombre_centres}}
  5920.                     ],
  5921.                     'button' => $relativeUrl,  // <--- seulement le chemin dynamique
  5922.                 ]
  5923.             );
  5924.         }
  5925.     }
  5926.     /**
  5927.      * Get coordinates from the postal code using the database.
  5928.      */
  5929.     private function getCoordinatesFromPostalCode(string $postalCode): array
  5930.     {
  5931.         $region $this->entityManager
  5932.             ->getRepository(RegionDepartment::class)
  5933.             ->findOneBy(['codePostal' => $postalCode]);
  5934.         if ($region) {
  5935.             return [
  5936.                 'latitude' => $region->getLatitude(),
  5937.                 'longitude' => $region->getLongitude(),
  5938.             ];
  5939.         }
  5940.         return [
  5941.             'latitude' => null,
  5942.             'longitude' => null,
  5943.         ];
  5944.     }
  5945.     /**
  5946.      * Get the department code from the code postal
  5947.      */
  5948.     private function getDepartmentFromPostalCode(string $postalCode): ?array
  5949.     {
  5950.         $region $this->entityManager
  5951.             ->getRepository(RegionDepartment::class)
  5952.             ->findOneBy(['codePostal' => $postalCode]);
  5953.         if ($region) {
  5954.             return [
  5955.                 'departmentCode' => $region->getCodeDepartement(),
  5956.                 'departmentName' => $region->getNomDepartement(),
  5957.                 'regionCode' => $region->getCodeRegion(),
  5958.                 'regionName' => $region->getNomRegion(),
  5959.                 'city' => $region->getNomCommunePostal(),
  5960.             ];
  5961.         }
  5962.         return null;
  5963.     }
  5964.     /**
  5965.      * 
  5966.      * @Route("/giuili-admin/lead/{leadId}/centre/{centreId}", name="showLeadCentre", methods={"GET"})
  5967.      */
  5968.     public function showLeadCentre(int $leadIdCentre $centreId): Response
  5969.     {
  5970.         // dd("tets");
  5971.         $center $centres $this->getDoctrine()
  5972.             ->getRepository(AudioCentre::class)
  5973.             ->findOneBy(['id_centre' => $centreId->getId()]);
  5974.         $audio $center->getIdAudio();
  5975.         $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  5976.             ->findBy(['id_audio' => $audio'isDeleted' => 0]);
  5977.         return $this->render('easyadmin/leadRdv/centre_show.html.twig', [
  5978.             'audio' => $audio,
  5979.             'leadId' => $leadId,
  5980.             'centreId' => $centreId,
  5981.             'motifs' => $motifs,
  5982.         ]);
  5983.     }
  5984.     /**
  5985.      * @Route("/rdv-easyadmin", name="postRdvEasyAdmin", methods={"POST"})
  5986.      */
  5987.     public function postRdvEasyAdmin(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSmsAppointmentCallService $Callservice): Response
  5988.     {
  5989.         $data json_decode($request->getContent(), true);
  5990.         $entityManager $this->getDoctrine()->getManager();
  5991.         $audio $this->getDoctrine()
  5992.             ->getRepository(Audio::class)
  5993.             ->findOneBy(['id' => $data["audio_id"]]);
  5994.         $leadRdv =   $this->getDoctrine()->getRepository(LeadRdv::class)
  5995.             ->find($data["lead_id"]);
  5996.         $client $this->getDoctrine()->getRepository(Client::class)
  5997.             ->find($leadRdv->getClient());
  5998.         $responses = [
  5999.             'rangeAge' => $leadRdv->getRangeAge(),
  6000.             'situations' =>  implode(", "$leadRdv->getSituationsGene()),
  6001.             'equipeAppareil' => $leadRdv->getEquipeAppareil(),
  6002.             'durationEquipe' => $leadRdv->getDurationEquipeAppareil(),
  6003.             'bilanAuditif' => $leadRdv->getBilanAuditif(),
  6004.             'ordonance' => $leadRdv->getOrdonance(),
  6005.             'dateOrdonance' => $leadRdv->getDateOrdonance(),
  6006.             'canMove' => $leadRdv->getCanMove(),
  6007.         ];
  6008.         // makes the rdv
  6009.         $rdv = new Rdv();
  6010.         $rdv->setIdAudio($audio);
  6011.         if (isset($proche)) {
  6012.             $rdv->setIdProche($proche);
  6013.         }
  6014.         if (isset($data["client_id_temp"])) {
  6015.             $rdv->setIdClientTemp($client);
  6016.         } else {
  6017.             $rdv->setIdClient($client);
  6018.         }
  6019.         $rdv->setIsMyaudio(true);
  6020.         if (isset($data["isRdvLead"])) {
  6021.             $rdv->setIsRdvLp(true);
  6022.         }
  6023.         if (isset($data["isRdvRapide"])) {
  6024.             $rdv->setIsRdvRapide(true);
  6025.         }
  6026.         if (isset($data["duree"])) {
  6027.             $rdv->setDuration($data["duree"]);
  6028.         }
  6029.         if (isset($data["color"])) {
  6030.             $rdv->setColor($data["color"]);
  6031.         }
  6032.         /** @var Centre */
  6033.         if (isset($data["centre_id"])) {
  6034.             $centre $this->getDoctrine()
  6035.                 ->getRepository(Centre::class)
  6036.                 ->findOneBy(['id' => $data["centre_id"]]);
  6037.             if ($centre == null) {
  6038.                 return new Response(json_encode(([
  6039.                     'message' => 'Error, no centre found at this id',
  6040.                     'path' => 'src/Controller/RdvController.php',
  6041.                     "status" => 400,
  6042.                 ])), 400);
  6043.             }
  6044.             /** @var AudioCentre */
  6045.             $liaison $this->getDoctrine()
  6046.                 ->getRepository(AudioCentre::class)
  6047.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  6048.             if ($liaison == null) {
  6049.                 return new Response(json_encode(([
  6050.                     'message' => 'Error, audio isnt part of the centre',
  6051.                     'path' => 'src/Controller/RdvController.php',
  6052.                     "status" => 400,
  6053.                 ])), 400);
  6054.             }
  6055.             $rdv->setIdCentre($centre);
  6056.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  6057.             // tries to set the lieu if it's an audio indie
  6058.             $lieu $this->getDoctrine()
  6059.                 ->getRepository(Lieu::class)
  6060.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  6061.             if ($lieu == null) {
  6062.                 return new Response(json_encode(([
  6063.                     'message' => 'Error, no lieu found at this id',
  6064.                     'path' => 'src/Controller/RdvController.php',
  6065.                     "status" => 400,
  6066.                 ])), 400);
  6067.             }
  6068.             $rdv->setIdLieu($lieu);
  6069.         } else {
  6070.             return new Response(json_encode(([
  6071.                 'message' => 'Error, no lieu/centre id',
  6072.                 'path' => 'src/Controller/RdvController.php',
  6073.                 "status" => 400,
  6074.             ])), 400);
  6075.         }
  6076.         /** @var Motif */
  6077.         $motif $this->getDoctrine()
  6078.             ->getRepository(Motif::class)
  6079.             ->find($data["motif_id"]);
  6080.         if ($motif == null) {
  6081.             return new Response(json_encode(([
  6082.                 'message' => 'Error, no motif found at this id',
  6083.                 'path' => 'src/Controller/RdvController.php',
  6084.                 "status" => 400,
  6085.             ])), 400);
  6086.         }
  6087.         /** @var AudioMotif */
  6088.         $audioMotif $this->getDoctrine()
  6089.             ->getRepository(AudioMotif::class)
  6090.             ->findOneBy(["id_audio" => $audio->getId(), "id_motif" => $data["motif_id"]]);
  6091.         if ($audioMotif == null) {
  6092.             return new Response(json_encode(([
  6093.                 'message' => 'Error, no motif of this id found at this audio',
  6094.                 'path' => 'src/Controller/RdvController.php',
  6095.                 "status" => 400,
  6096.             ])), 400);
  6097.         }
  6098.         // remove the taken schedule by rdv to make sure there is no overlap
  6099.         $data["date"] = str_replace("h"":"$data["date"]);
  6100.         $date \DateTime::createFromFormat("Y-m-d\TH:i"$data["date"]);
  6101.         if (isset($data["note"])) {
  6102.             $rdv->setNote($data["note"]);
  6103.         }
  6104.         $date \DateTime::createFromFormat("Y-m-d\TH:i"$data["date"]);
  6105.         $rdv->setDate($date);
  6106.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  6107.         /** @var EtatRdv */
  6108.         $etat $this->getDoctrine()
  6109.             ->getRepository(EtatRdv::class)
  6110.             ->findOneBy(['id' => $data["etat_id"]]);
  6111.         if ($etat == null) {
  6112.             return new Response(json_encode(([
  6113.                 'message' => 'Error, no etat found at this id',
  6114.                 'path' => 'src/Controller/RdvController.php',
  6115.                 "status" => 400,
  6116.             ])), 400);
  6117.         }
  6118.         $rdv->setIdEtat($etat);
  6119.         $rdv->setIdMotif($motif);
  6120.         $rdv->setIsAbsence(0);
  6121.         $rdv->setCacher(0);
  6122.         $entityManager $this->getDoctrine()->getManager();
  6123.         $entityManager->persist($rdv);
  6124.         $leadRdv->setRdv($rdv);
  6125.         $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'rdv_valider']);
  6126.         $leadRdv->setLeadStatus($leadStatus);
  6127.         $entityManager->flush();
  6128.         /// SMSEMAIL A décommenter pour autoriser l'envoi de sms / email à la création de rdv par l'audio / le client SMSEMAIL ///
  6129.         $date $rdv->getDate();
  6130.         $smsDate $date->format('d-m-Y H:i');
  6131.         $locale 'fr_FR';
  6132.         $formatter = new IntlDateFormatter(
  6133.             $locale,
  6134.             IntlDateFormatter::FULL,
  6135.             IntlDateFormatter::SHORT,
  6136.             null,
  6137.             IntlDateFormatter::GREGORIAN,
  6138.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  6139.         );
  6140.         $smsDateLongFormat $formatter->format($date);
  6141.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  6142.         $client->setIdCentre($rdv->getIdCentre());
  6143.         $client->setIdAudio($rdv->getIdAudio());
  6144.         $entityManager->persist($client);
  6145.         $entityManager->flush();
  6146.         // client notif mail Sms
  6147.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  6148.         $frenchDate ucfirst($frenchDate);
  6149.         $params = array(
  6150.             "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  6151.             "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  6152.             "date" => $smsDateLongFormat,
  6153.             "RdvDate" => $smsDateLongFormat,
  6154.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  6155.             "centerName" => $rdv->getIdCentre()->getName(),
  6156.             "prenom" => $client->getName(),
  6157.             "centerAddress" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  6158.             "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  6159.             'motif' => $rdv->getIdMotif()->getTitre(),
  6160.             "centerCity" => $rdv->getIdCentre()->getCity(),
  6161.             "audioName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  6162.             'titre' => "Votre rendez-vous est validé le " substr($smsDate010) . " à "  substr($smsDate1115),
  6163.             "position" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  6164.             "address" => $rdv->getIdCentre()->getAddress(),
  6165.             "postal" => $rdv->getIdCentre()->getPostale(),
  6166.             "city" => $rdv->getIdCentre()->getCity(),
  6167.             "clientEmail" => $client->getMail(),
  6168.             "clientPassword" => isset($data["passwordGenerated"]) ? $data["passwordGenerated"] : null,
  6169.             "clientAddress" => $client->getAddress(),
  6170.             "clientPostal" => $client->getPostal(),
  6171.             "clientCity" => $client->getCity(),
  6172.             "audioName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  6173.             "frenchDate" => $frenchDate,
  6174.             "heure" => substr($smsDate1115),
  6175.             "centerName" => $rdv->getIdCentre()->getName(),
  6176.             "audioMail" => $rdv->getIdAudio()->getMail(),
  6177.             "modifUrl" => "{$_ENV['BASE_client']}mes-rendez-vous",
  6178.         );
  6179.         $paramsPatient $params;
  6180.         $isNew false;
  6181.         if (isset($data["isLead"]) && isset($data["passwordGenerated"]) != null) {
  6182.             $subject "✅Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  6183.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject189);
  6184.             $isNew true;
  6185.         } else {
  6186.             $subject "Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  6187.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject181);
  6188.         }
  6189.         $sms "Votre RDV est validé le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'imprévu contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  6190.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  6191.         // audio Notif mail SMS
  6192.         $birthday $rdv->getIdClient()->getBirthdate();
  6193.         $params = array(
  6194.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  6195.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  6196.             "date" => substr($smsDate010),
  6197.             "heure" => substr($smsDate1115),
  6198.             "mail" => $client->getMail(),
  6199.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  6200.             'telClient' => $client->getPhone(),
  6201.             'phone' => $client->getPhone(),
  6202.             'clientCivilite' => $client->getCivilite(),
  6203.             'clientNom' => $client->getLastname(),
  6204.             'clientPrenom' => $client->getName(),
  6205.             'clientPostal' => $client->getPostal(),
  6206.             'clientMail' => $client->getMail(),
  6207.             'clientPhone' => $client->getPhone(),
  6208.             'motif' => $rdv->getIdMotif()->getTitre(),
  6209.             'birthdate' => $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
  6210.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  6211.             'centerName' => $rdv->getIdCentre()->getName(),
  6212.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  6213.             'centerCity' => $rdv->getIdCentre()->getCity(),
  6214.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  6215.             'idPatient' => $client->getId(),
  6216.             'proUrl' => "{$_ENV['BASE_logiciel']}",
  6217.             'frenchDate' => $frenchDate,
  6218.             'responses' => $responses,
  6219.         );
  6220.         $templateEmail 182;
  6221.         if (!empty($data['canMove'])) {
  6222.             $templateEmail 197;
  6223.         }
  6224.         $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  6225.         $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  6226.         if ($rdv->getIdAudio()->getConfirmRdvMail()) {
  6227.             $subject "✅ Nouveau Rendez-vous My Audio le " $frenchDate " à " substr($smsDate1115);
  6228.             $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject$templateEmail);
  6229.         }
  6230.         if ($rdv->getIdAudio()->getConfirmRdvSms()) {
  6231.             $sms "Vous avez un nouveau RDV le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'aléas contactez votre patient " $client->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  6232.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  6233.         }
  6234.         $age null;
  6235.         if ($client->getBirthdate()) {
  6236.             $age $client->getBirthdate()->diff(new \DateTime())->y;
  6237.         }
  6238.         // Génère le PDF à partir d’un template
  6239.         $pdfContent $this->generatePdf(
  6240.             'pdf/rdv_recap.html.twig',
  6241.             [
  6242.                 'id' => $client->getId() ?? '',
  6243.                 'nom' => $client->getName() ?? '',
  6244.                 'prenom' => $client->getLastname() ?? '',
  6245.                 'birthday' =>  $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
  6246.                 'age' => $age,
  6247.                 'adresse' => $client->getAddress() ?? '',
  6248.                 'postal' => $client->getPostal() ?? '',
  6249.                 'city' => $client->getCity() ?? '',
  6250.                 'phone' => $client->getPhone() ?? '',
  6251.                 'mail' => $client->getMail() ?? '',
  6252.                 'centerName' => $rdv->getIdCentre()->getName() ?? '',
  6253.                 "date" => substr($smsDate010) ?? '',
  6254.                 "heure" => substr($smsDate1115) ?? '',
  6255.                 'duration' => $rdv->getDuration(),
  6256.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  6257.                 'motif' => $rdv->getIdMotif() ? $rdv->getIdMotif()->getTitre() : '',
  6258.                 'situations' => $this->formatImploded($leadRdv->getSituationsGene()),
  6259.                 'IntensiteGen' => $leadRdv->getIntensiteGene() ?? '',
  6260.                 'devicePref' => $this->formatImploded($leadRdv->getPreferenceDevice()),
  6261.                 'deviceModelPref' =>  implode(", "$leadRdv->getDeviceModelPreference()),
  6262.                 'criterePrincipal' => $this->formatImploded($leadRdv->getCriterePrincipal()),
  6263.                 'accoupheneCote' =>  $leadRdv->getAcoupheneCote() ?? '',
  6264.                 'originePerte' => $this->formatImploded($leadRdv->getOriginePerte()),
  6265.                 'diabete' =>  $leadRdv->getDiabete() ?? '',
  6266.                 'hypertension' =>  $leadRdv->getHypertension() ?? '',
  6267.                 'mutuelle' =>  $leadRdv->getMutuelle() ?? '',
  6268.                 'nameMutuelle' =>  $leadRdv->getNameMutuelle() ?? '',
  6269.                 'priseEnCharge' => $leadRdv->getPriseEnCharge() ?? '',
  6270.                 'budget' => $leadRdv->getBudget() ?? '',
  6271.                 'equipeAppareil' => $leadRdv->getEquipeAppareil() ?? '',
  6272.                 'durationEquipe' => $leadRdv->getDurationEquipeAppareil() ?? '',
  6273.                 'bilanAuditif' => $leadRdv->getBilanAuditif() ?? '',
  6274.                 'ordonance' => $leadRdv->getOrdonance() ?? '',
  6275.                 'dateOrdonance' => $leadRdv->getDateOrdonance() ?? '',
  6276.                 'canMove' => $leadRdv->getCanMove() ?? '',
  6277.                 'comment' => $leadRdv->getComment() ?? '',
  6278.             ],
  6279.             $this->getParameter('kernel.project_dir') . '/public/assets/pdf/recap-rdv-myaudio.pdf'
  6280.         );
  6281.         $this->sendEmailWithPdfAttachmentThenDelete(
  6282.             $params,
  6283.             $mailAudio,
  6284.             $client->getName(),
  6285.             $subject,
  6286.             $templateEmail// ID du template Sendinblue
  6287.             $pdfContent
  6288.         );
  6289.         // send notif to admin
  6290.         $paramsSourceLead = [
  6291.             'trafficSource' => "EasyAdmin",
  6292.         ];
  6293.         $paramsAdmin = array(
  6294.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  6295.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  6296.             "RdvDate" => substr($smsDate010),
  6297.             "heure" => substr($smsDate1115),
  6298.             "clientMail" => $client->getMail(),
  6299.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  6300.             'telClient' => $client->getPhone(),
  6301.             'clientNom' => $client->getLastname(),
  6302.             'clientPrenom' => $client->getName(),
  6303.             'clientCivilite' => $client->getCivilite(),
  6304.             'clientPostal' => $client->getPostal(),
  6305.             'clientPhone' => $client->getPhone(),
  6306.             'motif' => $rdv->getIdMotif()->getTitre(),
  6307.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  6308.             'centerName' => $rdv->getIdCentre()->getName(),
  6309.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  6310.             'centerCity' => $rdv->getIdCentre()->getCity(),
  6311.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  6312.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  6313.             'date' => substr($smsDate010),
  6314.             'urlApi' => "{$_ENV['BASE_API']}",
  6315.             'clientId' => $client->getId(),
  6316.             'centerId' => $rdv->getIdCentre()->getId(),
  6317.             'frenchDate' => $frenchDate,
  6318.             'responses' => $responses,
  6319.             'paramsSourceLead' => $paramsSourceLead
  6320.         );
  6321.         $subject "Nouveau RDV MA | RR - " $rdv->getIdCentre()->getName();
  6322.         $templateEmail 183;
  6323.         if (!empty($data['canMove'])) {
  6324.             $templateEmail 190;
  6325.         }
  6326.         $publicFunction->sendEmail($paramsAdmin"contact@myaudio.fr""my audio"$subject$templateEmail);
  6327.         $publicFunction->sendEmail($paramsAdmin"lead.myaudio@gmail.com""my audio"$subject$templateEmail);
  6328.         // google calendar post
  6329.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  6330.             ->findBy(array('audio' => $audio->getId()));
  6331.         $data['rdv'] = $rdv->getId();
  6332.         foreach ($synchronisations as $synchronisation) {
  6333.             if (!$synchronisation->getIsDeleted()) {
  6334.                 $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  6335.                 $googleCalendar->createEvent($synchronisation$data);
  6336.             }
  6337.         }
  6338.         try {
  6339.             $Callservice->handleCallCenterAfterRdv(
  6340.                 $rdv
  6341.             );
  6342.             $rdv->setIsNotificationRdvCallSent(1);
  6343.             $this->entityManager->flush();
  6344.         } catch (\Exception $e) {
  6345.             $this->logger->error("Erreur lors de l'appel de notification pour le RDV #{$rdv->getId()}: " $e->getMessage());
  6346.         }
  6347.         return new Response(json_encode(([
  6348.             "id" => $rdv->getId(),
  6349.             "motif_id" => $rdv->getIdMotif()->getId(),
  6350.             "audio_id" => $rdv->getIdAudio()->getId(),
  6351.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  6352.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  6353.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  6354.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  6355.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  6356.             "testclient" => $rdv->getTestClient() ? [
  6357.                 "result" => $rdv->getTestClient()->getResultTonal(),
  6358.                 "date" => $rdv->getTestClient()->getDate(),
  6359.                 "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  6360.             ] : null,
  6361.             "duration" => $audioMotif->getDuration(),
  6362.             "consigne" => $audioMotif->getConsigne(),
  6363.             "etat_id" => $rdv->getIdEtat()->getId(),
  6364.             "date" => $rdv->getDate(),
  6365.             "comment" => $rdv->getComment(),
  6366.             "centerName" => $rdv->getIdCentre()->getName(),
  6367.             "review" => $rdv->getReview(),
  6368.             "note" => $rdv->getNote(),
  6369.             "status" => 200,
  6370.             "paramsPatient" => $paramsPatient,
  6371.             "isNew" => $isNew,
  6372.         ])));
  6373.     }
  6374.     private function generatePdf(string $template, array $data = [], string $outputPath): string
  6375.     {
  6376.         // Render le contenu HTML avec Twig
  6377.         $html $this->twig->render($template$data);
  6378.         // Configurer Dompdf
  6379.         $options = new Options();
  6380.         $options->set('defaultFont''Arial');
  6381.         $dompdf = new Dompdf($options);
  6382.         $dompdf->loadHtml($html);
  6383.         $dompdf->setPaper('A4''portrait');
  6384.         $dompdf->render();
  6385.         // Sauvegarder le PDF
  6386.         file_put_contents($outputPath$dompdf->output());
  6387.         return $outputPath// Renvoie le chemin du fichier PDF généré
  6388.     }
  6389.     private function sendEmailWithPdfAttachmentThenDelete(
  6390.         array $params,
  6391.         string $mail,
  6392.         string $name,
  6393.         string $subject,
  6394.         int $templateId,
  6395.         string $pdfFilePath
  6396.     ): void {
  6397.         // Lire et encoder le contenu du PDF
  6398.         $attachment = [
  6399.             "name" => basename($pdfFilePath),
  6400.             "content" => base64_encode(file_get_contents($pdfFilePath)),
  6401.         ];
  6402.         // Construire les données pour l’API Sendinblue
  6403.         $data = [
  6404.             "sender" => [
  6405.                 "email" => 'noreply@myaudio.fr',
  6406.                 "name" => 'My Audio',
  6407.             ],
  6408.             "to" => [
  6409.                 [
  6410.                     "email" => $mail,
  6411.                     "name" => $name,
  6412.                 ],
  6413.             ],
  6414.             "subject" => $subject,
  6415.             "templateId" => $templateId,
  6416.             "params" => $params,
  6417.             "attachment" => [$attachment],
  6418.         ];
  6419.         // Envoi via cURL
  6420.         $ch curl_init();
  6421.         curl_setopt($chCURLOPT_URL'https://api.sendinblue.com/v3/smtp/email');
  6422.         curl_setopt($chCURLOPT_RETURNTRANSFER1);
  6423.         curl_setopt($chCURLOPT_POST1);
  6424.         curl_setopt($chCURLOPT_POSTFIELDSjson_encode($data));
  6425.         $headers = [
  6426.             'Accept: application/json',
  6427.             'Api-Key: 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',
  6428.             'Content-Type: application/json',
  6429.         ];
  6430.         curl_setopt($chCURLOPT_HTTPHEADER$headers);
  6431.         $result curl_exec($ch);
  6432.         if (curl_errno($ch)) {
  6433.             echo 'Erreur email : ' curl_error($ch);
  6434.         }
  6435.         curl_close($ch);
  6436.         // Supprimer le PDF après envoi
  6437.         if (file_exists($pdfFilePath)) {
  6438.             unlink($pdfFilePath);
  6439.         }
  6440.     }
  6441.     private function formatImploded(array $data): string
  6442.     {
  6443.         return implode(', 'array_map(function ($item) {
  6444.             return str_replace('_'' '$item);
  6445.         }, $data));
  6446.     }
  6447.     /**
  6448.      * 
  6449.      * @Route("/admin/rdv/export-pdf-form", name="admin_rdv_export_pdf_form", methods={"GET", "POST"})
  6450.      */
  6451.     public function exportPdfForm(Request $request): Response
  6452.     {
  6453.         $form $this->createFormBuilder()
  6454.             ->add('startDate'\Symfony\Component\Form\Extension\Core\Type\DateType::class, [
  6455.                 'label' => 'Date de début',
  6456.                 'widget' => 'single_text',
  6457.                 'html5' => true,
  6458.                 'required' => true,
  6459.             ])
  6460.             ->add('endDate'\Symfony\Component\Form\Extension\Core\Type\DateType::class, [
  6461.                 'label' => 'Date de fin',
  6462.                 'widget' => 'single_text',
  6463.                 'html5' => true,
  6464.                 'required' => true,
  6465.             ])
  6466.             ->add('format'\Symfony\Component\Form\Extension\Core\Type\ChoiceType::class, [
  6467.                 'label' => 'Format d\'export',
  6468.                 'choices' => [
  6469.                     'PDF' => 'pdf',
  6470.                     'Excel' => 'excel',
  6471.                 ],
  6472.                 'expanded' => false,
  6473.                 'multiple' => false,
  6474.                 'required' => true,
  6475.             ])
  6476.             ->getForm();
  6477.         //dd($request);
  6478.         $form->handleRequest($request);
  6479.         if ($form->isSubmitted() && $form->isValid()) {
  6480.             $data $form->getData();
  6481.             $start $data['startDate']->format('Y-m-d');
  6482.             $end $data['endDate']->format('Y-m-d');
  6483.             if ($data['format'] === 'pdf') {
  6484.                 return $this->redirectToRoute('admin_rdv_export_pdf', [
  6485.                     'startDate' => $start,
  6486.                     'endDate' => $end,
  6487.                 ]);
  6488.             } else {
  6489.                 return $this->redirectToRoute('admin_rdv_export_excel', [
  6490.                     'startDate' => $start,
  6491.                     'endDate' => $end,
  6492.                 ]);
  6493.             }
  6494.         }
  6495.         return $this->render('easyadmin/rdv/export_pdf_form.html.twig', [
  6496.             'form' => $form->createView(),
  6497.         ]);
  6498.     }
  6499.     /**
  6500.      * @Route("/admin/lead-rdv/update-status", name="admin_lead_rdv_update_status", methods={"POST"})
  6501.      */
  6502.     public function updateStatus(Request $request): JsonResponse
  6503.     {
  6504.         // Récupérer les données envoyées en AJAX
  6505.         $data json_decode($request->getContent(), true);
  6506.         $leadId $data['leadId'] ?? null;
  6507.         $statusId $data['statusId'] ?? null;
  6508.         if (!$leadId || !$statusId) {
  6509.             return new JsonResponse(['success' => false'message' => 'Données manquantes'], 400);
  6510.         }
  6511.         // Récupérer le lead et le statut
  6512.         $lead $this->entityManager->getRepository(LeadRdv::class)->find($leadId);
  6513.         $status $this->entityManager->getRepository(LeadStatus::class)->find($statusId);
  6514.         if (!$lead || !$status) {
  6515.             return new JsonResponse(['success' => false'message' => 'Lead ou statut introuvable'], 404);
  6516.         }
  6517.         // Mettre à jour le statut du lead
  6518.         $lead->setLeadStatus($status);
  6519.         $this->entityManager->flush();
  6520.         return new JsonResponse(['success' => true]);
  6521.     }
  6522.     /**
  6523.      * @Route("/admin/rdv/export-pdf/{startDate}/{endDate}", name="admin_rdv_export_pdf", methods={"GET"})
  6524.      */
  6525.     public function exportPdfFromDate(string $startDatestring $endDateKernelInterface $kernel): Response
  6526.     {
  6527.         $start = new \DateTimeImmutable($startDate);
  6528.         $end = new \DateTimeImmutable($endDate);
  6529.         $today = new \DateTimeImmutable();
  6530.         $rdvs $this->rdvRepository->findBySinceDateAndMyAudio($start$end);
  6531.         $html "
  6532.     <html>
  6533.     <head>
  6534.         <style>
  6535.             body { font-family: Arial, sans-serif; font-size: 13px; }
  6536.             table { width: 100%; border-collapse: collapse; font-size: 11px; }
  6537.             th, td { border: 1px solid #000; padding: 5px; text-align: left; }
  6538.             th { font-weight: bold; }
  6539.             h1 { font-size: 14px; }
  6540.         </style>
  6541.     </head>
  6542.     <body>
  6543.         <h1>Rendez-vous My Audio du " $start->format('d/m/Y') . " au " $end->format('d/m/Y') . "</h1>
  6544.         <table cellspacing='0' cellpadding='5'>
  6545.             <thead>
  6546.                 <tr>
  6547.                     <th>ID du RDV</th>
  6548.                     <th>Date du RDV</th>
  6549.                     <th>Jours écoulés</th>
  6550.                     <th>Statut RDV</th>
  6551.                     <th>Nom patient</th>
  6552.                     <th>Téléphone patient</th>
  6553.                     <th>Statut patient</th>
  6554.                     <th>Centre</th>
  6555.                     <th>Téléphone Centre</th>
  6556.                     <th>Adresse</th>
  6557.                     <th>Nom Audio</th>
  6558.                 </tr>
  6559.             </thead>
  6560.             <tbody>";
  6561.         foreach ($rdvs as $rdv) {
  6562.             $dateRdv $rdv->getDate();
  6563.             $joursEcoules $dateRdv->diff($today)->days;
  6564.             $client $rdv->getIdClient();
  6565.             $centre $rdv->getIdCentre();
  6566.             $etat $rdv->getIdEtat();
  6567.             $audio $rdv->getIdAudio();
  6568.             $html .= "<tr>
  6569.             <td>" $rdv->getId() . "</td>
  6570.             <td>" $dateRdv->format('d/m/Y H:i') . "</td>
  6571.             <td>" $joursEcoules " jours</td>
  6572.             <td>" . ($etat htmlspecialchars($etat->getLibelle()) : 'Non défini') . "</td>
  6573.             <td>" . ($client htmlspecialchars($client->getName() . ' ' $client->getLastname()) : '') . "</td>
  6574.             <td>" . ($client htmlspecialchars($client->getPhone()) : '') . "</td>
  6575.             <td>" . ($client && $client->getClientStatus() ? htmlspecialchars($client->getClientStatus()->getLibelle()) : 'Non défini') . "</td>
  6576.             <td>" . ($centre htmlspecialchars($centre->getName()) : '') . "</td>
  6577.             <td>" . ($centre htmlspecialchars($centre->getPhone()) : '') . "</td>
  6578.             <td>" . ($centre htmlspecialchars($centre->getAddress() . ', ' $centre->getPostale() . ' ' $centre->getCity()) : '') . "</td>
  6579.             <td>" . ($audio htmlspecialchars($audio->getCivilite() . ' ' $audio->getName() . ' ' $audio->getLastname()) : '') . "</td>
  6580.         </tr>";
  6581.         }
  6582.         $html .= "</tbody></table></body></html>";
  6583.         // Configuration et rendu du PDF
  6584.         $options = new Options();
  6585.         $options->set('defaultFont''Arial');
  6586.         $dompdf = new Dompdf($options);
  6587.         $dompdf->loadHtml($html);
  6588.         $dompdf->setPaper('A4''landscape');
  6589.         $dompdf->render();
  6590.         // Création du dossier s'il n'existe pas
  6591.         $projectDir $kernel->getProjectDir();
  6592.         $outputDir $projectDir '/public/assets/pdf/rdv';
  6593.         $filesystem = new Filesystem();
  6594.         if (!$filesystem->exists($outputDir)) {
  6595.             $filesystem->mkdir($outputDir0775);
  6596.         }
  6597.         $filenameDate $start->format('Y-m-d') . '_to_' $end->format('Y-m-d');
  6598.         $outputPath "$outputDir/rdvs-$filenameDate.pdf";
  6599.         file_put_contents($outputPath$dompdf->output());
  6600.         return new Response($dompdf->output(), 200, [
  6601.             'Content-Type' => 'application/pdf',
  6602.             'Content-Disposition' => 'attachment; filename="rdvs-' $filenameDate '.pdf"',
  6603.         ]);
  6604.     }
  6605.     /**
  6606.      * 
  6607.      * @Route("/admin/rdv/export/excel/{startDate}/{endDate}", name="admin_rdv_export_excel", methods={"GET"})
  6608.      */
  6609.     public function exportExcelFromDate(string $startDatestring $endDate): Response
  6610.     {
  6611.         $start = new \DateTimeImmutable($startDate);
  6612.         $end = new \DateTimeImmutable($endDate);
  6613.         $rdvs $this->rdvRepository->findBySinceDateAndMyAudio($start$end);
  6614.         $spreadsheet = new Spreadsheet();
  6615.         $sheet $spreadsheet->getActiveSheet();
  6616.         // Headers
  6617.         $sheet->fromArray([
  6618.             'ID du RDV',
  6619.             'Date du RDV',
  6620.             'Jours écoulés',
  6621.             'Statut RDV',
  6622.             'Nom patient',
  6623.             'Téléphone patient',
  6624.             'Statut patient',
  6625.             'Centre',
  6626.             'Téléphone Centre',
  6627.             'Adresse',
  6628.             'Nom Audio'
  6629.         ], null'A1');
  6630.         $today = new \DateTimeImmutable();
  6631.         $row 2;
  6632.         foreach ($rdvs as $rdv) {
  6633.             $dateRdv $rdv->getDate();
  6634.             $joursEcoules $dateRdv->diff($today)->days;
  6635.             $client $rdv->getIdClient();
  6636.             $centre $rdv->getIdCentre();
  6637.             $etat $rdv->getIdEtat();
  6638.             $sheet->fromArray([
  6639.                 $rdv->getId(),
  6640.                 $dateRdv->format('d/m/Y H:i'),
  6641.                 $joursEcoules ' jours',
  6642.                 $etat $etat->getLibelle() : 'Non défini',
  6643.                 $client $client->getName() . ' ' $client->getLastname() : '',
  6644.                 $client $client->getPhone() : '',
  6645.                 $client && $client->getClientStatus() ? $client->getClientStatus()->getLibelle() : 'Non défini',
  6646.                 $centre $centre->getName() : '',
  6647.                 $centre $centre->getPhone() : '',
  6648.                 $centre $centre->getAddress() . ', ' $centre->getPostale() . ' ' $centre->getCity() : '',
  6649.                 $rdv->getIdAudio() ? $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastname() : '',
  6650.             ], null'A' $row);
  6651.             $row++;
  6652.         }
  6653.         $writer = new Xlsx($spreadsheet);
  6654.         $filename "rdvs-$startDate-to-$endDate.xlsx";
  6655.         // Stream the file to browser
  6656.         $response = new \Symfony\Component\HttpFoundation\StreamedResponse(function () use ($writer) {
  6657.             $writer->save('php://output');
  6658.         });
  6659.         $dispositionHeader $response->headers->makeDisposition(
  6660.             \Symfony\Component\HttpFoundation\ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  6661.             $filename
  6662.         );
  6663.         $response->headers->set('Content-Type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  6664.         $response->headers->set('Content-Disposition'$dispositionHeader);
  6665.         return $response;
  6666.     }
  6667.     /**
  6668.      * 
  6669.      * @Route("/admin/update-note", name="update_note", methods={"POST"})
  6670.      */
  6671.     public function updateNote(Request $requestEntityManagerInterface $em): JsonResponse
  6672.     {
  6673.         $data json_decode($request->getContent(), true);
  6674.         $id $data['id'] ?? null;
  6675.         $note $data['note'] ?? null;
  6676.         if (!$id || $note === null) {
  6677.             return new JsonResponse(['status' => 'error''message' => 'Invalid data'], 400);
  6678.         }
  6679.         $entity $em->getRepository(Rdv::class)->find($id);
  6680.         if (!$entity) {
  6681.             return new JsonResponse(['status' => 'error''message' => 'Entity not found'], 404);
  6682.         }
  6683.         $entity->setNote($note);
  6684.         $em->flush();
  6685.         return new JsonResponse(['status' => 'success']);
  6686.     }
  6687.     /**
  6688.      * 
  6689.      * @Route("/giuili-admin/edit-rdv/{rdvId}/centre/{centreId}", name="update_admin_rdv", methods={"GET"})
  6690.      */
  6691.     public function showRdvCentre(int $rdvIdCentre $centreId): Response
  6692.     {
  6693.         // dd("tets");
  6694.         $center $centres $this->getDoctrine()
  6695.             ->getRepository(AudioCentre::class)
  6696.             ->findOneBy(['id_centre' => $centreId->getId()]);
  6697.         $audio $center->getIdAudio();
  6698.         $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  6699.             ->findBy(['id_audio' => $audio'isDeleted' => 0]);
  6700.         return $this->render('easyadmin/rdv/centre_show.html.twig', [
  6701.             'audio' => $audio,
  6702.             'rdvId' => $rdvId,
  6703.             'centreId' => $centreId,
  6704.             'motifs' => $motifs,
  6705.         ]);
  6706.     }
  6707.     /**
  6708.      * @Route("/update-rdv-easyadmin", name="update_rdv_easyadmin", methods={"POST"})
  6709.      */
  6710.     public function updateRdvEasyadmin(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSms): Response
  6711.     {
  6712.         $data json_decode($request->getContent(), true);
  6713.         $rdv $this->getDoctrine()
  6714.             ->getRepository(Rdv::class)
  6715.             ->find($data["rdv_id"]);
  6716.         $pastDate $rdv->getDate();
  6717.         $entityManager $this->getDoctrine()->getManager();
  6718.         if (isset($data["etat_id"])) {
  6719.             $etat $this->getDoctrine()
  6720.                 ->getRepository(EtatRdv::class)
  6721.                 ->findOneBy(['id' => $data["etat_id"]]);
  6722.             if ($etat == null) {
  6723.                 return new Response(json_encode(([
  6724.                     'message' => 'Error, no etat found at this id',
  6725.                     'path' => 'src/Controller/TrustedUserController.php',
  6726.                     "status" => 400,
  6727.                 ])), 400);
  6728.             }
  6729.             $rdv->setIdEtat($etat);
  6730.         }
  6731.         if (isset($data["audio_id"])) {
  6732.             $audio $this->getDoctrine()
  6733.                 ->getRepository(Audio::class)
  6734.                 ->findOneBy(['id' => $data["audio_id"]]);
  6735.             if ($audio == null) {
  6736.                 return new Response(json_encode(([
  6737.                     'message' => 'Error, no audio found at this id',
  6738.                     'path' => 'src/Controller/TrustedUserController.php',
  6739.                     "status" => 400,
  6740.                 ])), 400);
  6741.             }
  6742.             $rdv->setIdAudio($audio);
  6743.         }
  6744.         if (isset($data["motif_id"])) {
  6745.             $motif $this->getDoctrine()
  6746.                 ->getRepository(Motif::class)
  6747.                 ->find($data["motif_id"]);
  6748.             if ($motif == null) {
  6749.                 return new Response(json_encode(([
  6750.                     'message' => 'Error, no motif found at this id',
  6751.                     'path' => 'src/Controller/TrustedUserController.php',
  6752.                     "status" => 400,
  6753.                 ])), 400);
  6754.             }
  6755.             $rdv->setIdMotif($motif);
  6756.         }
  6757.         if (isset($data["client_id"])) {
  6758.             $client $this->getDoctrine()
  6759.                 ->getRepository(Client::class)
  6760.                 ->findOneBy(['id' => $data["client_id"]]);
  6761.             if ($client == null) {
  6762.                 return new Response(json_encode(([
  6763.                     'message' => 'Error, no client found at this id',
  6764.                     'path' => 'src/Controller/TrustedUserController.php',
  6765.                     "status" => 400,
  6766.                 ])), 400);
  6767.             }
  6768.             $rdv->setIdClient($client);
  6769.         }
  6770.         if (isset($data["date"])) {
  6771.             $data["date"] = str_replace("h"":"$data["date"]);
  6772.             $date \DateTime::createFromFormat("Y-m-d\TH:i"$data["date"]);
  6773.             $audioMotif $this->getDoctrine()
  6774.                 ->getRepository(AudioMotif::class)
  6775.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  6776.             if ($audioMotif == null) {
  6777.                 return new Response(json_encode(([
  6778.                     'message' => 'Error, no motif of this id found at this audio',
  6779.                     'path' => 'src/Controller/RdvController.php',
  6780.                     "status" => 400,
  6781.                 ])), 400);
  6782.             }
  6783.             if ($rdv->getIdAudio()->getIsIndie()) {
  6784.                 if ($rdv->getIdCentre()) {
  6785.                     // regular centre audio indie
  6786.                     /** @var AudioCentre */
  6787.                     $liaison $this->getDoctrine()
  6788.                         ->getRepository(AudioCentre::class)
  6789.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  6790.                     if ($liaison == null) {
  6791.                         return new Response(json_encode(([
  6792.                             'message' => 'Error, audio isnt part of the centre',
  6793.                             'path' => 'src/Controller/RdvController.php',
  6794.                             "status" => 400,
  6795.                         ])), 400);
  6796.                     }
  6797.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  6798.                         return new Response(json_encode(([
  6799.                             'message' => 'Error, no horaire found for this audio',
  6800.                             'path' => 'src/Controller/RdvController.php',
  6801.                             "status" => 400,
  6802.                         ])), 400);
  6803.                     }
  6804.                 } else {
  6805.                     // lieu audio indie
  6806.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  6807.                         return new Response(json_encode(([
  6808.                             'message' => 'Error, no horaire found for this audio',
  6809.                             'path' => 'src/Controller/RdvController.php',
  6810.                             "status" => 400,
  6811.                         ])), 400);
  6812.                     }
  6813.                 }
  6814.             } else {
  6815.                 // regular centre
  6816.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  6817.                     return new Response(json_encode(([
  6818.                         'message' => 'Error, no horaire found for this audio',
  6819.                         'path' => 'src/Controller/RdvController.php',
  6820.                         "status" => 400,
  6821.                     ])), 400);
  6822.                 }
  6823.             }
  6824.             $rdv->setDate($date);
  6825.         }
  6826.         if (isset($data["comment"]) && $token->getIdClient()) {
  6827.             $rdv->setComment($data["comment"]);
  6828.         }
  6829.         if (isset($data["review"]) && $token->getIdClient()) {
  6830.             $rdv->setReview($data["review"]);
  6831.         }
  6832.         if (isset($data["note"])) {
  6833.             $rdv->setNote($data["note"]);
  6834.         }
  6835.         $entityManager->flush();
  6836.         $date $rdv->getDate();
  6837.         $smsDate $date->format('d-m-Y H:i');
  6838.         $oldDate $pastDate->format('d-m-Y H:i');
  6839.         $locale 'fr_FR';
  6840.         $formatter = new IntlDateFormatter(
  6841.             $locale,
  6842.             IntlDateFormatter::FULL,
  6843.             IntlDateFormatter::SHORT,
  6844.             null,
  6845.             IntlDateFormatter::GREGORIAN,
  6846.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  6847.         );
  6848.         $smsDateLongFormat $formatter->format($date);
  6849.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  6850.         $frenchDate ucfirst($frenchDate);
  6851.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  6852.         // notif client
  6853.         if ($rdv->getIdEtat()->getId() != 2) {
  6854.             $params = array(
  6855.                 "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  6856.                 "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  6857.                 "date" => $smsDateLongFormat,
  6858.                 "heure" => substr($smsDate1115),
  6859.                 "motif" => $rdv->getIdMotif()->getTitre(),
  6860.                 "centerName" => $rdv->getIdCentre()->getName(),
  6861.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  6862.                 "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  6863.                 "audioMail" => $rdv->getIdAudio()->getMail(),
  6864.                 "centerPhone" => $rdv->getIdCentre()->getPhone(),
  6865.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  6866.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  6867.                 'titre' => 'Votre rendez-vous est modifié pour le',
  6868.                 'frenchDate' => $frenchDate,
  6869.             );
  6870.             $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  6871.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  6872.             $sms "Votre RDV est modifié pour le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'imprévu contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  6873.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  6874.         }
  6875.         //     //// == suppression
  6876.         else if ($rdv->getIdEtat()->getId() == 2) {
  6877.             $params = array(
  6878.                 "date" => substr($smsDate010),
  6879.                 "lien" => "{$_ENV['BASE_client']}search",
  6880.                 "heure" => substr($smsDate1115),
  6881.                 "patientName" => $client->getLastName(),
  6882.                 'titre' => 'Votre rendez-vous est annulé :',
  6883.                 'centerName' => $rdv->getIdCentre()->getName(),
  6884.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  6885.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  6886.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  6887.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  6888.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  6889.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  6890.                 'motif' => $rdv->getIdMotif()->getTitre(),
  6891.             );
  6892.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  6893.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  6894.             if ($data["sms"]) {
  6895.                 $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  6896.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  6897.             }
  6898.         }
  6899.         //notif Audio
  6900.         if ($rdv->getIdEtat()->getId() != 2) {
  6901.             $params = array(
  6902.                 "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  6903.                 "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  6904.                 "date" => substr($smsDate010),
  6905.                 "frenchDate" => $frenchDate,
  6906.                 "heure" => substr($smsDate1115),
  6907.                 'motif' => $rdv->getIdMotif()->getTitre(),
  6908.                 'clientPhone' => $client->getPhone(),
  6909.                 'clientNom' => $client->getLastname(),
  6910.                 'clientPrenom' => $client->getName(),
  6911.                 'clientCivilite' => $client->getCivilite(),
  6912.                 'clientPostal' => $client->getPostal(),
  6913.                 'clientMail' => $client->getMail(),
  6914.                 'centerName' => $rdv->getIdCentre()->getName(),
  6915.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  6916.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  6917.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  6918.                 'idPatient' => $client->getId(),
  6919.                 'proUrl' => "{$_ENV['BASE_logiciel']}",
  6920.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  6921.                 'titre' => 'Votre rendez-vous est modifié pour le :'
  6922.             );
  6923.             $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  6924.             $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  6925.             if ($rdv->getIdAudio()->getModifRdvMail()) {
  6926.                 $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  6927.                 $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  6928.             }
  6929.             if ($rdv->getIdAudio()->getModifRdvSms()) {
  6930.                 $sms "Votre RDV est modifié pour le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'imprévu contacter votre patient " $client->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  6931.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  6932.             }
  6933.         } else if ($rdv->getIdEtat()->getId() == 2) {
  6934.             $params = array(
  6935.                 "date" => substr($smsDate010),
  6936.                 "lien" => "{$_ENV['BASE_client']}search",
  6937.                 "heure" => substr($smsDate1115),
  6938.                 "patientName" => $client->getLastName(),
  6939.                 'titre' => 'Votre rendez-vous est annulé :',
  6940.                 'centerName' => $rdv->getIdCentre()->getName(),
  6941.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  6942.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  6943.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  6944.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  6945.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  6946.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  6947.                 'motif' => $rdv->getIdMotif()->getTitre(),
  6948.             );
  6949.             $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  6950.             $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  6951.             if ($rdv->getIdAudio()->getModifRdvMail()) {
  6952.                 $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  6953.                 $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject188);
  6954.             }
  6955.             if ($rdv->getIdAudio()->getModifRdvSms()) {
  6956.                 $sms "Votre RDV du " substr($oldDate010) . " à " substr($oldDate1115) . "a été annulé, vous pouvez contacter votre patient pour fixer un autre RDV:" $client->getPhone() . " pour fixer un autre RDV.\nNe pas répondre.";
  6957.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  6958.             }
  6959.         }
  6960.         /* generate sms notif on update */
  6961.         // update sms notification     
  6962.         $rdvSms->updateRdvSms($rdv);
  6963.         // google calendar update
  6964.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  6965.             ->findBy(array('audio' => $rdv->getIdAudio()));
  6966.         $data['rdv'] = $rdv->getId();
  6967.         $data['motif_id'] = $rdv->getIdMotif();
  6968.         $data['note'] = $rdv->getNote();
  6969.         if ($rdv->getIdClient() !== null) {
  6970.             $data["client_id"] = $rdv->getIdClient()->getId();
  6971.         }
  6972.         if ($rdv->getIdClientTemp() !== null) {
  6973.             $data["client_id_temp"] = $rdv->getIdClientTemp()->getId();
  6974.         }
  6975.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  6976.             ->findBy(array('rdv' => $rdv));
  6977.         foreach ($rdvEvents as $rdvEvent) {
  6978.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  6979.             $googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  6980.         }
  6981.         return new Response(json_encode(([
  6982.             "id" => $rdv->getId(),
  6983.             "motif_id" => $rdv->getIdMotif()->getId(),
  6984.             "audio_id" => $rdv->getIdAudio()->getId(),
  6985.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  6986.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  6987.             "fullName" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  6988.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  6989.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  6990.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  6991.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  6992.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  6993.             "centre_id" => $rdv->getIdCentre()->getId(),
  6994.             "centerName" => $rdv->getIdCentre()->getName(),
  6995.             "etat_id" => $rdv->getIdEtat()->getId(),
  6996.             "date" => $rdv->getDate(),
  6997.             "comment" => $rdv->getComment(),
  6998.             "note" => $rdv->getNote(),
  6999.             "review" => $rdv->getReview(),
  7000.             "status" => 200,
  7001.         ])));
  7002.     }
  7003.        private function checkRdvReminder($rdv): ?array
  7004. {
  7005.     $dateRdv $rdv->getDate();
  7006.     $today = new \DateTime();
  7007.     $today->setTime(000);
  7008.     $dateRdv->setTime(000);
  7009.     $intervalDays $today->diff($dateRdv)->days;
  7010.     if ($intervalDays === 1) {
  7011.         $interval "24";
  7012.     } elseif ($intervalDays === 2) {
  7013.         $interval "48";
  7014.     } elseif ($intervalDays === 3) {
  7015.         $interval "72";
  7016.     } elseif ($intervalDays === 4) {
  7017.         $interval "96";
  7018.     } else { // >= 4 jours
  7019.         $interval "92";
  7020.     }
  7021.     $client $rdv->getIdClientTemp() ?: $rdv->getIdClient();
  7022.     $clientId $client $client->getId() : null;
  7023.     $clientName null;
  7024.     if ($client) {        
  7025.             $clientName $client->getName();
  7026.     }
  7027.     $motif $rdv->getIdMotif();
  7028.     $motifTitle $motif $motif->getTitre() : null;
  7029.     $centre $rdv->getIdCentre();
  7030.     $centreName null;
  7031.     if ($centre) {
  7032.         $centreName $centre->getName();
  7033.     }
  7034.    return [
  7035.         'rdvId' => $rdv->getId(),
  7036.         'clientId' => $clientId,
  7037.         'clientName' => $clientName ?? 'N/A',
  7038.         'interval' => $interval,
  7039.         'date' => $rdv->getDate() ? $rdv->getDate()->format('d-m-Y H:i') : null,
  7040.         'motif' => $motifTitle ?? 'N/A',
  7041.         'centreName' => $centreName ?? 'N/A',
  7042.     ];
  7043. }
  7044. }