src/Controller/MessageController.php line 74

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