src/Controller/MessageController.php line 47

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Symfony\Component\HttpFoundation\Response;
  5. use Symfony\Component\Routing\Annotation\Route;
  6. use App\Entity\Message;
  7. use Symfony\Contracts\HttpClient\HttpClientInterface;
  8. use App\Form\MessageType;
  9. use App\Repository\TypeMessageRepository;
  10. use App\Repository\MessageRepository;
  11. use Doctrine\ORM\EntityManagerInterface;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\File\Exception\FileException;
  14. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  15. use App\Entity\Client;
  16. use App\Entity\Conversation;
  17. use App\Entity\StatutConversation;
  18. use App\Entity\Canal;
  19. use App\Entity\RechercheAppuisConseil;
  20. use Symfony\Component\HttpFoundation\JsonResponse;
  21. use Lexik\Bundle\JWTAuthenticationBundle\Encoder\JWTEncoderInterface;
  22. use App\Repository\ClientRepository;
  23. use App\Repository\ConversationRepository;
  24. use App\Repository\CanalRepository;
  25. use App\Repository\StatutConversationRepository;
  26. use App\Entity\Session;
  27. use App\Repository\RechercheAgroMeteoRepository;
  28. use App\Repository\RechercheAppuisConseilRepository;
  29. use App\Entity\RechercheAgroMeteo;
  30. use App\Repository\RecherchePrixRepository;
  31. use App\Entity\RecherchePrix;
  32. use App\Repository\SessionRepository;
  33. use App\Fonctions\Fonctions;
  34. use App\Repository\UserRepository;
  35. use DateTimeImmutable;
  36. class MessageController extends AbstractController
  37. {
  38.     private $client;
  39.     public function __construct(SessionInterface $session,HttpClientInterface $client,Fonctions $fonct)
  40.     {
  41.         $this->client $client;
  42.         $this->fonct $fonct;
  43.         $this->session $session;
  44.        
  45.     }
  46.    
  47.     // #[Route('/webhook/garbal/messagerie', methods: ['GET','POST'])]
  48.     // public function messageriewebhook(Request $request): Response
  49.     // {
  50.     //     $verifyToken = "QJEOIDJQEILDJLQDJLEQCLKFDEQLKLEQSKDKQEM";
  51.     //     $mode = trim((string) $request->query->get('hub_mode'));
  52.     //     $token = trim((string) $request->query->get('hub_verify_token'));
  53.     //     $challenge = $request->query->get('hub_challenge');
  54.     //     if ($mode === 'subscribe' && $token === $verifyToken) {
  55.     //         return new Response($challenge, 200, ['Content-Type' => 'text/plain']);
  56.     //     }
  57.     //     return new Response('Forbidden: '.$token, 403);
  58.     // }
  59.     #[Route('/webhook/garbal/messagerie'name'app_webhook_garbal_messagerie'methods: ['GET''POST'])]
  60.     public function messageriewebhook(Request $requestConversationRepository $ConversationRepositoryStatutConversationRepository $StatutConversationRepositoryCanalRepository $CanalRepositoryClientRepository $ClientRepositoryTypeMessageRepository $TypeMessageRepositoryEntityManagerInterface $entityManager,HttpClientInterface $httpClient): Response
  61.     {
  62.         $json $request->getContent();
  63.         $data json_decode($jsontrue);
  64.         if (!$data) {
  65.             return new Response('Invalid JSON'400);
  66.         }
  67.         // Vérifier qu'il y a un message entrant
  68.         if (!isset($data['entry'][0]['changes'][0]['value']['messages'][0])) {
  69.             return new Response('No message'200);
  70.         }
  71.         $value $data['entry'][0]['changes'][0]['value'];
  72.         // Récupérations
  73.         $numero $value['messages'][0]['from'] ?? null;
  74.         $nomPrenom $value['contacts'][0]['profile']['name'] ?? null;
  75.         $typeMessage $value['messages'][0]['type'] ?? null;
  76.         // $body = $value['messages'][0]['text']['body'] ?? null;
  77.         $client $ClientRepository->findOneBy(['telephone' => $numero'statut' => 1]);
  78.         if (!$client) {
  79.             $client = new Client();
  80.             $client->setNomPrenom($nomPrenom);
  81.             $client->setTelephone($numero);
  82.             $client->setAdresse("");
  83.             $client->setCreatedAt(new DateTimeImmutable());
  84.             $client->setStatut(1);
  85.             $entityManager->persist($client);
  86.             $entityManager->flush();
  87.         }
  88.         $conversation $ConversationRepository->findOneBy(['id_client' => $client->getId(), 'id_statut_conversation' => 1]);
  89.         // $this->MessageSimple("ok", $numero);
  90.         if (!$conversation) {
  91.             $conversation = new Conversation();
  92.             // $conversation->setIdUser($name);
  93.             $conversation->setIdClient($client);
  94.             $conversation->setIdStatutConversation($StatutConversationRepository->findOneBy(['id'=>1]));
  95.             // $conversation->setObjet("");
  96.             $conversation->setDateDebutConversation(new DateTimeImmutable());
  97.             // $conversation->setDateFinConversation($number);
  98.             $conversation->setCreatedAt(new DateTimeImmutable());
  99.             $conversation->setStatut(1);
  100.             $entityManager->persist($conversation);
  101.             $entityManager->flush();
  102.         }
  103.         $message = new Message();
  104.         $message->setTelephone($numero);
  105.         $message->setIdCanal($CanalRepository->findOneBy(['id'=>1]));
  106.         $message->setIdConversation($conversation);
  107.         $message->setCreatedAt(new DateTimeImmutable());
  108.         $message->setStatus(1);
  109.         switch ($typeMessage) {
  110.             case 'text':
  111.                 $body $value['messages'][0]['text']['body'] ?? null;
  112.                 $message->setIdTypeMessage($TypeMessageRepository->findOneBy(['id'=>1]));
  113.                 $message->setContenus($body);
  114.                 break;
  115.             case 'image':
  116.                 $imageId $value['messages'][0]['image']['id'] ?? null;
  117.                 $caption $value['messages'][0]['image']['caption'] ?? null;
  118.                 if ($imageId) {
  119.                     $token $_ENV['WHATSAPP_TOKEN'];
  120.                     // récupérer l'URL du média
  121.                     $response $httpClient->request(
  122.                         'GET',
  123.                         "https://graph.facebook.com/v22.0/$imageId",
  124.                         [
  125.                             'headers' => [
  126.                                 'Authorization' => 'Bearer '.$token
  127.                             ]
  128.                         ]
  129.                     );
  130.                     $mediaData $response->toArray();
  131.                     $imageUrl $mediaData['url'];
  132.                     // $imageUrl = 'https://sandbox.crmgarbal.com/uploads/messages/'.$newFilename;
  133.                     
  134.                         // télécharger l'image
  135.                         $imageResponse $httpClient->request(
  136.                             'GET',
  137.                             $imageUrl,
  138.                             [
  139.                                 'headers' => [
  140.                                     'Authorization' => 'Bearer '.$token
  141.                                 ]
  142.                             ]
  143.                         );
  144.                         $imageContent $imageResponse->getContent();
  145.                         $newFilename 'whatsapp_'.uniqid().'.jpg';
  146.                         // $urls = 'https://sandbox.crmgarbal.com/uploads/messages/' . $newFilename;
  147.                         $filePath $this->getParameter('messages_images_directory').'/'.$newFilename;
  148.                         file_put_contents($filePath$imageContent);   
  149.                         
  150.                         $message->addImage($newFilename);
  151.                         $message->setIdTypeMessage($TypeMessageRepository->findOneBy(['id'=>2]));
  152.                         $message->setContenus($caption);
  153.                         $entityManager->persist($message);
  154.                         // $entityManager->flush(); 
  155.                         // $this->MessageSimple("enregistrement effectué", $numero);
  156.                 }
  157.                 break;
  158.             case 'audio':
  159.                 $audioId $value['messages'][0]['audio']['id'] ?? null;
  160.                 $mimeType $value['messages'][0]['audio']['mime_type'] ?? 'audio/ogg';
  161.                 if ($audioId) {
  162.                     $extension str_contains($mimeType'mpeg') ? 'mp3' 'ogg';
  163.                     $audioPath $this->downloadWhatsAppMedia(
  164.                         $audioId,
  165.                         $httpClient,
  166.                         'audio',
  167.                         $extension
  168.                     );
  169.                     $message->setIdTypeMessage($TypeMessageRepository->findOneBy(['id'=>3]));
  170.                     $message->setAudio($audioPath);
  171.                 }
  172.                 break;
  173.            case 'video':
  174.                 $videoId $value['messages'][0]['video']['id'] ?? null;
  175.                 $caption $value['messages'][0]['video']['caption'] ?? null;
  176.                 $mimeType $value['messages'][0]['video']['mime_type'] ?? 'video/mp4';
  177.                 if ($videoId) {
  178.                     $extension explode('/'$mimeType)[1] ?? 'mp4';
  179.                     $videoPath $this->downloadWhatsAppMedia(
  180.                         $videoId,
  181.                         $httpClient,
  182.                         'videos',
  183.                         $extension
  184.                     );
  185.                     $message->setVideo($videoPath);
  186.                     $message->setIdTypeMessage($TypeMessageRepository->findOneBy(['id'=>4]));
  187.                     $message->setContenus($caption);
  188.                 }
  189.                 break;
  190.                 case 'document':
  191.                     $documentId $value['messages'][0]['document']['id'] ?? null;
  192.                     $caption $value['messages'][0]['document']['caption'] ?? null;
  193.                     $filename $value['messages'][0]['document']['filename'] ?? null;
  194.                     $mimeType $value['messages'][0]['document']['mime_type'] ?? null;
  195.                     if ($documentId) {
  196.                         $extension pathinfo($filenamePATHINFO_EXTENSION) ?: 'bin';
  197.                         $docPath $this->downloadWhatsAppMedia(
  198.                             $documentId,
  199.                             $httpClient,
  200.                             'documents',
  201.                             $extension
  202.                         );
  203.                         $message->setDocument($docPath);
  204.                         $message->setIdTypeMessage($TypeMessageRepository->findOneBy(['id'=>5]));
  205.                         $message->setContenus($caption ?? $filename);
  206.                     }
  207.                     break;
  208.             case 'location':
  209.                 $latitude  $value['messages'][0]['location']['latitude'] ?? null;
  210.                 $longitude $value['messages'][0]['location']['longitude'] ?? null;
  211.                 $name      $value['messages'][0]['location']['name'] ?? null;
  212.                 $address   $value['messages'][0]['location']['address'] ?? null;
  213.                 if ($latitude && $longitude) {
  214.                     $contenu "Localisation reçue :\n";
  215.                     $contenu .= "Latitude : $latitude\n";
  216.                     $contenu .= "Longitude : $longitude\n";
  217.                     if ($name) {
  218.                         $contenu .= "Nom : $name\n";
  219.                     }
  220.                     if ($address) {
  221.                         $contenu .= "Adresse : $address\n";
  222.                     }
  223.                     $contenu .= "Lien Google Maps : https://www.google.com/maps?q=$latitude,$longitude";
  224.                     $message->setLatitude($latitude);
  225.                     $message->setIdTypeMessage($TypeMessageRepository->findOneBy(['id'=>6]));
  226.                     $message->setLongitude($longitude);
  227.                     $message->setContenus("Localisation envoyée par le client");
  228.                 }else {
  229.                     $this->MessageSimple("Echec"$numero);
  230.                 }
  231.                 break;
  232.         case 'sticker':
  233.             $stickerId  $value['messages'][0]['sticker']['id'] ?? null;
  234.             $mimeType   $value['messages'][0]['sticker']['mime_type'] ?? 'image/webp';
  235.             if ($stickerId) {
  236.                 $extension explode('/'$mimeType)[1] ?? 'webp';
  237.                 $stickerPath $this->downloadWhatsAppMedia(
  238.                     $stickerId,
  239.                     $httpClient,
  240.                     'stickers',
  241.                     $extension
  242.                 );
  243.                 $message->addImage($stickerPath);
  244.                 $message->setIdTypeMessage($TypeMessageRepository->findOneBy(['id'=>7]));
  245.                 $message->setContenus("Sticker envoyé");
  246.             }
  247.             break;
  248.             default:
  249.                 $message->setContenus("Type de message non supporté : ".$typeMessage);
  250.                 break;
  251.         }
  252.         
  253.         $entityManager->persist($message);
  254.         $entityManager->flush();
  255.         $this->MessageSimple("enregistrement effectué"$numero);
  256.         return new Response('EVENT_RECEIVED'200);
  257.         
  258.     }
  259.     //fonction fin convertion
  260.     #[Route('/fin/garbal/conversation'name'app_fin_garbal_conversation')]
  261.     public function FinConversation(Request $requestConversationRepository $ConversationRepositoryStatutConversationRepository $StatutConversationRepositoryEntityManagerInterface $entityManagerHttpClientInterface $httpClient): Response
  262.     {
  263.             
  264.         if ($request->request->count()>0){
  265.             $objet=$request->request->get('objet');
  266.             $commentaire=$request->request->get('commentaire');
  267.             $id=$request->request->get('id');
  268.             $conversation=$ConversationRepository->findOneBy(['id'=>$id]);
  269.             if (!$conversation) {
  270.                 return $this->redirectToRoute('app_whatsapp_communication', [], Response::HTTP_SEE_OTHER);
  271.             }
  272.             
  273.             if ($objet==1) {
  274.                 $conversation->setObjet("AGRO METEO");
  275.             }elseif ($objet==2) {
  276.                 $conversation->setObjet("APPUIS CONSEIL");
  277.             }elseif ($objet==3) {
  278.                 $conversation->setObjet("PRIX");
  279.             }else {
  280.                 $conversation->setObjet("AUTRE");
  281.             }
  282.             $conversation->setCommentaire($commentaire);
  283.             $conversation->setDateFinConversation(new DateTimeImmutable());
  284.             $conversation->setIdStatutConversation($StatutConversationRepository->findOneBy(['id'=>3]));
  285.             $entityManager->persist($conversation);
  286.             
  287.             $entityManager->flush();
  288.         }
  289.         return $this->redirectToRoute('app_whatsapp_communication', [], Response::HTTP_SEE_OTHER);
  290.         
  291.     }
  292.     private function downloadWhatsAppMedia($mediaIdHttpClientInterface $httpClient$folder 'media'$extension 'bin')
  293.     {
  294.         $token $_ENV['WHATSAPP_TOKEN'];
  295.         try {
  296.             // 1. Récupérer les infos du média
  297.             $response $httpClient->request(
  298.                 'GET',
  299.                 "https://graph.facebook.com/v22.0/$mediaId",
  300.                 [
  301.                     'headers' => [
  302.                         'Authorization' => 'Bearer '.$token
  303.                     ]
  304.                 ]
  305.             );
  306.             if ($response->getStatusCode() !== 200) {
  307.                 throw new \Exception('Erreur récupération metadata média');
  308.             }
  309.             $mediaData $response->toArray(false);
  310.             if (!isset($mediaData['url'])) {
  311.                 throw new \Exception('URL média introuvable');
  312.             }
  313.             $mediaUrl $mediaData['url'];
  314.             // 2. Télécharger le fichier
  315.             $mediaResponse $httpClient->request(
  316.                 'GET',
  317.                 $mediaUrl,
  318.                 [
  319.                     'headers' => [
  320.                         'Authorization' => 'Bearer '.$token
  321.                     ]
  322.                 ]
  323.             );
  324.             if ($mediaResponse->getStatusCode() !== 200) {
  325.                 throw new \Exception('Erreur téléchargement média');
  326.             }
  327.             $content $mediaResponse->getContent();
  328.             // 3. Sécuriser extension
  329.             if (!$extension) {
  330.                 $extension 'bin';
  331.             }
  332.             // 4. Créer dossier si inexistant
  333.             $basePath $this->getParameter('messages_directory');
  334.             $folderPath $basePath '/' $folder;
  335.             if (!is_dir($folderPath)) {
  336.                 mkdir($folderPath0777true);
  337.             }
  338.             // 5. Générer nom fichier
  339.             $newFilename $folder.'_'.uniqid().'.'.$extension;
  340.             $filePath $folderPath '/' $newFilename;
  341.             // 6. Sauvegarde
  342.             file_put_contents($filePath$content);
  343.             return $folder '/' $newFilename;
  344.         } catch (\Exception $e) {
  345.             // 🔥 LOG IMPORTANT
  346.             file_put_contents(
  347.                 $this->getParameter('kernel.project_dir').'/var/log/whatsapp_error.log',
  348.                 date('Y-m-d H:i:s').' - '.$e->getMessage().PHP_EOL,
  349.                 FILE_APPEND
  350.             );
  351.             return null;
  352.         }
  353.     }
  354.     // private function downloadWhatsAppMedia($mediaId, $httpClient, $folder, $extension)
  355.     // {
  356.     //     $token = $_ENV['WHATSAPP_TOKEN'];
  357.     //     $response = $httpClient->request(
  358.     //         'GET',
  359.     //         "https://graph.facebook.com/v22.0/$mediaId",
  360.     //         [
  361.     //             'headers' => [
  362.     //                 'Authorization' => 'Bearer '.$token
  363.     //             ]
  364.     //         ]
  365.     //     );
  366.     //     $mediaData = $response->toArray();
  367.     //     $mediaUrl = $mediaData['url'];
  368.     //     $mediaResponse = $httpClient->request(
  369.     //         'GET',
  370.     //         $mediaUrl,
  371.     //         [
  372.     //             'headers' => [
  373.     //                 'Authorization' => 'Bearer '.$token
  374.     //             ]
  375.     //         ]
  376.     //     );
  377.     //     $content = $mediaResponse->getContent();
  378.     //     $newFilename = $folder.'_'.uniqid().'.'.$extension;
  379.     //     $filePath = $this->getParameter('messages_directory').'/'.$newFilename;
  380.     //     file_put_contents($filePath, $content);
  381.     //     return $newFilename;
  382.     // }
  383.     private function downloadWhatsAppVideo(string $mediaIdHttpClientInterface $httpClientstring $folderstring $extension ): ?string
  384.     {
  385.         $token $_ENV['EAAesTlijMGcBQtdhdKedpB4DqNDFsDVcuBb8Kcx3zETgu8pMjX67hpliaoL2wAHjgZAJZAo0rPblwFesxiJXqm19ZC5mjQdixA5oYqjpoVYnbq97dqOMnNR8qoT2QqIcaraJDLHdZBd52UTEcxj8qTRT82iqy0GyOltkXdZBtBgrKUc3f1TpHRXHQOZBw3gt7kewZDZD'];
  386.         //  Récupérer l'URL temporaire
  387.         $response $httpClient->request(
  388.             'GET',
  389.             "https://graph.facebook.com/v22.0/$mediaId",
  390.             [
  391.                 'headers' => [
  392.                     'Authorization' => 'Bearer ' $token
  393.                 ]
  394.             ]
  395.         );
  396.         if ($response->getStatusCode() !== 200) {
  397.             return null;
  398.         }
  399.         $mediaData $response->toArray();
  400.         $mediaUrl $mediaData['url'];
  401.         // 2️⃣ Télécharger le fichier
  402.         $mediaResponse $httpClient->request(
  403.             'GET',
  404.             $mediaUrl,
  405.             [
  406.                 'headers' => [
  407.                     'Authorization' => 'Bearer ' $token
  408.                 ]
  409.             ]
  410.         );
  411.         if ($mediaResponse->getStatusCode() !== 200) {
  412.             return null;
  413.         }
  414.         $content $mediaResponse->getContent();
  415.         // 3️⃣ Créer dossier si inexistant
  416.         $uploadDir $this->getParameter('kernel.project_dir') . '/public/uploads/' $folder;
  417.         if (!is_dir($uploadDir)) {
  418.             mkdir($uploadDir0777true);
  419.         }
  420.         $fileName uniqid() . '.' $extension;
  421.         $filePath $uploadDir '/' $fileName;
  422.         file_put_contents($filePath$content);
  423.         
  424.         file_put_contents($filePath$audioContent);
  425.         return '/uploads/video/' $folder '/' $fileName;
  426.     }
  427.     private function downloadWhatsAppDocumentstring $mediaIdHttpClientInterface $httpClientstring $originalFilename null ): ?string
  428.     {
  429.         $token $_ENV['EAAesTlijMGcBQtdhdKedpB4DqNDFsDVcuBb8Kcx3zETgu8pMjX67hpliaoL2wAHjgZAJZAo0rPblwFesxiJXqm19ZC5mjQdixA5oYqjpoVYnbq97dqOMnNR8qoT2QqIcaraJDLHdZBd52UTEcxj8qTRT82iqy0GyOltkXdZBtBgrKUc3f1TpHRXHQOZBw3gt7kewZDZD'];
  430.         // 1️⃣ Récupérer l’URL temporaire via Graph API v22.0
  431.         $response $httpClient->request(
  432.             'GET',
  433.             "https://graph.facebook.com/v22.0/$mediaId",
  434.             [
  435.                 'headers' => [
  436.                     'Authorization' => 'Bearer ' $token
  437.                 ]
  438.             ]
  439.         );
  440.         if ($response->getStatusCode() !== 200) {
  441.             return null;
  442.         }
  443.         $mediaData $response->toArray();
  444.         $mediaUrl $mediaData['url'] ?? null;
  445.         if (!$mediaUrl) {
  446.             return null;
  447.         }
  448.         // 2️⃣ Télécharger le fichier réel
  449.         $fileResponse $httpClient->request(
  450.             'GET',
  451.             $mediaUrl,
  452.             [
  453.                 'headers' => [
  454.                     'Authorization' => 'Bearer ' $token
  455.                 ]
  456.             ]
  457.         );
  458.         if ($fileResponse->getStatusCode() !== 200) {
  459.             return null;
  460.         }
  461.         $content $fileResponse->getContent();
  462.         // 3️⃣ Déterminer l’extension
  463.         $extension pathinfo($originalFilenamePATHINFO_EXTENSION);
  464.         if (!$extension) {
  465.             $extension 'bin';
  466.         }
  467.         // 4️⃣ Créer dossier si inexistant
  468.         $uploadDir $this->getParameter('kernel.project_dir') . '/public/uploads/documents';
  469.         if (!is_dir($uploadDir)) {
  470.             mkdir($uploadDir0777true);
  471.         }
  472.         // 5️⃣ Générer nom unique
  473.         $fileName uniqid() . '.' $extension;
  474.         $filePath $uploadDir '/' $fileName;
  475.         file_put_contents($filePath$content);
  476.         return '/uploads/documents/' $fileName;
  477.     }
  478.      public function MessageSimple(string $contenusstring $numero)
  479.     {
  480.         $numero ltrim($numero'+');
  481.         $apiUrl 'https://graph.facebook.com/v22.0/1037760686078257/messages';
  482.         $token 'EAAesTlijMGcBQtdhdKedpB4DqNDFsDVcuBb8Kcx3zETgu8pMjX67hpliaoL2wAHjgZAJZAo0rPblwFesxiJXqm19ZC5mjQdixA5oYqjpoVYnbq97dqOMnNR8qoT2QqIcaraJDLHdZBd52UTEcxj8qTRT82iqy0GyOltkXdZBtBgrKUc3f1TpHRXHQOZBw3gt7kewZDZD';
  483.         $data = [
  484.             "messaging_product" => "whatsapp",   
  485.             // "recipient_type": "individual",
  486.             "to" => $numero,
  487.             "type" => "text",
  488.             "text" => [
  489.                 "preview_url" => false,
  490.                 "body" => $contenus
  491.             ]
  492.         ];
  493.         $ch curl_init();
  494.         curl_setopt_array($ch, [
  495.             CURLOPT_URL => $apiUrl,
  496.             CURLOPT_RETURNTRANSFER => true,
  497.             CURLOPT_POST => true,
  498.             CURLOPT_TIMEOUT => 10,
  499.       CURLOPT_CUSTOMREQUEST => 'POST',
  500.             CURLOPT_HTTPHEADER => [
  501.                 "Authorization: Bearer $token",
  502.                 "Content-Type: application/json"
  503.             ],
  504.             CURLOPT_POSTFIELDS => json_encode($data)
  505.         ]);
  506.         $response curl_exec($ch);
  507.         $httpCode curl_getinfo($chCURLINFO_HTTP_CODE);
  508.         if (curl_errno($ch)) {
  509.             dump("Curl error: " curl_error($ch));
  510.         }
  511.         curl_close($ch);
  512.         dump("HTTP CODE: " $httpCode);
  513.         dump("RESPONSE: " $response);
  514.         return $response;
  515.     }
  516.     #[Route('/message/communication'name'app_message_communication'methods: ['GET''POST'])]
  517.     public function MessageCommunication(Request $request,SessionRepository $SessionRepository,ClientRepository $ClientRepository,EntityManagerInterface $entityManager): Response 
  518.     {
  519.    
  520.         // $json = $request->getContent();
  521.         // $data = json_decode($json, true);
  522.         // if (!$data || !isset($data['entry'][0]['changes'][0]['value']['messages'][0])) {
  523.         //     return new Response("No message", 200);
  524.         // }
  525.         // $messages = $data['entry'][0]['changes'][0]['value']['messages'][0];
  526.         // $name = $data['entry'][0]['changes'][0]['value']['contacts'][0]['profile']['name'];
  527.         // $number = $messages['from'];
  528.         // $typeMessage = $messages['type'];
  529.         // $body = "";
  530.         // if (isset($messages['text']['body'])) {
  531.         //     $body = trim($messages['text']['body']);
  532.         // }
  533.         // $client = $ClientRepository->findOneBy(['telephone' => $number, 'statut' => 1]);
  534.         // if (!$client) {
  535.         //     $client = new Client();
  536.         //     $client->setNomPrenom($name);
  537.         //     $client->setTelephone($number);
  538.         //     $client->setAdresse("");
  539.         //     $client->setCreatedAt(new DateTimeImmutable());
  540.         //     $client->setStatut(1);
  541.         //     $entityManager->persist($client);
  542.         //     $entityManager->flush();
  543.         // }
  544.         // $session = $SessionRepository->findOneBy(['idClient' => $client->getId(), 'statut' => 1]);
  545.         // if ($body === "Merci" || $body === "Au revoir") {
  546.         //     if ($session) {
  547.         //         $session->setStatut(0);
  548.         //         $session->setDeletedAt(new DateTimeImmutable());
  549.         //         $entityManager->flush();
  550.         //     }
  551.         //     $this->envoyerSimpleMessage(
  552.         //         "*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ très bientôt !",
  553.         //         $number
  554.         //     );
  555.         //     return new Response("", 200);
  556.         // }
  557.         // if (!$session) {
  558.         //     // Ignorer tout ce qui n'est pas un texte
  559.         //     if ($typeMessage !== "text") {
  560.         //         return new Response("", 200);
  561.         //     }
  562.         //     $body = trim($messages['text']['body']);
  563.         //     // Ne pas recréer une session si l'utilisateur dit encore un mot de fin
  564.         //     if ($body === "Merci" || $body === "Au revoir") {
  565.         //         return new Response("", 200);
  566.         //     }
  567.         //     $session = new Session();
  568.         //     $session->setIdClient($client);
  569.         //     $session->setEtape(0);
  570.         //     $session->setTempsConnexion(0);
  571.         //     $session->setCreatedAt(new DateTimeImmutable());
  572.         //     $session->setStatut(1);
  573.         //     $entityManager->persist($session);
  574.         //     $entityManager->flush();
  575.         //     $text = "Bonjour bienvenue *{$name}*\nje suis votre assistante de service *GARBAL*, c'est un plaisir de vous accueillir parmi nous. Je suis là pour vous accompagner à chaque étape.";
  576.         //     $this->MessageChoixService($text, $number);
  577.         //     return new Response("", 200);
  578.         // }
  579.         // if ($session->getEtape() == 0) {
  580.         //     if ($typeMessage == 'interactive') {
  581.         //         $choix = $messages['interactive']['list_reply']['id'];
  582.         //         $session->setService($choix);
  583.         //         $session->setEtape(1);
  584.         //         $entityManager->flush();
  585.         //         switch ($choix) {
  586.         //             case "Sc_001":
  587.         //                 $agrometeo = new RechercheAgroMeteo();
  588.         //                 $agrometeo->setIdSession($session);
  589.         //                 $agrometeo->setEtape(0);
  590.         //                 $agrometeo->setCreatedAt(new DateTimeImmutable());
  591.         //                 $agrometeo->setStatut(1);
  592.         //                 $entityManager->persist($agrometeo);
  593.         //                 $entityManager->flush();
  594.         //                 $this->ChoixInformation("Veuillez choisir le type d'information souhaité.", $number);
  595.         //                 break;
  596.         //             case "Sc_002":
  597.         //                 $app = new RechercheAppuisConseil();
  598.         //                 $app->setIdSession($session);
  599.         //                 $app->setEtape(0);
  600.         //                 $app->setCreatedAt(new DateTimeImmutable());
  601.         //                 $app->setStatut(1);
  602.         //                 $entityManager->persist($app);
  603.         //                 $entityManager->flush();
  604.         //                 $this->ChoixDomaine($number);
  605.         //                 break;
  606.         //             case "Sc_003":
  607.         //                 $prix = new RecherchePrix();
  608.         //                 $prix->setIdSession($session);
  609.         //                 $prix->setEtape(0);
  610.         //                 $prix->setCreatedAt(new DateTimeImmutable());
  611.         //                 $prix->setStatut(1);
  612.         //                 $entityManager->persist($prix);
  613.         //                 $entityManager->flush();
  614.         //                 $this->EnvoyerListeCategories("Veuillez choisir le type d'information souhaité.", $number);
  615.         //                 break;
  616.         //             default:
  617.         //                 $this->envoyerSimpleMessage("Désolé, choix inconnu.", $number);
  618.         //         }
  619.         //         return new Response("", 200);
  620.         //     }
  621.         //     // Pas interactif
  622.         //     $this->envoyerSimpleMessage("Veuillez faire un choix.", $number);
  623.         //     return new Response("", 200);
  624.         // }
  625.         // switch ($session->getService()) {
  626.         //     case "Sc_001":
  627.         //         $this->TraiterAgroMeteo($data, $session, $entityManager);
  628.         //         break;
  629.         //     case "Sc_002":
  630.         //         $this->TraiterAppuisConseil($data, $session, $entityManager);
  631.         //         break;
  632.         //     case "Sc_003":
  633.         //         $this->TraiterPrix($data, $session, $entityManager);
  634.         //         break;
  635.         //     default:
  636.         //         $this->envoyerSimpleMessage("Choix non reconnu.", $number);
  637.         // }
  638.         // return new Response("", 200);
  639.     }
  640.     public function TraiterPrix($data$session$entityManager)
  641.     {
  642.         $messages $data['entry'][0]['changes'][0]['value']['messages'][0];
  643.         $number $messages['from'];
  644.         $typeMessage $messages['type'];
  645.         if ($typeMessage === "text") {
  646.             $texte trim($messages['text']['body']);
  647.             if ($texte === "Merci" || $texte === "Au revoir") {
  648.                 $session->setStatut(0);
  649.                 $session->setDeletedAt(new DateTimeImmutable());
  650.                 $entityManager->persist($session);
  651.                 $entityManager->flush();
  652.                 $this->envoyerSimpleMessage(
  653.                     "*Session expirée*\nMerci d'avoir utilisé notre service prix.\nÀ très bientôt.",
  654.                     $number
  655.                 );
  656.                 return;
  657.             }
  658.         }
  659.         $prixSession $entityManager->getRepository(RecherchePrix::class)
  660.             ->findOneBy(['idSession' => $session->getId(), 'statut' => 1]);
  661.         if (!$prixSession) {
  662.             $this->envoyerSimpleMessage("Aucune session."$number);
  663.                 return;
  664.         }
  665.         /*  ÉTAPE 0 : CHOIX CATÉGORIE  */
  666.         if ($prixSession->getEtape() == 0) {
  667.             if (isset($messages['interactive']['list_reply']['id'])) {
  668.                 $choix $messages['interactive']['list_reply']['id'];
  669.                 if ($choix === "Pc_001") {
  670.                     $prixSession->setType("AGRICULTURE");
  671.                     $prixSession->setEtape(1);
  672.                     $entityManager->flush();
  673.                     $this->envoyerSimpleMessage(
  674.                         "Vous avez choisi *AGRO ALIMENTAIRE*.\n\nVeuillez saisir le nom d'une commune :",
  675.                         $number
  676.                     );
  677.                     return;
  678.                 }
  679.                 if ($choix === "Pc_002") {
  680.                     $prixSession->setType("BETAIL");
  681.                     $prixSession->setEtape(1);
  682.                     $entityManager->flush();
  683.                     $this->envoyerSimpleMessage(
  684.                         "Vous avez choisi *ANIMAUX / BÉTAIL*.\n\nVeuillez saisir le nom d'une commune :",
  685.                         $number
  686.                     );
  687.                     return;
  688.                 }
  689.                 $this->envoyerSimpleMessage("Choix invalide, veuillez réessayer."$number);
  690.                 return;
  691.             }
  692.             // Si aucun choix reçu, envoyer la liste de catégories
  693.             $this->EnvoyerListeCategories("Veuillez choisir une catégorie :"$number);
  694.             return;
  695.         }
  696.         /* ÉTAPE 1 : RECHERCHE DE COMMUNE */
  697.         if ($prixSession->getEtape() == ) {
  698.             if ($typeMessage !== "text") {
  699.                 $this->envoyerSimpleMessage(
  700.                     "Veuillez saisir un nom de commune sous forme de texte.",
  701.                     $number
  702.                 );
  703.                 return;
  704.             }
  705.             $texteRecu trim($messages['text']['body']);
  706.             $listeCommunes $this->AppelApiRechercheCommunes($texteRecu);
  707.             if (empty($listeCommunes)) {
  708.                 $this->envoyerSimpleMessage(
  709.                     "Aucune commune trouvée pour *$texteRecu*.\nVeuillez saisir un autre nom.",
  710.                     $number
  711.                 );
  712.                 return;
  713.             }
  714.             // Stocker la liste pour sélection
  715.             $prixSession->setListeResultat(json_encode($listeCommunes));
  716.             $prixSession->setEtape(2);
  717.             $entityManager->flush();
  718.             $this->EnvoyerListeCommunes($listeCommunes$number);
  719.             return;
  720.         }
  721.         /*  ÉTAPE 2 : CHOIX D'UNE COMMUNE */
  722.         if ($prixSession->getEtape() == && $typeMessage === "text") {
  723.             $choix trim($messages['text']['body']);
  724.             if (!ctype_digit($choix)) {
  725.                 $this->envoyerSimpleMessage("Veuillez saisir un numéro valide."$number);
  726.                 return;
  727.             }
  728.             $listeCommunes json_decode($prixSession->getListeResultat(), true);
  729.             $index intval($choix) - 1;
  730.             if (!isset($listeCommunes[$index])) {
  731.                 $this->envoyerSimpleMessage("Numéro invalide. Veuillez réessayer."$number);
  732.                 return;
  733.             }
  734.             $commune $listeCommunes[$index];
  735.             $prixSession->setCommune($commune['id']);
  736.             $prixSession->setListeResultat(null);
  737.             $prixSession->setEtape(3);
  738.             $entityManager->flush();
  739.             /* les prix selon la catégorie */
  740.             if ($prixSession->getType() === "AGRICULTURE") {
  741.                 $listePrix $this->AppelApiPrixProduitsAgricoles($commune['id']);
  742.                 $this->EnvoyerPrixProduitsAgricoles($listePrix$number);
  743.                 $prixSession->setStatut(0);
  744.                 $prixSession->setDeletedAt(new DateTimeImmutable());
  745.                 $session->setStatut(0);
  746.                 $session->setDeletedAt(new DateTimeImmutable());
  747.                 $entityManager->persist($session);
  748.                 $entityManager->flush();
  749.                 $this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !"$number);
  750.                 return;
  751.             }
  752.             if ($prixSession->getType() === "BETAIL") {
  753.                 $listePrix $this->AppelApiPrixBetail($commune['id']);
  754.                 $this->EnvoyerPrixBetail($listePrix$number);
  755.                 $prixSession->setStatut(0);
  756.                 $prixSession->setDeletedAt(new DateTimeImmutable());
  757.                 $session->setStatut(0);
  758.                 $session->setDeletedAt(new DateTimeImmutable());
  759.                 $entityManager->persist($session);
  760.                 $entityManager->flush();
  761.                 $this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !"$number);
  762.                 return;
  763.             }
  764.             return;
  765.         }
  766.         /* ERREUR PAR DÉFAUT  */
  767.         $this->envoyerSimpleMessage("Désolé, je n'ai pas reconnu votre choix."$number);
  768.         return;
  769.     }
  770.     
  771.     public function EnvoyerListeCommunes(array $listeCommunesstring $number)
  772.     {
  773.         if (empty($listeCommunes)) {
  774.             $this->envoyerSimpleMessage("Aucune commune trouvée. Veuillez réessayer."$number);
  775.             return;
  776.         }
  777.         $message "*Communes trouvées :*\n\n";
  778.         $i 1;
  779.         foreach ($listeCommunes as $commune) {
  780.             $message .= "👉 Tapez *".$i."* pour *".$commune['libelle']."*\n";
  781.             $i++;
  782.         }
  783.         $message .= "\n*Tapez le numéro* correspondant à votre commune.";
  784.         // CORRECTION : utiliser $number et NON $numero
  785.         $this->envoyerSimpleMessage($message$number);
  786.     }
  787.     public function AppelApiRechercheCommunes(string $texte): array 
  788.     {  
  789.         //Authentification API 
  790.         $auth $this->fonct->execPost('''api/authentification'json_encode([
  791.             "email" => "djafarasakinatou@gmail.com",
  792.             "password" => "l2323"
  793.         ]));
  794.           
  795.         //Appel API de recherche des communes 
  796.         $response $this->fonct->execPost$auth['data']['token'], 'api/communes/recherche'json_encode([ "commune" => $texte ]) );  
  797.        
  798.         //Vérification réponse 
  799.         if (!isset($response['status']) || $response['status'] != 200
  800.         { 
  801.             return []; 
  802.         }  
  803.         //Retourne la liste des résultats 
  804.         return $response['results'] ?? []; 
  805.     }
  806.     public function AppelApiPrixBetail(string $idCommune): array 
  807.     { 
  808.         // Authentification API 
  809.         $auth $this->fonct->execPost('''api/authentification'json_encode([
  810.             "email" => "djafarasakinatou@gmail.com",
  811.             "password" => "l2323"
  812.         ]));
  813.         // Appel API Prix Bétail 
  814.         $response $this->fonct->execPost$auth['data']['token'], 'api/prix/animaux'json_encode([ "id_commune" => $idCommune ]) ); 
  815.         if (!isset($response['status']) || $response['status'] != 200
  816.         { 
  817.             return []; 
  818.         } 
  819.         return $response['data'] ?? []; 
  820.     }
  821.     public function AppelApiPrixProduitsAgricoles(string $idCommune): array
  822.     {
  823.         // Authentification API
  824.         $auth $this->fonct->execPost('''api/authentification'json_encode([
  825.             "email" => "djafarasakinatou@gmail.com",
  826.             "password" => "l2323"
  827.         ]));
  828.         // Appel API Prix Produits Agricoles
  829.         $response $this->fonct->execPost(
  830.             $auth['data']['token'],
  831.             'api/prix/produit/agricole',
  832.             json_encode([
  833.                 "id_commune" => $idCommune,
  834.                 "id_semaine" => "" // ton API prend automatiquement la semaine active
  835.             ])
  836.         );
  837.         // Vérification du status
  838.         if (!isset($response['status']) || $response['status'] != 200) {
  839.             return [];
  840.         }
  841.         // Retour des données
  842.         return $response['data'] ?? [];
  843.     }
  844.     public function EnvoyerListeCategories(string $textstring $number
  845.     { 
  846.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages';
  847.         $token 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
  848.         
  849.         $payload = [ 
  850.             "messaging_product" => "whatsapp"
  851.             "to" => $number
  852.             "type" => "interactive"
  853.             "interactive" => [ 
  854.                 "type" => "list",
  855.                 "body" => [ 
  856.                     "text" => $text 
  857.                 ], 
  858.                 "footer" => [ 
  859.                     "text" => "Pour arrêter le processus tapez merci ou au revoir" 
  860.                 ], 
  861.                 "action" => [ 
  862.                     "button" => "Catégories"
  863.                     "sections" => [ 
  864.                         [ 
  865.                             "title" => "Catégories disponibles"
  866.                             "rows" => [ 
  867.                                 [ 
  868.                                     "id" => "Pc_001"
  869.                                     "title" => "AGRO ALIMENT"
  870.                                     "description" => "Prix des aliments d'une localité du Niger" 
  871.                                 ],
  872.                                 [ 
  873.                                     "id" => "Pc_002"
  874.                                     "title" => "ANIMAUX"
  875.                                     "description" => "Prix du bétail d'une localité du Niger" 
  876.                                 
  877.                             ] 
  878.                         ] 
  879.                     ] 
  880.                 ] 
  881.             ] 
  882.         ]; 
  883.         try { 
  884.             $response $this->client->request('POST'$apiUrl, [ 
  885.                 'headers' => [ 
  886.                     'Authorization' => 'Bearer ' $token
  887.                     'Content-Type' => 'application/json'
  888.                 ], 
  889.                 'json' => $payload
  890.             ]); 
  891.             $result $response->toArray(false); 
  892.             return $result;
  893.         } catch (\Exception $e) {
  894.             return ['error' => $e->getMessage()];
  895.         }
  896.     }
  897.     public function EnvoyerPrixBetail(array $prixstring $number)
  898.     {
  899.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages';
  900.         $token 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
  901.         // Construction du message
  902.         if (empty($prix)) {
  903.             $texte " *Aucun prix de bétail trouvé pour cette commune.*";
  904.         } else {
  905.             $texte " *Prix du Bétail*\n\n";
  906.             foreach ($prix as $item) {
  907.                 $texte .= " *" $item["animal"] . "*\n";
  908.                 $texte .= " Prix : " $item["prix"] . " FCFA\n";
  909.                 $texte .= "-------------------------\n";
  910.             }
  911.         }
  912.         $payload = [
  913.             "messaging_product" => "whatsapp",
  914.             "to" => $number,
  915.             "type" => "text",
  916.             "text" => [
  917.                 "body" => $texte
  918.             ]
  919.         ];
  920.         try {
  921.             $response $this->client->request('POST'$apiUrl, [
  922.                 'headers' => [
  923.                     'Authorization' => 'Bearer ' $token,
  924.                     'Content-Type' => 'application/json',
  925.                 ],
  926.                 'json' => $payload,
  927.             ]);
  928.             return $response->toArray();
  929.         } catch (\Exception $e) {
  930.             return ['error' => $e->getMessage()];
  931.         }
  932.     }
  933.     
  934.     public function EnvoyerPrixProduitsAgricoles(array $prixstring $number
  935.     { 
  936.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages'
  937.         $token 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD'
  938.         // Construction du message 
  939.         if (empty($prix)) 
  940.         { 
  941.             $texte " *Aucun prix de produit agricole trouvé pour cette commune.*"
  942.         } else 
  943.         { 
  944.             $texte " *Prix des produits agricoles*\n\n"
  945.             foreach ($prix as $item
  946.             { 
  947.                 $texte .= " *" $item["produit"] . "*\n"
  948.                 $texte .= " Prix : " $item["prix"] . " FCFA\n"
  949.                 $texte .= "-------------------------\n"
  950.             } 
  951.         } 
  952.         $payload = [ 
  953.             "messaging_product" => "whatsapp"
  954.             "to" => $number
  955.             "type" => "text"
  956.             "text" => [ 
  957.                 "body" => $texte 
  958.             
  959.         ]; 
  960.         try 
  961.         {
  962.             $response $this->client->request('POST'$apiUrl, [ 'headers' => [ 'Authorization' => 'Bearer ' $token'Content-Type' => 'application/json', ], 'json' => $payload, ]); 
  963.             return $response->toArray(); 
  964.         } catch (\Exception $e
  965.         { 
  966.             return ['error' => $e->getMessage()]; 
  967.         } 
  968.     }
  969.     public function TraiterAgroMeteo($data,$session,$entityManager)
  970.     {
  971.         $messages $data['entry'][0]['changes'][0]['value']['messages'][0];
  972.         $number $messages['from'];
  973.         $typeMessage $messages['type'];
  974.         if ($typeMessage === "text") {
  975.             $texte trim($messages['text']['body']);
  976.             if ($texte === "Merci" || $texte === "Au revoir") {
  977.                 $session->setStatut(0);
  978.                 $session->setDeletedAt(new DateTimeImmutable());
  979.                 $entityManager->persist($session);
  980.                 $entityManager->flush();
  981.                 $this->envoyerSimpleMessage(
  982.                     "*Session expirée*\nMerci d'avoir utilisé notre service prix.\nÀ très bientôt.",
  983.                     $number
  984.                 );
  985.                 return;
  986.             }
  987.         }
  988.         $agrometeo $entityManager->getRepository(RechercheAgroMeteo::class)->findOneBy(['idSession' => $session->getId(),'statut' => 1]);
  989.         
  990.         
  991.            // Fin de session
  992.         // if ($agrometeo->getEtape()==3)
  993.         // {
  994.         //     $session->setStatut(0);
  995.         //     $session->setDeletedAt(new DateTimeImmutable());
  996.         //     $entityManager->flush();
  997.         //     $this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !", $number);
  998.         //     return;
  999.         // }
  1000.         
  1001.         if (!$agrometeo) {
  1002.             $this->envoyerSimpleMessage("Aucune session."$number);
  1003.                 return;
  1004.             // $agrometeo = new RechercheAgroMeteo();
  1005.             // $agrometeo->setIdSession($session);
  1006.             // $agrometeo->setEtape(0);            //etape 0 creation
  1007.             
  1008.             // $agrometeo->setCreatedAt(new DateTimeImmutable());
  1009.             // $agrometeo->setStatut(1);
  1010.             // $entityManager->persist($agrometeo);
  1011.             // $entityManager->flush();
  1012.             // // $text = "👉 Tapez 1 pour *Dates de semis*\n👉 Tapez 2 pour *Poches de sècheresse*\n👉 Tapez 3 pour *Début et fin de saison*\n👉 Tapez 4 pour *Alertes acridiennes et aviaires*\nVeuillez choisir le type d'information souhaité.";
  1013.             // $text = "Veuillez choisir le type d'information souhaité.";
  1014.             // $this->ChoixInformation($text,$number);
  1015.             // return;
  1016.         }
  1017.         if ($agrometeo->getEtape()==0) {
  1018.             if (isset($messages['interactive']['list_reply']['id'])) {
  1019.                 $choix $messages['interactive']['list_reply']['id'];
  1020.             } else {
  1021.                 $this->envoyerSimpleMessage("Veuillez sélectionner un type d'information dans la liste."$number);
  1022.                 return;
  1023.             }
  1024.             
  1025.             $agrometeo->setType($choix);
  1026.             $agrometeo->setEtape(1); // choix type info
  1027.             $entityManager->persist($agrometeo);
  1028.             $entityManager->flush();
  1029.             
  1030.             
  1031.             // $text = "Veuillez saissir la localité souhaitée.";
  1032.             // $this->envoyerSimpleMessage($text, $number);
  1033.             
  1034.         }
  1035.         if ($agrometeo->getEtape()==&& $agrometeo->getType()!=null) {// si etape 1 choix commune fait
  1036.             if ($typeMessage !== "text") {
  1037.                 $this->envoyerSimpleMessage("Veuillez saisir un nom de commune sous forme de texte.",$number);
  1038.                 return;
  1039.             }
  1040.             $texteRecu trim($messages['text']['body']);
  1041.             $listeCommunes $this->AppelApiRechercheCommunes($texteRecu);
  1042.                 if (empty($listeCommunes)) {
  1043.                     $this->envoyerSimpleMessage(
  1044.                         "Aucune commune trouvée pour *$texteRecu*.\nVeuillez saisir un autre nom.",
  1045.                         $number
  1046.                     );
  1047.                     return;
  1048.                 }
  1049.                 $agrometeo->setResultat(json_encode($listeCommunes));
  1050.                 $agrometeo->setEtape(2); //saissi commune
  1051.                 $entityManager->persist($agrometeo);
  1052.                 $entityManager->flush();
  1053.             $this->EnvoyerListeCommunes($listeCommunes$number);
  1054.             return;
  1055.         }
  1056.         if ($agrometeo->getEtape() == 2) {
  1057.             // $this->envoyerSimpleMessage("ok", $number);
  1058.             $userMessage trim($messages['text']['body']);
  1059.             if ($typeMessage !== "text") {
  1060.                 $this->envoyerSimpleMessage("Veuillez saisir un numéro."$number);
  1061.                 return;
  1062.             }
  1063.             if (!ctype_digit($messages['text']['body'])) {
  1064.                 $this->envoyerSimpleMessage("Numéro invalide."$number);
  1065.                 return;
  1066.             }
  1067.             $listeCommunes json_decode($agrometeo->getResultat(), true);
  1068.             $index intval($messages['text']['body']) - 1;
  1069.             if (!isset($listeCommunes[$index])) {
  1070.                 $this->envoyerSimpleMessage("Numéro invalide. Veuillez réessayer."$number);
  1071.                 return;
  1072.             }
  1073.             $commune $listeCommunes[$index];
  1074.             $idCommune=$commune['id'];
  1075.             // Enregistrer dans la base
  1076.             $agrometeo->setCommune($idCommune);
  1077.             $agrometeo->setEtape(3);
  1078.             $entityManager->flush();
  1079.             // Continue selon type
  1080.             if ($agrometeo->getType() == "In_01") {
  1081.                 
  1082.                 $this->EnvoyerDateSemis($idCommune$number);
  1083.                 $agrometeo->setStatut(0);
  1084.                 $agrometeo->setDeletedAt(new DateTimeImmutable());
  1085.                 $session->setStatut(0);
  1086.                 $session->setDeletedAt(new DateTimeImmutable());
  1087.                 $entityManager->persist($session);
  1088.                 $entityManager->flush();
  1089.                 $this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !"$number);
  1090.                 return;
  1091.             }
  1092.             if ($agrometeo->getType() == "In_02") {
  1093.                 
  1094.                 $this->EnvoyerPocheSecheresse($idCommune$number);
  1095.                 $agrometeo->setStatut(0);
  1096.                 $agrometeo->setDeletedAt(new DateTimeImmutable());
  1097.                 $session->setStatut(0);
  1098.                 $session->setDeletedAt(new DateTimeImmutable());
  1099.                 $entityManager->persist($session);
  1100.                 $entityManager->flush();
  1101.                 $this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !"$number);
  1102.                 return;
  1103.             }
  1104.             if ($agrometeo->getType() == "In_03") {
  1105.                 
  1106.                 $this->EnvoyerDateSaison($idCommune$number);
  1107.                 $agrometeo->setStatut(0);
  1108.                 $agrometeo->setDeletedAt(new DateTimeImmutable());
  1109.                 $session->setStatut(0);
  1110.                 $session->setDeletedAt(new DateTimeImmutable());
  1111.                 $entityManager->persist($session);
  1112.                 $entityManager->flush();
  1113.                 $this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !"$number);
  1114.                 return;
  1115.             }
  1116.             if ($agrometeo->getType() == "In_04") {
  1117.                 
  1118.                 $this->EnvoyerAlerte($idCommune$number);
  1119.                 $agrometeo->setStatut(0);
  1120.                 $agrometeo->setDeletedAt(new DateTimeImmutable());
  1121.                 $session->setStatut(0);
  1122.                 $session->setDeletedAt(new DateTimeImmutable());
  1123.                 $entityManager->persist($session);
  1124.                 $entityManager->flush();
  1125.                 $this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !"$number);
  1126.                 return;
  1127.             }
  1128.             return;
  1129.         }
  1130.     
  1131.     }
  1132.     public function EnvoyerDateSemis($idCommune$number)
  1133.     {   
  1134.         // Authentification
  1135.         $auth $this->fonct->execPost('''api/authentification'json_encode(["email"=> "djafarasakinatou@gmail.com","password"=> "l2323"]));
  1136.         //thématiques
  1137.         $responsesemis $this->fonct->execPost($auth['data']['token'],'api/date/semis',json_encode(["id_commune" => $idCommune]));
  1138.             // $this->envoyerSimpleMessage("ok", $number);
  1139.         if (!isset($responsesemis['data'])) {
  1140.             $this->envoyerSimpleMessage("Aucune donnée trouvée ."$number);
  1141.             return;
  1142.         }
  1143.         $msg "Information disponible:\n";
  1144.         foreach ($responsesemis['data'] as $semis) {
  1145.             $msg .= "*{$semis['information']}*\n\n";
  1146.         }
  1147.         $msg .= "\nPour arrêter tapez *merci* ou *au revoir*.";
  1148.         // Envoyer
  1149.         $this->envoyerSimpleMessage($msg$number);
  1150.     }
  1151.     public function EnvoyerPocheSecheresse($idCommune$number)
  1152.     {   
  1153.         
  1154.         // Authentification
  1155.         $auth $this->fonct->execPost('''api/authentification'json_encode(["email"=> "djafarasakinatou@gmail.com","password"=> "l2323"]));
  1156.         //thématiques
  1157.         $responsesemis $this->fonct->execPost($auth['data']['token'],'api/poche/secheresse',json_encode(["id_commune" => $idCommune]));
  1158.             // $this->envoyerSimpleMessage("ok", $number);
  1159.         // 🔍 DEBUG : voir ce que retourne l'API
  1160.         //$this->envoyerSimpleMessage("DEBUG : \n" . json_encode($responsesemis), $number);
  1161.         if (!isset($responsesemis['data'])) {
  1162.             $this->envoyerSimpleMessage("Aucune donnée trouvée ."$number);
  1163.             return;
  1164.         }
  1165.         $msg "Information disponible:\n";
  1166.         foreach ($responsesemis['data'] as $semis) {
  1167.             $msg .= "*{$semis['information']}*\n\n";
  1168.         }
  1169.         $msg .= "\nPour arrêter tapez *merci* ou *au revoir*.";
  1170.         // Envoyer
  1171.         $this->envoyerSimpleMessage($msg$number);
  1172.     }
  1173.        public function EnvoyerDateSaison($idCommune$number)
  1174.     {   
  1175.         // Authentification
  1176.         $auth $this->fonct->execPost('''api/authentification'json_encode(["email"=> "djafarasakinatou@gmail.com","password"=> "l2323"]));
  1177.         //thématiques
  1178.         $responsesemis $this->fonct->execPost($auth['data']['token'],'api/date/saison',json_encode(["id_commune" => $idCommune]));
  1179.             // $this->envoyerSimpleMessage("ok", $number);
  1180.         if (!isset($responsesemis['data'])) {
  1181.             $this->envoyerSimpleMessage("Aucune donnée trouvée ."$number);
  1182.             return;
  1183.         }
  1184.         $msg "Information disponible:\n";
  1185.         foreach ($responsesemis['data'] as $semis) {
  1186.             $msg .= "*{$semis['information']}*\n\n";
  1187.         }
  1188.         $msg .= "\nPour arrêter tapez *merci* ou *au revoir*.";
  1189.         // Envoyer
  1190.         $this->envoyerSimpleMessage($msg$number);
  1191.     }
  1192.     public function EnvoyerAlerte($idCommune$number)
  1193.     {   
  1194.         // Authentification
  1195.         $auth $this->fonct->execPost('''api/authentification'json_encode(["email"=> "djafarasakinatou@gmail.com","password"=> "l2323"]));
  1196.         //thématiques
  1197.         $responsesemis $this->fonct->execPost($auth['data']['token'],'api/alerte',json_encode(["id_commune" => $idCommune]));
  1198.             // $this->envoyerSimpleMessage("ok", $number);
  1199.         if (!isset($responsesemis['data'])) {
  1200.             $this->envoyerSimpleMessage("Aucune donnée trouvée ."$number);
  1201.             return;
  1202.         }
  1203.         $msg "Information disponible:\n";
  1204.         foreach ($responsesemis['data'] as $semis) {
  1205.             $msg .= "*{$semis['information']}*\n\n";
  1206.         }
  1207.         $msg .= "\nPour arrêter tapez *merci* ou *au revoir*.";
  1208.         // Envoyer
  1209.         $this->envoyerSimpleMessage($msg$number);
  1210.     }
  1211.     public function TraiterAppuisConseil($data$session$entityManager)
  1212.     {
  1213.         $messages $data['entry'][0]['changes'][0]['value']['messages'][0];
  1214.         $number $messages['from'];
  1215.         $typeMessage $messages['type'];
  1216.         if ($typeMessage === "text") {
  1217.             $texte trim($messages['text']['body']);
  1218.             if ($texte === "Merci" || $texte === "Au revoir") {
  1219.                 $session->setStatut(0);
  1220.                 $session->setDeletedAt(new DateTimeImmutable());
  1221.                 $entityManager->persist($session);
  1222.                 $entityManager->flush();
  1223.                 $this->envoyerSimpleMessage(
  1224.                     "*Session expirée*\nMerci d'avoir utilisé notre service prix.\nÀ très bientôt.",
  1225.                     $number
  1226.                 );
  1227.                 return;
  1228.             }
  1229.         }
  1230.         $apuisconseil $entityManager->getRepository(RechercheAppuisConseil::class)->findOneBy(['idSession' => $session->getId(), 'statut' => 1]);
  1231.         if (!$apuisconseil) {
  1232.             $this->envoyerSimpleMessage("Aucune session."$number);
  1233.                 return;
  1234.         }
  1235.         if ($apuisconseil->getEtape() == 0) {
  1236.             // Récupère le choix domaine depuis interactive ou texte
  1237.             
  1238.             if (isset($messages['interactive']['list_reply']['id'])) {
  1239.                 $choix $messages['interactive']['list_reply']['id'];
  1240.             } else {
  1241.                 $this->envoyerSimpleMessage("Veuillez sélectionner un type d'information dans la liste."$number);
  1242.                 return;
  1243.             }
  1244.             $theme $this->thematiqueTrouver($choix);
  1245.                 if (empty($theme)) {
  1246.                     $this->envoyerSimpleMessage(
  1247.                         "Aucun thème trouvé.",
  1248.                         $number
  1249.                     );
  1250.                     return;
  1251.                 }
  1252.             $apuisconseil->setResultat(json_encode($theme));
  1253.             $apuisconseil->setDomaine($choix);
  1254.             $apuisconseil->setEtape(1); // étape thématique
  1255.             $entityManager->flush();
  1256.             $this->EnvoyerListeThematique($choix$number);
  1257.             return;
  1258.         }
  1259.         if ($apuisconseil->getEtape() == && $typeMessage == "text") {
  1260.             
  1261.             
  1262.             $choixThematique trim($messages['text']['body']);
  1263.            
  1264.             // Vérifie que le choix est un ID numérique ou valide
  1265.             if (!ctype_digit($choixThematique)) {
  1266.                 $this->envoyerSimpleMessage("Veuillez saisir un numéro valide."$number);
  1267.                 return;
  1268.             }
  1269.             
  1270.             $listetheme json_decode($apuisconseil->getResultat(), true);
  1271.             $index intval($choixThematique) - 1;
  1272.             if (!isset($listetheme[$index])) {
  1273.                 $this->envoyerSimpleMessage("Numéro invalide. Veuillez réessayer."$number);
  1274.                 return;
  1275.             }
  1276.             $theme $listetheme[$index];
  1277.             $idTheme=$theme['id'];
  1278.             $apuisconseil->setThematique($idTheme);
  1279.             $apuisconseil->setEtape(2); // fin
  1280.             $entityManager->flush();
  1281.             
  1282.             $this->envoyerFichierTheme($number$idTheme);
  1283.             sleep(2);
  1284.             $this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !"$number);
  1285.             $apuisconseil->setStatut(0);
  1286.             $apuisconseil->setDeletedAt(new DateTimeImmutable());
  1287.             $session->setStatut(0);
  1288.             $session->setDeletedAt(new DateTimeImmutable());
  1289.             $entityManager->flush();
  1290.             return;
  1291.         }
  1292.     }
  1293.     #[Route('/communication'name'app_communication'methods: ['GET''POST'])]
  1294.     public function index(Request $requestMessageRepository $messageRepository): Response
  1295.     {
  1296.         $message = new Message();
  1297.         $form $this->createForm(MessageType::class, $message);
  1298.         $form->handleRequest($request);  
  1299.         if ($form->isSubmitted() && $form->isValid()) {
  1300.             $imageFiles $form->get('image')->getData();
  1301.             $telephone $form->get('telephone')->getData();
  1302.             $contenus $form->get('contenus')->getData();
  1303.             $titre $form->get('titre')->getData();
  1304.             if ($imageFiles) {
  1305.                 foreach ($imageFiles as $imageFile) {
  1306.                     $newFilename uniqid().'.'.$imageFile->guessExtension();
  1307.                     try {
  1308.                         $imageFile->move(
  1309.                             $this->getParameter('messages_images_directory'),
  1310.                             $newFilename
  1311.                         );
  1312.                     } catch (FileException $e) {
  1313.                         $this->addFlash('error''Impossible de télécharger une image.');
  1314.                         continue;
  1315.                     }
  1316.                     $message->addImage($newFilename);
  1317.                 }
  1318.             }
  1319.             $message->setCreatedAt(new \DateTimeImmutable());
  1320.             $message->setStatus(1);
  1321.             $message->setIdUser($this->getUser());
  1322.                 // dd($message);
  1323.             $messageRepository->add($messagetrue);
  1324.             
  1325.             $resultat $this->envoyerMessage("227".$telephone,$contenus,$titre);
  1326.             // $resultat = $this->envoyerSimpleMessage($contenus, "227".$telephone);
  1327.             if ($imageFiles) {
  1328.             $resultat $this->envoyerMessagePlusDocument("227".$telephone"1" );
  1329.             }
  1330.             return $this->redirectToRoute('app_communication', [], Response::HTTP_SEE_OTHER);
  1331.         }
  1332.         $messages $messageRepository->findBy(
  1333.             ['status' => 1],
  1334.             ['createdAt' => 'DESC']
  1335.         );
  1336.         
  1337.         $this->addFlash('success''Message envoyé avec succès !');    
  1338.         return $this->render('message/index.html.twig', [
  1339.             'messages' => $messages,
  1340.             'form' => $form->createView(),
  1341.         ]);
  1342.     }
  1343.     #[Route('/message/{id}'name'app_message_show'methods: ['GET''POST'])]
  1344.     public function show(Message $messageMessageRepository $messageRepository): Response
  1345.     {
  1346.         
  1347.         return $this->render('message/detail.html.twig', [
  1348.             
  1349.             'messages' => $messageRepository->findBy(
  1350.             ['status' => 1],
  1351.             ['createdAt' => 'DESC']
  1352.         ),
  1353.             'message' => $message,
  1354.         ]);
  1355.     }
  1356.     public function envoyerSimpleMessage(string $contenusstring $numero)
  1357.     {
  1358.         $numero ltrim($numero'+');
  1359.         $apiUrl 'https://graph.facebook.com/v22.0/1037760686078257/messages';
  1360.         $token 'EAAesTlijMGcBQZBCYGuMKGO9Iqz0NQnaKVJPdyV94WmU5kfdLYE5PzgtO67IIL6qaiJMJ8KFLRACc5q7ZCsfCqQi9BmAuxQN88EDxhyhdZClUc16NdZB0TNXVoFWtjZCveKKT9R3ebxRnpYeePhIo0xsYtoQ8tZBwRBTWovkWmZBADso9xcrc3uEtEhCL8KRGKaaTkGeqhVuV2yzfWsVZAHpXzkx4lzwHZCccRyTeZCiDtAkFpoaTiXyTD2sTbLyN5ZC0VZCesDA5TezyKfR2n1vWmo3G98PIgZDZD';
  1361.         $data = [
  1362.             "messaging_product" => "whatsapp",
  1363.             "to" => $numero,
  1364.             "type" => "text",
  1365.             "text" => [
  1366.                 "preview_url" => false,
  1367.                 "body" => $contenus
  1368.             ]
  1369.         ];
  1370.         $ch curl_init();
  1371.         curl_setopt_array($ch, [
  1372.             CURLOPT_URL => $apiUrl,
  1373.             CURLOPT_RETURNTRANSFER => true,
  1374.             CURLOPT_POST => true,
  1375.             CURLOPT_TIMEOUT => 10,
  1376.             CURLOPT_HTTPHEADER => [
  1377.                 "Authorization: Bearer $token",
  1378.                 "Content-Type: application/json"
  1379.             ],
  1380.             CURLOPT_POSTFIELDS => json_encode($data)
  1381.         ]);
  1382.         $response curl_exec($ch);
  1383.         $httpCode curl_getinfo($chCURLINFO_HTTP_CODE);
  1384.         if (curl_errno($ch)) {
  1385.             dump("Curl error: " curl_error($ch));
  1386.         }
  1387.         curl_close($ch);
  1388.         dump("HTTP CODE: " $httpCode);
  1389.         dump("RESPONSE: " $response);
  1390.         return $response;
  1391.     }
  1392.     // public function envoyerSimpleMessage(string $contenus,string $numero)
  1393.     // {
  1394.     //     $apiUrl = 'https://graph.facebook.com/v22.0/1037760686078257/messages';
  1395.     //     $token =  'EAAesTlijMGcBQZBCYGuMKGO9Iqz0NQnaKVJPdyV94WmU5kfdLYE5PzgtO67IIL6qaiJMJ8KFLRACc5q7ZCsfCqQi9BmAuxQN88EDxhyhdZClUc16NdZB0TNXVoFWtjZCveKKT9R3ebxRnpYeePhIo0xsYtoQ8tZBwRBTWovkWmZBADso9xcrc3uEtEhCL8KRGKaaTkGeqhVuV2yzfWsVZAHpXzkx4lzwHZCccRyTeZCiDtAkFpoaTiXyTD2sTbLyN5ZC0VZCesDA5TezyKfR2n1vWmo3G98PIgZDZD';
  1396.         
  1397.     //     $data = [
  1398.     //         "messaging_product" => "whatsapp",
  1399.     //         "recipient_type" => "individual",
  1400.     //         "to" => "$numero", // numéro du destinataire
  1401.     //         "type" => "text",
  1402.     //         "text" => [
  1403.     //             "preview_url" => false,
  1404.     //             "body" => $contenus
  1405.     //         ]
  1406.     //     ];
  1407.     //     $ch = curl_init();
  1408.     //     curl_setopt_array($ch, [
  1409.     //         CURLOPT_URL => $apiUrl,
  1410.     //         CURLOPT_RETURNTRANSFER => true,
  1411.     //         CURLOPT_POST => true,
  1412.     //         CURLOPT_HTTPHEADER => [
  1413.     //             "Authorization: Bearer $token",
  1414.     //             "Content-Type: application/json"
  1415.     //         ],
  1416.     //         CURLOPT_POSTFIELDS => json_encode($data)
  1417.     //     ]);
  1418.     //     $response = curl_exec($ch);
  1419.     //     curl_close($ch);
  1420.     // }
  1421.     public function ChoixInformation(string $textstring $number)
  1422.     {
  1423.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages';
  1424.         $token 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
  1425.         $payload = [
  1426.             "messaging_product" => "whatsapp",
  1427.             "to" => $number,
  1428.             "type" => "interactive",
  1429.             "interactive" => [
  1430.                 "type" => "list",
  1431.                 "body" => [
  1432.                     "text" => $text
  1433.                 ],
  1434.                 "footer" => [
  1435.                     "text" => "Pour arrêter le processus tapez merci ou au revoir"
  1436.                 ],
  1437.                 "action" => [
  1438.                     "button" => "Choisir un type",
  1439.                     "sections" => [
  1440.                         [
  1441.                             "title" => "Type information",
  1442.                             "rows" => [
  1443.                                 [
  1444.                                     "id" => "In_01",
  1445.                                     "title" => "SEMIS",
  1446.                                     "description" => "Dates de semis"
  1447.                                 ],
  1448.                                 [
  1449.                                     "id" => "In_02",
  1450.                                     "title" => "SECHERESSE",
  1451.                                     "description" => "Poches de sècheresse"
  1452.                                 ],
  1453.                                 [
  1454.                                     "id" => "In_03",
  1455.                                     "title" => "SAISON",
  1456.                                     "description" => "Début et fin de la saison"
  1457.                                 ],
  1458.                                 [
  1459.                                     "id" => "In_04",
  1460.                                     "title" => "ALERTE",
  1461.                                     "description" => "Alerte sur l’invasion acridienne et aviaire"
  1462.                                 ]
  1463.                             ]
  1464.                         ]
  1465.                     ]
  1466.                 ]
  1467.             ]
  1468.         ];
  1469.         try {
  1470.             $response $this->client->request('POST'$apiUrl, [
  1471.                 'headers' => [
  1472.                     'Authorization' => 'Bearer ' $token,
  1473.                     'Content-Type' => 'application/json',
  1474.                 ],
  1475.                 'json' => $payload,
  1476.             ]);
  1477.             return $response->toArray();
  1478.         } catch (\Exception $e) {
  1479.             return ['error' => $e->getMessage()];
  1480.         }
  1481.     }
  1482.     public function MessageChoixService(string $textstring $number)
  1483.     {
  1484.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages';
  1485.         $token 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
  1486.         $payload = [
  1487.             "messaging_product" => "whatsapp",
  1488.             "to" => $number,
  1489.             "type" => "interactive",
  1490.             "interactive" => [
  1491.                 "type" => "list",
  1492.                 "body" => [
  1493.                     "text" => $text
  1494.                 ],
  1495.                 "footer" => [
  1496.                     "text" => "Pour arrêter le processus tapez merci ou au revoir"
  1497.                 ],
  1498.                 "action" => [
  1499.                     "button" => "Choisir un service",
  1500.                     "sections" => [
  1501.                         [
  1502.                             "title" => "Services disponibles",
  1503.                             "rows" => [
  1504.                                 [
  1505.                                     "id" => "Sc_001",
  1506.                                     "title" => "AGRO METEO",
  1507.                                     "description" => "Prévisions météorologiques d'une localité du Niger"
  1508.                                 ],
  1509.                                 [
  1510.                                     "id" => "Sc_002",
  1511.                                     "title" => "APPUIS CONSEIL",
  1512.                                     "description" => "Conseils et assistance dans divers domaines"
  1513.                                 ],
  1514.                                 [
  1515.                                     "id" => "Sc_003",
  1516.                                     "title" => "PRIX",
  1517.                                     "description" => "Prix des animaux et produits agricoles dans les marchés du Niger"
  1518.                                 ]
  1519.                             ]
  1520.                         ]
  1521.                     ]
  1522.                 ]
  1523.             ]
  1524.         ];
  1525.         try {
  1526.             $response $this->client->request('POST'$apiUrl, [
  1527.                 'headers' => [
  1528.                     'Authorization' => 'Bearer ' $token,
  1529.                     'Content-Type' => 'application/json',
  1530.                 ],
  1531.                 'json' => $payload,
  1532.             ]);
  1533.             return $response->toArray();
  1534.         } catch (\Exception $e) {
  1535.             return ['error' => $e->getMessage()];
  1536.         }
  1537.     }
  1538.     public function ChoixDomaine(string $number)
  1539.     {
  1540.         
  1541.        //on recupere la connection
  1542.         $all=[
  1543.             "email"=> "djafarasakinatou@gmail.com",
  1544.             "password"=> "l2323"
  1545.         ];
  1546.         $dataPost=json_encode($all);
  1547.         $chemin='api/authentification';
  1548.         $response=$this->fonct->execPost('',$chemin,$dataPost);
  1549.        
  1550.         //on recupere les domaines
  1551.         $cheminDomaine='api/appuis/conseil/domaine';
  1552.         $responseDomaine=$this->fonct->execGet($response['data']['token'],$cheminDomaine);
  1553.         
  1554.         $messageListe = array();
  1555.         $text="Veuillez choisir un domaine";
  1556.         foreach ($responseDomaine['data'] as $domaine) {
  1557.             
  1558.             $messageListe[] = [
  1559.                             "id" => $domaine['id'],
  1560.                             "title" => $domaine['libelle']
  1561.             ];
  1562.         }
  1563.     
  1564.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages';
  1565.         $token 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
  1566.         $payload = [
  1567.             "messaging_product" => "whatsapp",
  1568.             "to" => $number,
  1569.             "type" => "interactive",
  1570.             "interactive" => [
  1571.                 "type" => "list",
  1572.                 "body" => [
  1573.                     "text" => $text
  1574.                 ],
  1575.                 "footer" => [
  1576.                     "text" => "Pour arrêter le processus tapez merci ou au revoir"
  1577.                 ],
  1578.                 "action" => [
  1579.                     "button" => "Choisir un domaine",
  1580.                     "sections" => [
  1581.                         [
  1582.                             "title" => "domaine disponibles",
  1583.                             "rows" => $messageListe
  1584.                         ]
  1585.                     ]
  1586.                 ]
  1587.             ]
  1588.         ];
  1589.         try {
  1590.             $response $this->client->request('POST'$apiUrl, [
  1591.                 'headers' => [
  1592.                     'Authorization' => 'Bearer ' $token,
  1593.                     'Content-Type' => 'application/json',
  1594.                 ],
  1595.                 'json' => $payload,
  1596.             ]);
  1597.             return $response->toArray();
  1598.         } catch (\Exception $e) {
  1599.             return ['error' => $e->getMessage()];
  1600.         }
  1601.     }
  1602.     public function EnvoyerListeThematique($choix$number)
  1603.     {
  1604.         // Authentification
  1605.         $auth $this->fonct->execPost('''api/authentification'json_encode(["email"=> "djafarasakinatou@gmail.com","password"=> "l2323"]));
  1606.         //thématiques
  1607.         $responseThematique $this->fonct->execPost($auth['data']['token'],'api/appuis/conseil/theme',json_encode(["id_domaine" => $choix]));
  1608.         //$this->envoyerSimpleMessage("DEBUG : \n" . json_encode($responseThematique), $number);
  1609.         if (!isset($responseThematique['data'])) {
  1610.             $this->envoyerSimpleMessage("Aucune donnée trouvée pour cette commune."$number);
  1611.             return;
  1612.         }
  1613.         // texte
  1614.         $msg "📚 *Veuillez choisir une thématique :*\n\n";
  1615.         foreach ($responseThematique['data'] as $theme) {
  1616.             $msg .= "👉 Tapez *{$theme['N°']}* pour *{$theme['libelle']}*\n";
  1617.         }
  1618.         $msg .= "\nPour arrêter tapez *merci* ou *au revoir*.";
  1619.         // Envoyer
  1620.         $this->envoyerSimpleMessage($msg$number);
  1621.     }
  1622.     public function thematiqueTrouver($domaine): array 
  1623.     {  
  1624.         // Authentification
  1625.         $auth $this->fonct->execPost('','api/authentification',json_encode([
  1626.                 "email"=> "djafarasakinatou@gmail.com",
  1627.                 "password"=> "l2323"
  1628.             ])
  1629.         );
  1630.         // Vérification authentification
  1631.         if (!isset($auth['data']['token'])) {
  1632.             return [];
  1633.         }
  1634.         $token $auth['data']['token'];
  1635.         // Récupération thématiques
  1636.         $response $this->fonct->execPost($token,'api/appuis/conseil/theme',json_encode(["id_domaine" => $domaine]));
  1637.         // Vérification statuts
  1638.         if (!isset($response['status']) || $response['status'] !== 200) {
  1639.             return [];
  1640.         }
  1641.         // Retour du tableau des thématiques
  1642.         return $response['data'] ?? [];
  1643.     }
  1644.     #[Route('/envoyer/fichier'name'app_envoyer_fichier'methods: ['POST'])]
  1645.     public function envoyerFichier(Request $requestEntityManagerInterface $entityManagerUserRepository $UserRepository): Response
  1646.     {
  1647.         $data json_decode($request->getContent(), true);
  1648.         $obligatoire = ['id_theme','numero'];
  1649.         foreach ($obligatoire as $champs) {
  1650.             if (empty($data[$champs])) {
  1651.                 return $this->json([
  1652.                     'status' => 400,
  1653.                     'message' => 'failed',
  1654.                     'data' => ['error_message' => "Le champ $champs est obligatoire."],
  1655.                 ]);
  1656.             }
  1657.         }
  1658.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages';
  1659.         $token  'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
  1660.         // Authentification interne
  1661.         $auth $this->fonct->execPost('''api/authentification'json_encode([
  1662.             "email"=> "djafarasakinatou@gmail.com",
  1663.             "password"=> "l2323"
  1664.         ]));
  1665.         // Récupération des fichiers
  1666.         $responsefichiers $this->fonct->execPost(
  1667.             $auth['data']['token'],
  1668.             'api/appuis/conseil/fichier',
  1669.             json_encode(["id_theme"=> $data['id_theme']])
  1670.         );
  1671.         if (!isset($responsefichiers['data']) || empty($responsefichiers['data'])) {
  1672.             return $this->json(['status' => 400'message' => 'Aucun fichier trouvé']);
  1673.         }
  1674.         //dd($responsefichiers);
  1675.         $dataFichier = [];
  1676.         // $i=0;
  1677.         foreach ($responsefichiers['data'] as $item) {
  1678.             
  1679.             $dataFichier[] = [
  1680.                 'conseil'=>$item['conseil'],
  1681.                 'fichier'=>$item['fichier'],
  1682.                 'semaine'=>$item['semaine'],
  1683.                 'date_ajout'=>$item['date_ajout'],
  1684.             ];
  1685.             $extension pathinfo($item['fichier'], PATHINFO_EXTENSION);
  1686.             // dd($extension);
  1687.             $payload = [
  1688.                 "to" => $data['numero'],
  1689.                 "type" => "template",
  1690.                 "messaging_product" => "whatsapp",
  1691.                 "template" => [
  1692.                     "name" => "model_garbal_format_document",
  1693.                     "language" => ["code" => "fr"],
  1694.                     "components" => [
  1695.                         [
  1696.                             "type" => "header",
  1697.                             "parameters" => [
  1698.                                 [
  1699.                                     "type" => "document",
  1700.                                     "document" => [
  1701.                                         "link" => $item['fichier'],
  1702.                                         "filename" => $item['conseil']
  1703.                                     ]
  1704.                                 ]
  1705.                             ]
  1706.                         ],
  1707.                         [
  1708.                             "type" => "body",
  1709.                             "parameters" => [
  1710.                                 [
  1711.                                     "type" => "text",
  1712.                                     "text" => $item['conseil']
  1713.                                 ]
  1714.                             ]
  1715.                         ]
  1716.                     ]
  1717.                 ]
  1718.             ];
  1719.             $ch curl_init();
  1720.             curl_setopt($chCURLOPT_URL$apiUrl);
  1721.             curl_setopt($chCURLOPT_HTTPHEADER, [
  1722.                 'Authorization: Bearer '.$token,
  1723.                 'Content-Type: application/json'
  1724.             ]);
  1725.             curl_setopt($chCURLOPT_POSTFIELDSjson_encode($payload));
  1726.             curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  1727.             $response curl_exec($ch);
  1728.             $error curl_error($ch);
  1729.             curl_close($ch);
  1730.             file_put_contents("whatsapp_response.log""RESPONSE: ".$response." | ERROR: ".$error.PHP_EOLFILE_APPEND);
  1731.             // usleep(300000); // pause 0.3s pour ne pas se faire bloquer
  1732.         }
  1733.         
  1734.         return $this->json([
  1735.             'status' => 200,
  1736.             'message' => 'Fichiers envoyés avec succès'
  1737.             // 'data' => $dataFichier
  1738.         ]);
  1739.     }
  1740.     public function envoyerFichierTheme($numero$id_theme)
  1741.     {
  1742.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages';
  1743.         $token  'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
  1744.         // Authentification interne
  1745.         $auth $this->fonct->execPost('''api/authentification'json_encode([
  1746.             "email"=> "djafarasakinatou@gmail.com",
  1747.             "password"=> "l2323"
  1748.         ]));
  1749.         //$this->envoyerSimpleMessage("Aucune donnée trouvée pour cette commune.", $numero);
  1750.             
  1751.         // Récupération des fichiers
  1752.         $responsefichiers $this->fonct->execPost(
  1753.             $auth['data']['token'],
  1754.             'api/appuis/conseil/fichier',
  1755.             json_encode(["id_theme"=> $id_theme])
  1756.         );
  1757.         //$this->envoyerSimpleMessage("DEBUG : \n" . json_encode($responsefichiers), $numero);
  1758.         if (!isset($responsefichiers['data']) || empty($responsefichiers['data'])) {
  1759.             $this->envoyerSimpleMessage("Aucune donnée trouvée ."$numero);
  1760.             return;
  1761.         }
  1762.         $this->envoyerSimpleMessage("Veuillez patienter quelques instants, les fichiers sont en cours d'envoi…"$numero);
  1763.         //dd($responsefichiers);
  1764.         $dataFichier = [];
  1765.         // $i=0;
  1766.         foreach ($responsefichiers['data'] as $item) {
  1767.            // $this->envoyerSimpleMessage("TEST : ".$item['fichier'], $numero);
  1768.             $dataFichier[] = [
  1769.                 'conseil'=>$item['conseil'],
  1770.                 'fichier'=>$item['fichier'],
  1771.                 'semaine'=>$item['semaine'],
  1772.                 'date_ajout'=>$item['date_ajout'],
  1773.             ];
  1774.             $extension pathinfo($item['fichier'], PATHINFO_EXTENSION);
  1775.             // dd($extension);
  1776.             $payload = [
  1777.                 "to" => $numero,
  1778.                 "type" => "template",
  1779.                 "messaging_product" => "whatsapp",
  1780.                 "template" => [
  1781.                     "name" => "model_garbal_format_document",
  1782.                     "language" => ["code" => "fr"],
  1783.                     "components" => [
  1784.                         [
  1785.                             "type" => "header",
  1786.                             "parameters" => [
  1787.                                 [
  1788.                                     "type" => "document",
  1789.                                     "document" => [
  1790.                                         "link" => $item['fichier'],
  1791.                                         "filename" => $item['conseil']
  1792.                                     ]
  1793.                                 ]
  1794.                             ]
  1795.                         ],
  1796.                         [
  1797.                             "type" => "body",
  1798.                             "parameters" => [
  1799.                                 [
  1800.                                     "type" => "text",
  1801.                                     "text" => $item['conseil']
  1802.                                 ]
  1803.                             ]
  1804.                         ]
  1805.                     ]
  1806.                 ]
  1807.             ];
  1808.             $ch curl_init();
  1809.             curl_setopt($chCURLOPT_URL$apiUrl);
  1810.             curl_setopt($chCURLOPT_HTTPHEADER, [
  1811.                 'Authorization: Bearer '.$token,
  1812.                 'Content-Type: application/json'
  1813.             ]);
  1814.             curl_setopt($chCURLOPT_POSTFIELDSjson_encode($payload));
  1815.             curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  1816.             $response curl_exec($ch);
  1817.             $error curl_error($ch);
  1818.             curl_close($ch);
  1819.             file_put_contents("whatsapp_response.log""RESPONSE: ".$response." | ERROR: ".$error.PHP_EOLFILE_APPEND);
  1820.             // usleep(300000); // pause 0.3s pour ne pas se faire bloquer
  1821.         }
  1822.     }
  1823.     
  1824.      public function envoyerMessagePlusDocument(string $numerostring $nombre)
  1825.     {
  1826.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages';
  1827.         $token =  'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcS';
  1828.         
  1829.         $payload = [
  1830.             "messaging_product" => "whatsapp",
  1831.             "to" => "$numero",
  1832.             "type" => "template",
  1833.             "template" => [
  1834.                 "name" => "model_garbal_format_document ",
  1835.                 "language" => ["code" => "FR"],
  1836.                 "components" => [
  1837.                     [
  1838.                         "type" => "body",
  1839.                         "parameters" => [
  1840.                             ["type" => "text""text" => $nombre],
  1841.                         ],
  1842.                     ],
  1843.                 ],
  1844.             ],
  1845.         ];
  1846.         try {
  1847.             $response $this->client->request('POST'$apiUrl, [
  1848.                 'headers' => [
  1849.                     'Authorization' => 'Bearer ' $token,
  1850.                     'Content-Type' => 'application/json',
  1851.                 ],
  1852.                 'json' => $payload,
  1853.             ]);
  1854.             return $response->toArray(); 
  1855.         } catch (\Exception $e) {
  1856.             return ['error' => $e->getMessage()];
  1857.         }
  1858.     }
  1859.     
  1860.     public function envoyerMessage(string $numerostring $contenus ,string $titre)
  1861.     {
  1862.             
  1863.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages';
  1864.         $token =  'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
  1865.         
  1866.         $payload = [
  1867.             "messaging_product" => "whatsapp",
  1868.             "to" => "$numero",
  1869.             "type" => "template",
  1870.             "template" => [
  1871.                 "name" => "model_garbal_message",
  1872.                 "language" => ["code" => "fr"],
  1873.                 "components" => [
  1874.                         [
  1875.                         "type" => "header",
  1876.                         "parameters" => [
  1877.                             [
  1878.                                 "type" => "text",
  1879.                                 "text" => $titre
  1880.                             ]
  1881.                         ]
  1882.                     ],
  1883.                     [
  1884.                         "type" => "body",
  1885.                         "parameters" => [
  1886.                             ["type" => "text""text" => $contenus],
  1887.             
  1888.                         ],
  1889.                     ],
  1890.                 ],
  1891.             ],
  1892.         ];
  1893.         try {
  1894.             $response $this->client->request('POST'$apiUrl, [
  1895.                 'headers' => [
  1896.                     'Authorization' => 'Bearer ' $token,
  1897.                     'Content-Type' => 'application/json',
  1898.                 ],
  1899.                 'json' => $payload,
  1900.             ]);
  1901.             return $response->toArray(); 
  1902.         } catch (\Exception $e) {
  1903.             return ['error' => $e->getMessage()];
  1904.         }
  1905.     }
  1906.     private function validateToken(Request $requestJWTEncoderInterface $JWTDecodeManagerEntityManagerInterface $entityManagerUserRepository $UserRepository)
  1907.     {
  1908.         $authorizationHeader $request->headers->get('Authorization');
  1909.         if (!$authorizationHeader) {
  1910.             return new JsonResponse(['status' => 401'message' => 'Token non fourni'], 401);
  1911.         }
  1912.         $tokenParts explode(' '$authorizationHeader);
  1913.         if (count($tokenParts) !== || $tokenParts[0] !== 'Bearer') {
  1914.             return new JsonResponse(['status' => 401'message' => 'Format du token invalide'], 401);
  1915.         }
  1916.         $token $tokenParts[1];
  1917.         try {
  1918.             $userData $JWTDecodeManager->decode($token);
  1919.         } catch (\Exception $e) {
  1920.             return new JsonResponse(['status' => 401'message' => 'Token invalide'], 401);
  1921.         }
  1922.         if (!isset($userData['username'])) {
  1923.             return new JsonResponse(['status' => 401'message' => 'Token mal formé (username manquant)'], 401);
  1924.         }
  1925.         // dd($userData);
  1926.         $user $UserRepository->findOneBy(['email' => $userData['username']]);
  1927.         
  1928.         if (!$user) {
  1929.             return new JsonResponse(['status' => 401'message' => 'Utilisateur non trouvé'], 401);
  1930.         }
  1931.         if ($user->getStatut() != 1) {
  1932.             return new JsonResponse(['status' => 401'message' => 'Compte inactif'], 401);
  1933.         }
  1934.         if (isset($userData['exp']) && $userData['exp'] < time()) {
  1935.         return new JsonResponse(['status' => 401'message' => 'Token expiré'], 401);
  1936.         }
  1937.         // Tout est bon, on retourne les infos de l'utilisateur
  1938.         return [
  1939.             'id'    => $user->getId(),
  1940.             'role'  => $user->getRoles(),
  1941.             'email' => $user->getEmail()
  1942.         ];
  1943.     }
  1944. }