<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\Message;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use App\Form\MessageType;
use App\Repository\TypeMessageRepository;
use App\Repository\MessageRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use App\Entity\Client;
use App\Entity\Conversation;
use App\Entity\StatutConversation;
use App\Entity\Canal;
use App\Entity\RechercheAppuisConseil;
use Symfony\Component\HttpFoundation\JsonResponse;
use Lexik\Bundle\JWTAuthenticationBundle\Encoder\JWTEncoderInterface;
use App\Repository\ClientRepository;
use App\Repository\ConversationRepository;
use App\Repository\CanalRepository;
use App\Repository\StatutConversationRepository;
use App\Entity\Session;
use App\Repository\RechercheAgroMeteoRepository;
use App\Repository\RechercheAppuisConseilRepository;
use App\Entity\RechercheAgroMeteo;
use App\Repository\RecherchePrixRepository;
use App\Entity\RecherchePrix;
use App\Repository\SessionRepository;
use App\Fonctions\Fonctions;
use App\Repository\UserRepository;
use DateTimeImmutable;
class MessageController extends AbstractController
{
private $client;
public function __construct(SessionInterface $session,HttpClientInterface $client,Fonctions $fonct)
{
$this->client = $client;
$this->fonct = $fonct;
$this->session = $session;
}
// #[Route('/webhook/garbal/messagerie', methods: ['GET','POST'])]
// public function messageriewebhook(Request $request): Response
// {
// $verifyToken = "QJEOIDJQEILDJLQDJLEQCLKFDEQLKLEQSKDKQEM";
// $mode = trim((string) $request->query->get('hub_mode'));
// $token = trim((string) $request->query->get('hub_verify_token'));
// $challenge = $request->query->get('hub_challenge');
// if ($mode === 'subscribe' && $token === $verifyToken) {
// return new Response($challenge, 200, ['Content-Type' => 'text/plain']);
// }
// return new Response('Forbidden: '.$token, 403);
// }
#[Route('/webhook/garbal/messagerie', name: 'app_webhook_garbal_messagerie', methods: ['GET', 'POST'])]
public function messageriewebhook(Request $request, ConversationRepository $ConversationRepository, StatutConversationRepository $StatutConversationRepository, CanalRepository $CanalRepository, ClientRepository $ClientRepository, TypeMessageRepository $TypeMessageRepository, EntityManagerInterface $entityManager,HttpClientInterface $httpClient): Response
{
$json = $request->getContent();
$data = json_decode($json, true);
if (!$data) {
return new Response('Invalid JSON', 400);
}
// Vérifier qu'il y a un message entrant
if (!isset($data['entry'][0]['changes'][0]['value']['messages'][0])) {
return new Response('No message', 200);
}
$value = $data['entry'][0]['changes'][0]['value'];
// Récupérations
$numero = $value['messages'][0]['from'] ?? null;
$nomPrenom = $value['contacts'][0]['profile']['name'] ?? null;
$typeMessage = $value['messages'][0]['type'] ?? null;
// $body = $value['messages'][0]['text']['body'] ?? null;
$client = $ClientRepository->findOneBy(['telephone' => $numero, 'statut' => 1]);
if (!$client) {
$client = new Client();
$client->setNomPrenom($nomPrenom);
$client->setTelephone($numero);
$client->setAdresse("");
$client->setCreatedAt(new DateTimeImmutable());
$client->setStatut(1);
$entityManager->persist($client);
$entityManager->flush();
}
$conversation = $ConversationRepository->findOneBy(['id_client' => $client->getId(), 'id_statut_conversation' => 1]);
// $this->MessageSimple("ok", $numero);
if (!$conversation) {
$conversation = new Conversation();
// $conversation->setIdUser($name);
$conversation->setIdClient($client);
$conversation->setIdStatutConversation($StatutConversationRepository->findOneBy(['id'=>1]));
// $conversation->setObjet("");
$conversation->setDateDebutConversation(new DateTimeImmutable());
// $conversation->setDateFinConversation($number);
$conversation->setCreatedAt(new DateTimeImmutable());
$conversation->setStatut(1);
$entityManager->persist($conversation);
$entityManager->flush();
}
$message = new Message();
$message->setTelephone($numero);
$message->setIdCanal($CanalRepository->findOneBy(['id'=>1]));
$message->setIdConversation($conversation);
$message->setCreatedAt(new DateTimeImmutable());
$message->setStatus(1);
switch ($typeMessage) {
case 'text':
$body = $value['messages'][0]['text']['body'] ?? null;
$message->setIdTypeMessage($TypeMessageRepository->findOneBy(['id'=>1]));
$message->setContenus($body);
break;
case 'image':
$imageId = $value['messages'][0]['image']['id'] ?? null;
$caption = $value['messages'][0]['image']['caption'] ?? null;
if ($imageId) {
$token = $_ENV['WHATSAPP_TOKEN'];
// récupérer l'URL du média
$response = $httpClient->request(
'GET',
"https://graph.facebook.com/v22.0/$imageId",
[
'headers' => [
'Authorization' => 'Bearer '.$token
]
]
);
$mediaData = $response->toArray();
$imageUrl = $mediaData['url'];
// $imageUrl = 'https://sandbox.crmgarbal.com/uploads/messages/'.$newFilename;
// télécharger l'image
$imageResponse = $httpClient->request(
'GET',
$imageUrl,
[
'headers' => [
'Authorization' => 'Bearer '.$token
]
]
);
$imageContent = $imageResponse->getContent();
$newFilename = 'whatsapp_'.uniqid().'.jpg';
// $urls = 'https://sandbox.crmgarbal.com/uploads/messages/' . $newFilename;
$filePath = $this->getParameter('messages_images_directory').'/'.$newFilename;
file_put_contents($filePath, $imageContent);
$message->addImage($newFilename);
$message->setIdTypeMessage($TypeMessageRepository->findOneBy(['id'=>2]));
$message->setContenus($caption);
$entityManager->persist($message);
// $entityManager->flush();
// $this->MessageSimple("enregistrement effectué", $numero);
}
break;
case 'audio':
$audioId = $value['messages'][0]['audio']['id'] ?? null;
$mimeType = $value['messages'][0]['audio']['mime_type'] ?? 'audio/ogg';
if ($audioId) {
$extension = str_contains($mimeType, 'mpeg') ? 'mp3' : 'ogg';
$audioPath = $this->downloadWhatsAppMedia(
$audioId,
$httpClient,
'audio',
$extension
);
$message->setIdTypeMessage($TypeMessageRepository->findOneBy(['id'=>3]));
$message->setAudio($audioPath);
}
break;
case 'video':
$videoId = $value['messages'][0]['video']['id'] ?? null;
$caption = $value['messages'][0]['video']['caption'] ?? null;
$mimeType = $value['messages'][0]['video']['mime_type'] ?? 'video/mp4';
if ($videoId) {
$extension = explode('/', $mimeType)[1] ?? 'mp4';
$videoPath = $this->downloadWhatsAppMedia(
$videoId,
$httpClient,
'videos',
$extension
);
$message->setVideo($videoPath);
$message->setIdTypeMessage($TypeMessageRepository->findOneBy(['id'=>4]));
$message->setContenus($caption);
}
break;
case 'document':
$documentId = $value['messages'][0]['document']['id'] ?? null;
$caption = $value['messages'][0]['document']['caption'] ?? null;
$filename = $value['messages'][0]['document']['filename'] ?? null;
$mimeType = $value['messages'][0]['document']['mime_type'] ?? null;
if ($documentId) {
$extension = pathinfo($filename, PATHINFO_EXTENSION) ?: 'bin';
$docPath = $this->downloadWhatsAppMedia(
$documentId,
$httpClient,
'documents',
$extension
);
$message->setDocument($docPath);
$message->setIdTypeMessage($TypeMessageRepository->findOneBy(['id'=>5]));
$message->setContenus($caption ?? $filename);
}
break;
case 'location':
$latitude = $value['messages'][0]['location']['latitude'] ?? null;
$longitude = $value['messages'][0]['location']['longitude'] ?? null;
$name = $value['messages'][0]['location']['name'] ?? null;
$address = $value['messages'][0]['location']['address'] ?? null;
if ($latitude && $longitude) {
$contenu = "Localisation reçue :\n";
$contenu .= "Latitude : $latitude\n";
$contenu .= "Longitude : $longitude\n";
if ($name) {
$contenu .= "Nom : $name\n";
}
if ($address) {
$contenu .= "Adresse : $address\n";
}
$contenu .= "Lien Google Maps : https://www.google.com/maps?q=$latitude,$longitude";
$message->setLatitude($latitude);
$message->setIdTypeMessage($TypeMessageRepository->findOneBy(['id'=>6]));
$message->setLongitude($longitude);
$message->setContenus("Localisation envoyée par le client");
}else {
$this->MessageSimple("Echec", $numero);
}
break;
case 'sticker':
$stickerId = $value['messages'][0]['sticker']['id'] ?? null;
$mimeType = $value['messages'][0]['sticker']['mime_type'] ?? 'image/webp';
if ($stickerId) {
$extension = explode('/', $mimeType)[1] ?? 'webp';
$stickerPath = $this->downloadWhatsAppMedia(
$stickerId,
$httpClient,
'stickers',
$extension
);
$message->addImage($stickerPath);
$message->setIdTypeMessage($TypeMessageRepository->findOneBy(['id'=>7]));
$message->setContenus("Sticker envoyé");
}
break;
default:
$message->setContenus("Type de message non supporté : ".$typeMessage);
break;
}
$entityManager->persist($message);
$entityManager->flush();
$this->MessageSimple("enregistrement effectué", $numero);
return new Response('EVENT_RECEIVED', 200);
}
//fonction fin convertion
#[Route('/fin/garbal/conversation', name: 'app_fin_garbal_conversation')]
public function FinConversation(Request $request, ConversationRepository $ConversationRepository, StatutConversationRepository $StatutConversationRepository, EntityManagerInterface $entityManager, HttpClientInterface $httpClient): Response
{
if ($request->request->count()>0){
$objet=$request->request->get('objet');
$commentaire=$request->request->get('commentaire');
$id=$request->request->get('id');
$conversation=$ConversationRepository->findOneBy(['id'=>$id]);
if (!$conversation) {
return $this->redirectToRoute('app_whatsapp_communication', [], Response::HTTP_SEE_OTHER);
}
if ($objet==1) {
$conversation->setObjet("AGRO METEO");
}elseif ($objet==2) {
$conversation->setObjet("APPUIS CONSEIL");
}elseif ($objet==3) {
$conversation->setObjet("PRIX");
}else {
$conversation->setObjet("AUTRE");
}
$conversation->setCommentaire($commentaire);
$conversation->setDateFinConversation(new DateTimeImmutable());
$conversation->setIdStatutConversation($StatutConversationRepository->findOneBy(['id'=>3]));
$entityManager->persist($conversation);
$entityManager->flush();
}
return $this->redirectToRoute('app_whatsapp_communication', [], Response::HTTP_SEE_OTHER);
}
private function downloadWhatsAppMedia($mediaId, HttpClientInterface $httpClient, $folder = 'media', $extension = 'bin')
{
$token = $_ENV['WHATSAPP_TOKEN'];
try {
// 1. Récupérer les infos du média
$response = $httpClient->request(
'GET',
"https://graph.facebook.com/v22.0/$mediaId",
[
'headers' => [
'Authorization' => 'Bearer '.$token
]
]
);
if ($response->getStatusCode() !== 200) {
throw new \Exception('Erreur récupération metadata média');
}
$mediaData = $response->toArray(false);
if (!isset($mediaData['url'])) {
throw new \Exception('URL média introuvable');
}
$mediaUrl = $mediaData['url'];
// 2. Télécharger le fichier
$mediaResponse = $httpClient->request(
'GET',
$mediaUrl,
[
'headers' => [
'Authorization' => 'Bearer '.$token
]
]
);
if ($mediaResponse->getStatusCode() !== 200) {
throw new \Exception('Erreur téléchargement média');
}
$content = $mediaResponse->getContent();
// 3. Sécuriser extension
if (!$extension) {
$extension = 'bin';
}
// 4. Créer dossier si inexistant
$basePath = $this->getParameter('messages_directory');
$folderPath = $basePath . '/' . $folder;
if (!is_dir($folderPath)) {
mkdir($folderPath, 0777, true);
}
// 5. Générer nom fichier
$newFilename = $folder.'_'.uniqid().'.'.$extension;
$filePath = $folderPath . '/' . $newFilename;
// 6. Sauvegarde
file_put_contents($filePath, $content);
return $folder . '/' . $newFilename;
} catch (\Exception $e) {
// 🔥 LOG IMPORTANT
file_put_contents(
$this->getParameter('kernel.project_dir').'/var/log/whatsapp_error.log',
date('Y-m-d H:i:s').' - '.$e->getMessage().PHP_EOL,
FILE_APPEND
);
return null;
}
}
// private function downloadWhatsAppMedia($mediaId, $httpClient, $folder, $extension)
// {
// $token = $_ENV['WHATSAPP_TOKEN'];
// $response = $httpClient->request(
// 'GET',
// "https://graph.facebook.com/v22.0/$mediaId",
// [
// 'headers' => [
// 'Authorization' => 'Bearer '.$token
// ]
// ]
// );
// $mediaData = $response->toArray();
// $mediaUrl = $mediaData['url'];
// $mediaResponse = $httpClient->request(
// 'GET',
// $mediaUrl,
// [
// 'headers' => [
// 'Authorization' => 'Bearer '.$token
// ]
// ]
// );
// $content = $mediaResponse->getContent();
// $newFilename = $folder.'_'.uniqid().'.'.$extension;
// $filePath = $this->getParameter('messages_directory').'/'.$newFilename;
// file_put_contents($filePath, $content);
// return $newFilename;
// }
private function downloadWhatsAppVideo(string $mediaId, HttpClientInterface $httpClient, string $folder, string $extension ): ?string
{
$token = $_ENV['EAAesTlijMGcBQtdhdKedpB4DqNDFsDVcuBb8Kcx3zETgu8pMjX67hpliaoL2wAHjgZAJZAo0rPblwFesxiJXqm19ZC5mjQdixA5oYqjpoVYnbq97dqOMnNR8qoT2QqIcaraJDLHdZBd52UTEcxj8qTRT82iqy0GyOltkXdZBtBgrKUc3f1TpHRXHQOZBw3gt7kewZDZD'];
// Récupérer l'URL temporaire
$response = $httpClient->request(
'GET',
"https://graph.facebook.com/v22.0/$mediaId",
[
'headers' => [
'Authorization' => 'Bearer ' . $token
]
]
);
if ($response->getStatusCode() !== 200) {
return null;
}
$mediaData = $response->toArray();
$mediaUrl = $mediaData['url'];
// 2️⃣ Télécharger le fichier
$mediaResponse = $httpClient->request(
'GET',
$mediaUrl,
[
'headers' => [
'Authorization' => 'Bearer ' . $token
]
]
);
if ($mediaResponse->getStatusCode() !== 200) {
return null;
}
$content = $mediaResponse->getContent();
// 3️⃣ Créer dossier si inexistant
$uploadDir = $this->getParameter('kernel.project_dir') . '/public/uploads/' . $folder;
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0777, true);
}
$fileName = uniqid() . '.' . $extension;
$filePath = $uploadDir . '/' . $fileName;
file_put_contents($filePath, $content);
file_put_contents($filePath, $audioContent);
return '/uploads/video/' . $folder . '/' . $fileName;
}
private function downloadWhatsAppDocument( string $mediaId, HttpClientInterface $httpClient, string $originalFilename = null ): ?string
{
$token = $_ENV['EAAesTlijMGcBQtdhdKedpB4DqNDFsDVcuBb8Kcx3zETgu8pMjX67hpliaoL2wAHjgZAJZAo0rPblwFesxiJXqm19ZC5mjQdixA5oYqjpoVYnbq97dqOMnNR8qoT2QqIcaraJDLHdZBd52UTEcxj8qTRT82iqy0GyOltkXdZBtBgrKUc3f1TpHRXHQOZBw3gt7kewZDZD'];
// 1️⃣ Récupérer l’URL temporaire via Graph API v22.0
$response = $httpClient->request(
'GET',
"https://graph.facebook.com/v22.0/$mediaId",
[
'headers' => [
'Authorization' => 'Bearer ' . $token
]
]
);
if ($response->getStatusCode() !== 200) {
return null;
}
$mediaData = $response->toArray();
$mediaUrl = $mediaData['url'] ?? null;
if (!$mediaUrl) {
return null;
}
// 2️⃣ Télécharger le fichier réel
$fileResponse = $httpClient->request(
'GET',
$mediaUrl,
[
'headers' => [
'Authorization' => 'Bearer ' . $token
]
]
);
if ($fileResponse->getStatusCode() !== 200) {
return null;
}
$content = $fileResponse->getContent();
// 3️⃣ Déterminer l’extension
$extension = pathinfo($originalFilename, PATHINFO_EXTENSION);
if (!$extension) {
$extension = 'bin';
}
// 4️⃣ Créer dossier si inexistant
$uploadDir = $this->getParameter('kernel.project_dir') . '/public/uploads/documents';
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0777, true);
}
// 5️⃣ Générer nom unique
$fileName = uniqid() . '.' . $extension;
$filePath = $uploadDir . '/' . $fileName;
file_put_contents($filePath, $content);
return '/uploads/documents/' . $fileName;
}
public function MessageSimple(string $contenus, string $numero)
{
$numero = ltrim($numero, '+');
$apiUrl = 'https://graph.facebook.com/v22.0/1037760686078257/messages';
$token = 'EAAesTlijMGcBQtdhdKedpB4DqNDFsDVcuBb8Kcx3zETgu8pMjX67hpliaoL2wAHjgZAJZAo0rPblwFesxiJXqm19ZC5mjQdixA5oYqjpoVYnbq97dqOMnNR8qoT2QqIcaraJDLHdZBd52UTEcxj8qTRT82iqy0GyOltkXdZBtBgrKUc3f1TpHRXHQOZBw3gt7kewZDZD';
$data = [
"messaging_product" => "whatsapp",
// "recipient_type": "individual",
"to" => $numero,
"type" => "text",
"text" => [
"preview_url" => false,
"body" => $contenus
]
];
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $apiUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => [
"Authorization: Bearer $token",
"Content-Type: application/json"
],
CURLOPT_POSTFIELDS => json_encode($data)
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
dump("Curl error: " . curl_error($ch));
}
curl_close($ch);
dump("HTTP CODE: " . $httpCode);
dump("RESPONSE: " . $response);
return $response;
}
#[Route('/message/communication', name: 'app_message_communication', methods: ['GET', 'POST'])]
public function MessageCommunication(Request $request,SessionRepository $SessionRepository,ClientRepository $ClientRepository,EntityManagerInterface $entityManager): Response
{
// $json = $request->getContent();
// $data = json_decode($json, true);
// if (!$data || !isset($data['entry'][0]['changes'][0]['value']['messages'][0])) {
// return new Response("No message", 200);
// }
// $messages = $data['entry'][0]['changes'][0]['value']['messages'][0];
// $name = $data['entry'][0]['changes'][0]['value']['contacts'][0]['profile']['name'];
// $number = $messages['from'];
// $typeMessage = $messages['type'];
// $body = "";
// if (isset($messages['text']['body'])) {
// $body = trim($messages['text']['body']);
// }
// $client = $ClientRepository->findOneBy(['telephone' => $number, 'statut' => 1]);
// if (!$client) {
// $client = new Client();
// $client->setNomPrenom($name);
// $client->setTelephone($number);
// $client->setAdresse("");
// $client->setCreatedAt(new DateTimeImmutable());
// $client->setStatut(1);
// $entityManager->persist($client);
// $entityManager->flush();
// }
// $session = $SessionRepository->findOneBy(['idClient' => $client->getId(), 'statut' => 1]);
// if ($body === "Merci" || $body === "Au revoir") {
// if ($session) {
// $session->setStatut(0);
// $session->setDeletedAt(new DateTimeImmutable());
// $entityManager->flush();
// }
// $this->envoyerSimpleMessage(
// "*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ très bientôt !",
// $number
// );
// return new Response("", 200);
// }
// if (!$session) {
// // Ignorer tout ce qui n'est pas un texte
// if ($typeMessage !== "text") {
// return new Response("", 200);
// }
// $body = trim($messages['text']['body']);
// // Ne pas recréer une session si l'utilisateur dit encore un mot de fin
// if ($body === "Merci" || $body === "Au revoir") {
// return new Response("", 200);
// }
// $session = new Session();
// $session->setIdClient($client);
// $session->setEtape(0);
// $session->setTempsConnexion(0);
// $session->setCreatedAt(new DateTimeImmutable());
// $session->setStatut(1);
// $entityManager->persist($session);
// $entityManager->flush();
// $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.";
// $this->MessageChoixService($text, $number);
// return new Response("", 200);
// }
// if ($session->getEtape() == 0) {
// if ($typeMessage == 'interactive') {
// $choix = $messages['interactive']['list_reply']['id'];
// $session->setService($choix);
// $session->setEtape(1);
// $entityManager->flush();
// switch ($choix) {
// case "Sc_001":
// $agrometeo = new RechercheAgroMeteo();
// $agrometeo->setIdSession($session);
// $agrometeo->setEtape(0);
// $agrometeo->setCreatedAt(new DateTimeImmutable());
// $agrometeo->setStatut(1);
// $entityManager->persist($agrometeo);
// $entityManager->flush();
// $this->ChoixInformation("Veuillez choisir le type d'information souhaité.", $number);
// break;
// case "Sc_002":
// $app = new RechercheAppuisConseil();
// $app->setIdSession($session);
// $app->setEtape(0);
// $app->setCreatedAt(new DateTimeImmutable());
// $app->setStatut(1);
// $entityManager->persist($app);
// $entityManager->flush();
// $this->ChoixDomaine($number);
// break;
// case "Sc_003":
// $prix = new RecherchePrix();
// $prix->setIdSession($session);
// $prix->setEtape(0);
// $prix->setCreatedAt(new DateTimeImmutable());
// $prix->setStatut(1);
// $entityManager->persist($prix);
// $entityManager->flush();
// $this->EnvoyerListeCategories("Veuillez choisir le type d'information souhaité.", $number);
// break;
// default:
// $this->envoyerSimpleMessage("Désolé, choix inconnu.", $number);
// }
// return new Response("", 200);
// }
// // Pas interactif
// $this->envoyerSimpleMessage("Veuillez faire un choix.", $number);
// return new Response("", 200);
// }
// switch ($session->getService()) {
// case "Sc_001":
// $this->TraiterAgroMeteo($data, $session, $entityManager);
// break;
// case "Sc_002":
// $this->TraiterAppuisConseil($data, $session, $entityManager);
// break;
// case "Sc_003":
// $this->TraiterPrix($data, $session, $entityManager);
// break;
// default:
// $this->envoyerSimpleMessage("Choix non reconnu.", $number);
// }
// return new Response("", 200);
}
public function TraiterPrix($data, $session, $entityManager)
{
$messages = $data['entry'][0]['changes'][0]['value']['messages'][0];
$number = $messages['from'];
$typeMessage = $messages['type'];
if ($typeMessage === "text") {
$texte = trim($messages['text']['body']);
if ($texte === "Merci" || $texte === "Au revoir") {
$session->setStatut(0);
$session->setDeletedAt(new DateTimeImmutable());
$entityManager->persist($session);
$entityManager->flush();
$this->envoyerSimpleMessage(
"*Session expirée*\nMerci d'avoir utilisé notre service prix.\nÀ très bientôt.",
$number
);
return;
}
}
$prixSession = $entityManager->getRepository(RecherchePrix::class)
->findOneBy(['idSession' => $session->getId(), 'statut' => 1]);
if (!$prixSession) {
$this->envoyerSimpleMessage("Aucune session.", $number);
return;
}
/* ÉTAPE 0 : CHOIX CATÉGORIE */
if ($prixSession->getEtape() == 0) {
if (isset($messages['interactive']['list_reply']['id'])) {
$choix = $messages['interactive']['list_reply']['id'];
if ($choix === "Pc_001") {
$prixSession->setType("AGRICULTURE");
$prixSession->setEtape(1);
$entityManager->flush();
$this->envoyerSimpleMessage(
"Vous avez choisi *AGRO ALIMENTAIRE*.\n\nVeuillez saisir le nom d'une commune :",
$number
);
return;
}
if ($choix === "Pc_002") {
$prixSession->setType("BETAIL");
$prixSession->setEtape(1);
$entityManager->flush();
$this->envoyerSimpleMessage(
"Vous avez choisi *ANIMAUX / BÉTAIL*.\n\nVeuillez saisir le nom d'une commune :",
$number
);
return;
}
$this->envoyerSimpleMessage("Choix invalide, veuillez réessayer.", $number);
return;
}
// Si aucun choix reçu, envoyer la liste de catégories
$this->EnvoyerListeCategories("Veuillez choisir une catégorie :", $number);
return;
}
/* ÉTAPE 1 : RECHERCHE DE COMMUNE */
if ($prixSession->getEtape() == 1 ) {
if ($typeMessage !== "text") {
$this->envoyerSimpleMessage(
"Veuillez saisir un nom de commune sous forme de texte.",
$number
);
return;
}
$texteRecu = trim($messages['text']['body']);
$listeCommunes = $this->AppelApiRechercheCommunes($texteRecu);
if (empty($listeCommunes)) {
$this->envoyerSimpleMessage(
"Aucune commune trouvée pour *$texteRecu*.\nVeuillez saisir un autre nom.",
$number
);
return;
}
// Stocker la liste pour sélection
$prixSession->setListeResultat(json_encode($listeCommunes));
$prixSession->setEtape(2);
$entityManager->flush();
$this->EnvoyerListeCommunes($listeCommunes, $number);
return;
}
/* ÉTAPE 2 : CHOIX D'UNE COMMUNE */
if ($prixSession->getEtape() == 2 && $typeMessage === "text") {
$choix = trim($messages['text']['body']);
if (!ctype_digit($choix)) {
$this->envoyerSimpleMessage("Veuillez saisir un numéro valide.", $number);
return;
}
$listeCommunes = json_decode($prixSession->getListeResultat(), true);
$index = intval($choix) - 1;
if (!isset($listeCommunes[$index])) {
$this->envoyerSimpleMessage("Numéro invalide. Veuillez réessayer.", $number);
return;
}
$commune = $listeCommunes[$index];
$prixSession->setCommune($commune['id']);
$prixSession->setListeResultat(null);
$prixSession->setEtape(3);
$entityManager->flush();
/* les prix selon la catégorie */
if ($prixSession->getType() === "AGRICULTURE") {
$listePrix = $this->AppelApiPrixProduitsAgricoles($commune['id']);
$this->EnvoyerPrixProduitsAgricoles($listePrix, $number);
$prixSession->setStatut(0);
$prixSession->setDeletedAt(new DateTimeImmutable());
$session->setStatut(0);
$session->setDeletedAt(new DateTimeImmutable());
$entityManager->persist($session);
$entityManager->flush();
$this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !", $number);
return;
}
if ($prixSession->getType() === "BETAIL") {
$listePrix = $this->AppelApiPrixBetail($commune['id']);
$this->EnvoyerPrixBetail($listePrix, $number);
$prixSession->setStatut(0);
$prixSession->setDeletedAt(new DateTimeImmutable());
$session->setStatut(0);
$session->setDeletedAt(new DateTimeImmutable());
$entityManager->persist($session);
$entityManager->flush();
$this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !", $number);
return;
}
return;
}
/* ERREUR PAR DÉFAUT */
$this->envoyerSimpleMessage("Désolé, je n'ai pas reconnu votre choix.", $number);
return;
}
public function EnvoyerListeCommunes(array $listeCommunes, string $number)
{
if (empty($listeCommunes)) {
$this->envoyerSimpleMessage("Aucune commune trouvée. Veuillez réessayer.", $number);
return;
}
$message = "*Communes trouvées :*\n\n";
$i = 1;
foreach ($listeCommunes as $commune) {
$message .= "👉 Tapez *".$i."* pour *".$commune['libelle']."*\n";
$i++;
}
$message .= "\n*Tapez le numéro* correspondant à votre commune.";
// CORRECTION : utiliser $number et NON $numero
$this->envoyerSimpleMessage($message, $number);
}
public function AppelApiRechercheCommunes(string $texte): array
{
//Authentification API
$auth = $this->fonct->execPost('', 'api/authentification', json_encode([
"email" => "djafarasakinatou@gmail.com",
"password" => "l2323"
]));
//Appel API de recherche des communes
$response = $this->fonct->execPost( $auth['data']['token'], 'api/communes/recherche', json_encode([ "commune" => $texte ]) );
//Vérification réponse
if (!isset($response['status']) || $response['status'] != 200)
{
return [];
}
//Retourne la liste des résultats
return $response['results'] ?? [];
}
public function AppelApiPrixBetail(string $idCommune): array
{
// Authentification API
$auth = $this->fonct->execPost('', 'api/authentification', json_encode([
"email" => "djafarasakinatou@gmail.com",
"password" => "l2323"
]));
// Appel API Prix Bétail
$response = $this->fonct->execPost( $auth['data']['token'], 'api/prix/animaux', json_encode([ "id_commune" => $idCommune ]) );
if (!isset($response['status']) || $response['status'] != 200)
{
return [];
}
return $response['data'] ?? [];
}
public function AppelApiPrixProduitsAgricoles(string $idCommune): array
{
// Authentification API
$auth = $this->fonct->execPost('', 'api/authentification', json_encode([
"email" => "djafarasakinatou@gmail.com",
"password" => "l2323"
]));
// Appel API Prix Produits Agricoles
$response = $this->fonct->execPost(
$auth['data']['token'],
'api/prix/produit/agricole',
json_encode([
"id_commune" => $idCommune,
"id_semaine" => "" // ton API prend automatiquement la semaine active
])
);
// Vérification du status
if (!isset($response['status']) || $response['status'] != 200) {
return [];
}
// Retour des données
return $response['data'] ?? [];
}
public function EnvoyerListeCategories(string $text, string $number)
{
$apiUrl = 'https://graph.facebook.com/v22.0/870067449513702/messages';
$token = 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
$payload = [
"messaging_product" => "whatsapp",
"to" => $number,
"type" => "interactive",
"interactive" => [
"type" => "list",
"body" => [
"text" => $text
],
"footer" => [
"text" => "Pour arrêter le processus tapez merci ou au revoir"
],
"action" => [
"button" => "Catégories",
"sections" => [
[
"title" => "Catégories disponibles",
"rows" => [
[
"id" => "Pc_001",
"title" => "AGRO ALIMENT",
"description" => "Prix des aliments d'une localité du Niger"
],
[
"id" => "Pc_002",
"title" => "ANIMAUX",
"description" => "Prix du bétail d'une localité du Niger"
]
]
]
]
]
]
];
try {
$response = $this->client->request('POST', $apiUrl, [
'headers' => [
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json',
],
'json' => $payload,
]);
$result = $response->toArray(false);
return $result;
} catch (\Exception $e) {
return ['error' => $e->getMessage()];
}
}
public function EnvoyerPrixBetail(array $prix, string $number)
{
$apiUrl = 'https://graph.facebook.com/v22.0/870067449513702/messages';
$token = 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
// Construction du message
if (empty($prix)) {
$texte = " *Aucun prix de bétail trouvé pour cette commune.*";
} else {
$texte = " *Prix du Bétail*\n\n";
foreach ($prix as $item) {
$texte .= " *" . $item["animal"] . "*\n";
$texte .= " Prix : " . $item["prix"] . " FCFA\n";
$texte .= "-------------------------\n";
}
}
$payload = [
"messaging_product" => "whatsapp",
"to" => $number,
"type" => "text",
"text" => [
"body" => $texte
]
];
try {
$response = $this->client->request('POST', $apiUrl, [
'headers' => [
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json',
],
'json' => $payload,
]);
return $response->toArray();
} catch (\Exception $e) {
return ['error' => $e->getMessage()];
}
}
public function EnvoyerPrixProduitsAgricoles(array $prix, string $number)
{
$apiUrl = 'https://graph.facebook.com/v22.0/870067449513702/messages';
$token = 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
// Construction du message
if (empty($prix))
{
$texte = " *Aucun prix de produit agricole trouvé pour cette commune.*";
} else
{
$texte = " *Prix des produits agricoles*\n\n";
foreach ($prix as $item)
{
$texte .= " *" . $item["produit"] . "*\n";
$texte .= " Prix : " . $item["prix"] . " FCFA\n";
$texte .= "-------------------------\n";
}
}
$payload = [
"messaging_product" => "whatsapp",
"to" => $number,
"type" => "text",
"text" => [
"body" => $texte
]
];
try
{
$response = $this->client->request('POST', $apiUrl, [ 'headers' => [ 'Authorization' => 'Bearer ' . $token, 'Content-Type' => 'application/json', ], 'json' => $payload, ]);
return $response->toArray();
} catch (\Exception $e)
{
return ['error' => $e->getMessage()];
}
}
public function TraiterAgroMeteo($data,$session,$entityManager)
{
$messages = $data['entry'][0]['changes'][0]['value']['messages'][0];
$number = $messages['from'];
$typeMessage = $messages['type'];
if ($typeMessage === "text") {
$texte = trim($messages['text']['body']);
if ($texte === "Merci" || $texte === "Au revoir") {
$session->setStatut(0);
$session->setDeletedAt(new DateTimeImmutable());
$entityManager->persist($session);
$entityManager->flush();
$this->envoyerSimpleMessage(
"*Session expirée*\nMerci d'avoir utilisé notre service prix.\nÀ très bientôt.",
$number
);
return;
}
}
$agrometeo = $entityManager->getRepository(RechercheAgroMeteo::class)->findOneBy(['idSession' => $session->getId(),'statut' => 1]);
// Fin de session
// if ($agrometeo->getEtape()==3)
// {
// $session->setStatut(0);
// $session->setDeletedAt(new DateTimeImmutable());
// $entityManager->flush();
// $this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !", $number);
// return;
// }
if (!$agrometeo) {
$this->envoyerSimpleMessage("Aucune session.", $number);
return;
// $agrometeo = new RechercheAgroMeteo();
// $agrometeo->setIdSession($session);
// $agrometeo->setEtape(0); //etape 0 creation
// $agrometeo->setCreatedAt(new DateTimeImmutable());
// $agrometeo->setStatut(1);
// $entityManager->persist($agrometeo);
// $entityManager->flush();
// // $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é.";
// $text = "Veuillez choisir le type d'information souhaité.";
// $this->ChoixInformation($text,$number);
// return;
}
if ($agrometeo->getEtape()==0) {
if (isset($messages['interactive']['list_reply']['id'])) {
$choix = $messages['interactive']['list_reply']['id'];
} else {
$this->envoyerSimpleMessage("Veuillez sélectionner un type d'information dans la liste.", $number);
return;
}
$agrometeo->setType($choix);
$agrometeo->setEtape(1); // choix type info
$entityManager->persist($agrometeo);
$entityManager->flush();
// $text = "Veuillez saissir la localité souhaitée.";
// $this->envoyerSimpleMessage($text, $number);
}
if ($agrometeo->getEtape()==1 && $agrometeo->getType()!=null) {// si etape 1 choix commune fait
if ($typeMessage !== "text") {
$this->envoyerSimpleMessage("Veuillez saisir un nom de commune sous forme de texte.",$number);
return;
}
$texteRecu = trim($messages['text']['body']);
$listeCommunes = $this->AppelApiRechercheCommunes($texteRecu);
if (empty($listeCommunes)) {
$this->envoyerSimpleMessage(
"Aucune commune trouvée pour *$texteRecu*.\nVeuillez saisir un autre nom.",
$number
);
return;
}
$agrometeo->setResultat(json_encode($listeCommunes));
$agrometeo->setEtape(2); //saissi commune
$entityManager->persist($agrometeo);
$entityManager->flush();
$this->EnvoyerListeCommunes($listeCommunes, $number);
return;
}
if ($agrometeo->getEtape() == 2) {
// $this->envoyerSimpleMessage("ok", $number);
$userMessage = trim($messages['text']['body']);
if ($typeMessage !== "text") {
$this->envoyerSimpleMessage("Veuillez saisir un numéro.", $number);
return;
}
if (!ctype_digit($messages['text']['body'])) {
$this->envoyerSimpleMessage("Numéro invalide.", $number);
return;
}
$listeCommunes = json_decode($agrometeo->getResultat(), true);
$index = intval($messages['text']['body']) - 1;
if (!isset($listeCommunes[$index])) {
$this->envoyerSimpleMessage("Numéro invalide. Veuillez réessayer.", $number);
return;
}
$commune = $listeCommunes[$index];
$idCommune=$commune['id'];
// Enregistrer dans la base
$agrometeo->setCommune($idCommune);
$agrometeo->setEtape(3);
$entityManager->flush();
// Continue selon type
if ($agrometeo->getType() == "In_01") {
$this->EnvoyerDateSemis($idCommune, $number);
$agrometeo->setStatut(0);
$agrometeo->setDeletedAt(new DateTimeImmutable());
$session->setStatut(0);
$session->setDeletedAt(new DateTimeImmutable());
$entityManager->persist($session);
$entityManager->flush();
$this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !", $number);
return;
}
if ($agrometeo->getType() == "In_02") {
$this->EnvoyerPocheSecheresse($idCommune, $number);
$agrometeo->setStatut(0);
$agrometeo->setDeletedAt(new DateTimeImmutable());
$session->setStatut(0);
$session->setDeletedAt(new DateTimeImmutable());
$entityManager->persist($session);
$entityManager->flush();
$this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !", $number);
return;
}
if ($agrometeo->getType() == "In_03") {
$this->EnvoyerDateSaison($idCommune, $number);
$agrometeo->setStatut(0);
$agrometeo->setDeletedAt(new DateTimeImmutable());
$session->setStatut(0);
$session->setDeletedAt(new DateTimeImmutable());
$entityManager->persist($session);
$entityManager->flush();
$this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !", $number);
return;
}
if ($agrometeo->getType() == "In_04") {
$this->EnvoyerAlerte($idCommune, $number);
$agrometeo->setStatut(0);
$agrometeo->setDeletedAt(new DateTimeImmutable());
$session->setStatut(0);
$session->setDeletedAt(new DateTimeImmutable());
$entityManager->persist($session);
$entityManager->flush();
$this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !", $number);
return;
}
return;
}
}
public function EnvoyerDateSemis($idCommune, $number)
{
// Authentification
$auth = $this->fonct->execPost('', 'api/authentification', json_encode(["email"=> "djafarasakinatou@gmail.com","password"=> "l2323"]));
//thématiques
$responsesemis = $this->fonct->execPost($auth['data']['token'],'api/date/semis',json_encode(["id_commune" => $idCommune]));
// $this->envoyerSimpleMessage("ok", $number);
if (!isset($responsesemis['data'])) {
$this->envoyerSimpleMessage("Aucune donnée trouvée .", $number);
return;
}
$msg = "Information disponible:\n";
foreach ($responsesemis['data'] as $semis) {
$msg .= "*{$semis['information']}*\n\n";
}
$msg .= "\nPour arrêter tapez *merci* ou *au revoir*.";
// Envoyer
$this->envoyerSimpleMessage($msg, $number);
}
public function EnvoyerPocheSecheresse($idCommune, $number)
{
// Authentification
$auth = $this->fonct->execPost('', 'api/authentification', json_encode(["email"=> "djafarasakinatou@gmail.com","password"=> "l2323"]));
//thématiques
$responsesemis = $this->fonct->execPost($auth['data']['token'],'api/poche/secheresse',json_encode(["id_commune" => $idCommune]));
// $this->envoyerSimpleMessage("ok", $number);
// 🔍 DEBUG : voir ce que retourne l'API
//$this->envoyerSimpleMessage("DEBUG : \n" . json_encode($responsesemis), $number);
if (!isset($responsesemis['data'])) {
$this->envoyerSimpleMessage("Aucune donnée trouvée .", $number);
return;
}
$msg = "Information disponible:\n";
foreach ($responsesemis['data'] as $semis) {
$msg .= "*{$semis['information']}*\n\n";
}
$msg .= "\nPour arrêter tapez *merci* ou *au revoir*.";
// Envoyer
$this->envoyerSimpleMessage($msg, $number);
}
public function EnvoyerDateSaison($idCommune, $number)
{
// Authentification
$auth = $this->fonct->execPost('', 'api/authentification', json_encode(["email"=> "djafarasakinatou@gmail.com","password"=> "l2323"]));
//thématiques
$responsesemis = $this->fonct->execPost($auth['data']['token'],'api/date/saison',json_encode(["id_commune" => $idCommune]));
// $this->envoyerSimpleMessage("ok", $number);
if (!isset($responsesemis['data'])) {
$this->envoyerSimpleMessage("Aucune donnée trouvée .", $number);
return;
}
$msg = "Information disponible:\n";
foreach ($responsesemis['data'] as $semis) {
$msg .= "*{$semis['information']}*\n\n";
}
$msg .= "\nPour arrêter tapez *merci* ou *au revoir*.";
// Envoyer
$this->envoyerSimpleMessage($msg, $number);
}
public function EnvoyerAlerte($idCommune, $number)
{
// Authentification
$auth = $this->fonct->execPost('', 'api/authentification', json_encode(["email"=> "djafarasakinatou@gmail.com","password"=> "l2323"]));
//thématiques
$responsesemis = $this->fonct->execPost($auth['data']['token'],'api/alerte',json_encode(["id_commune" => $idCommune]));
// $this->envoyerSimpleMessage("ok", $number);
if (!isset($responsesemis['data'])) {
$this->envoyerSimpleMessage("Aucune donnée trouvée .", $number);
return;
}
$msg = "Information disponible:\n";
foreach ($responsesemis['data'] as $semis) {
$msg .= "*{$semis['information']}*\n\n";
}
$msg .= "\nPour arrêter tapez *merci* ou *au revoir*.";
// Envoyer
$this->envoyerSimpleMessage($msg, $number);
}
public function TraiterAppuisConseil($data, $session, $entityManager)
{
$messages = $data['entry'][0]['changes'][0]['value']['messages'][0];
$number = $messages['from'];
$typeMessage = $messages['type'];
if ($typeMessage === "text") {
$texte = trim($messages['text']['body']);
if ($texte === "Merci" || $texte === "Au revoir") {
$session->setStatut(0);
$session->setDeletedAt(new DateTimeImmutable());
$entityManager->persist($session);
$entityManager->flush();
$this->envoyerSimpleMessage(
"*Session expirée*\nMerci d'avoir utilisé notre service prix.\nÀ très bientôt.",
$number
);
return;
}
}
$apuisconseil = $entityManager->getRepository(RechercheAppuisConseil::class)->findOneBy(['idSession' => $session->getId(), 'statut' => 1]);
if (!$apuisconseil) {
$this->envoyerSimpleMessage("Aucune session.", $number);
return;
}
if ($apuisconseil->getEtape() == 0) {
// Récupère le choix domaine depuis interactive ou texte
if (isset($messages['interactive']['list_reply']['id'])) {
$choix = $messages['interactive']['list_reply']['id'];
} else {
$this->envoyerSimpleMessage("Veuillez sélectionner un type d'information dans la liste.", $number);
return;
}
$theme = $this->thematiqueTrouver($choix);
if (empty($theme)) {
$this->envoyerSimpleMessage(
"Aucun thème trouvé.",
$number
);
return;
}
$apuisconseil->setResultat(json_encode($theme));
$apuisconseil->setDomaine($choix);
$apuisconseil->setEtape(1); // étape thématique
$entityManager->flush();
$this->EnvoyerListeThematique($choix, $number);
return;
}
if ($apuisconseil->getEtape() == 1 && $typeMessage == "text") {
$choixThematique = trim($messages['text']['body']);
// Vérifie que le choix est un ID numérique ou valide
if (!ctype_digit($choixThematique)) {
$this->envoyerSimpleMessage("Veuillez saisir un numéro valide.", $number);
return;
}
$listetheme = json_decode($apuisconseil->getResultat(), true);
$index = intval($choixThematique) - 1;
if (!isset($listetheme[$index])) {
$this->envoyerSimpleMessage("Numéro invalide. Veuillez réessayer.", $number);
return;
}
$theme = $listetheme[$index];
$idTheme=$theme['id'];
$apuisconseil->setThematique($idTheme);
$apuisconseil->setEtape(2); // fin
$entityManager->flush();
$this->envoyerFichierTheme($number, $idTheme);
sleep(2);
$this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !", $number);
$apuisconseil->setStatut(0);
$apuisconseil->setDeletedAt(new DateTimeImmutable());
$session->setStatut(0);
$session->setDeletedAt(new DateTimeImmutable());
$entityManager->flush();
return;
}
}
#[Route('/communication', name: 'app_communication', methods: ['GET', 'POST'])]
public function index(Request $request, MessageRepository $messageRepository): Response
{
$message = new Message();
$form = $this->createForm(MessageType::class, $message);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$imageFiles = $form->get('image')->getData();
$telephone = $form->get('telephone')->getData();
$contenus = $form->get('contenus')->getData();
$titre = $form->get('titre')->getData();
if ($imageFiles) {
foreach ($imageFiles as $imageFile) {
$newFilename = uniqid().'.'.$imageFile->guessExtension();
try {
$imageFile->move(
$this->getParameter('messages_images_directory'),
$newFilename
);
} catch (FileException $e) {
$this->addFlash('error', 'Impossible de télécharger une image.');
continue;
}
$message->addImage($newFilename);
}
}
$message->setCreatedAt(new \DateTimeImmutable());
$message->setStatus(1);
$message->setIdUser($this->getUser());
// dd($message);
$messageRepository->add($message, true);
$resultat = $this->envoyerMessage("227".$telephone,$contenus,$titre);
// $resultat = $this->envoyerSimpleMessage($contenus, "227".$telephone);
if ($imageFiles) {
$resultat = $this->envoyerMessagePlusDocument("227".$telephone, "1" );
}
return $this->redirectToRoute('app_communication', [], Response::HTTP_SEE_OTHER);
}
$messages = $messageRepository->findBy(
['status' => 1],
['createdAt' => 'DESC']
);
$this->addFlash('success', 'Message envoyé avec succès !');
return $this->render('message/index.html.twig', [
'messages' => $messages,
'form' => $form->createView(),
]);
}
#[Route('/message/{id}', name: 'app_message_show', methods: ['GET', 'POST'])]
public function show(Message $message, MessageRepository $messageRepository): Response
{
return $this->render('message/detail.html.twig', [
'messages' => $messageRepository->findBy(
['status' => 1],
['createdAt' => 'DESC']
),
'message' => $message,
]);
}
public function envoyerSimpleMessage(string $contenus, string $numero)
{
$numero = ltrim($numero, '+');
$apiUrl = 'https://graph.facebook.com/v22.0/1037760686078257/messages';
$token = 'EAAesTlijMGcBQZBCYGuMKGO9Iqz0NQnaKVJPdyV94WmU5kfdLYE5PzgtO67IIL6qaiJMJ8KFLRACc5q7ZCsfCqQi9BmAuxQN88EDxhyhdZClUc16NdZB0TNXVoFWtjZCveKKT9R3ebxRnpYeePhIo0xsYtoQ8tZBwRBTWovkWmZBADso9xcrc3uEtEhCL8KRGKaaTkGeqhVuV2yzfWsVZAHpXzkx4lzwHZCccRyTeZCiDtAkFpoaTiXyTD2sTbLyN5ZC0VZCesDA5TezyKfR2n1vWmo3G98PIgZDZD';
$data = [
"messaging_product" => "whatsapp",
"to" => $numero,
"type" => "text",
"text" => [
"preview_url" => false,
"body" => $contenus
]
];
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $apiUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer $token",
"Content-Type: application/json"
],
CURLOPT_POSTFIELDS => json_encode($data)
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
dump("Curl error: " . curl_error($ch));
}
curl_close($ch);
dump("HTTP CODE: " . $httpCode);
dump("RESPONSE: " . $response);
return $response;
}
// public function envoyerSimpleMessage(string $contenus,string $numero)
// {
// $apiUrl = 'https://graph.facebook.com/v22.0/1037760686078257/messages';
// $token = 'EAAesTlijMGcBQZBCYGuMKGO9Iqz0NQnaKVJPdyV94WmU5kfdLYE5PzgtO67IIL6qaiJMJ8KFLRACc5q7ZCsfCqQi9BmAuxQN88EDxhyhdZClUc16NdZB0TNXVoFWtjZCveKKT9R3ebxRnpYeePhIo0xsYtoQ8tZBwRBTWovkWmZBADso9xcrc3uEtEhCL8KRGKaaTkGeqhVuV2yzfWsVZAHpXzkx4lzwHZCccRyTeZCiDtAkFpoaTiXyTD2sTbLyN5ZC0VZCesDA5TezyKfR2n1vWmo3G98PIgZDZD';
// $data = [
// "messaging_product" => "whatsapp",
// "recipient_type" => "individual",
// "to" => "$numero", // numéro du destinataire
// "type" => "text",
// "text" => [
// "preview_url" => false,
// "body" => $contenus
// ]
// ];
// $ch = curl_init();
// curl_setopt_array($ch, [
// CURLOPT_URL => $apiUrl,
// CURLOPT_RETURNTRANSFER => true,
// CURLOPT_POST => true,
// CURLOPT_HTTPHEADER => [
// "Authorization: Bearer $token",
// "Content-Type: application/json"
// ],
// CURLOPT_POSTFIELDS => json_encode($data)
// ]);
// $response = curl_exec($ch);
// curl_close($ch);
// }
public function ChoixInformation(string $text, string $number)
{
$apiUrl = 'https://graph.facebook.com/v22.0/870067449513702/messages';
$token = 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
$payload = [
"messaging_product" => "whatsapp",
"to" => $number,
"type" => "interactive",
"interactive" => [
"type" => "list",
"body" => [
"text" => $text
],
"footer" => [
"text" => "Pour arrêter le processus tapez merci ou au revoir"
],
"action" => [
"button" => "Choisir un type",
"sections" => [
[
"title" => "Type information",
"rows" => [
[
"id" => "In_01",
"title" => "SEMIS",
"description" => "Dates de semis"
],
[
"id" => "In_02",
"title" => "SECHERESSE",
"description" => "Poches de sècheresse"
],
[
"id" => "In_03",
"title" => "SAISON",
"description" => "Début et fin de la saison"
],
[
"id" => "In_04",
"title" => "ALERTE",
"description" => "Alerte sur l’invasion acridienne et aviaire"
]
]
]
]
]
]
];
try {
$response = $this->client->request('POST', $apiUrl, [
'headers' => [
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json',
],
'json' => $payload,
]);
return $response->toArray();
} catch (\Exception $e) {
return ['error' => $e->getMessage()];
}
}
public function MessageChoixService(string $text, string $number)
{
$apiUrl = 'https://graph.facebook.com/v22.0/870067449513702/messages';
$token = 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
$payload = [
"messaging_product" => "whatsapp",
"to" => $number,
"type" => "interactive",
"interactive" => [
"type" => "list",
"body" => [
"text" => $text
],
"footer" => [
"text" => "Pour arrêter le processus tapez merci ou au revoir"
],
"action" => [
"button" => "Choisir un service",
"sections" => [
[
"title" => "Services disponibles",
"rows" => [
[
"id" => "Sc_001",
"title" => "AGRO METEO",
"description" => "Prévisions météorologiques d'une localité du Niger"
],
[
"id" => "Sc_002",
"title" => "APPUIS CONSEIL",
"description" => "Conseils et assistance dans divers domaines"
],
[
"id" => "Sc_003",
"title" => "PRIX",
"description" => "Prix des animaux et produits agricoles dans les marchés du Niger"
]
]
]
]
]
]
];
try {
$response = $this->client->request('POST', $apiUrl, [
'headers' => [
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json',
],
'json' => $payload,
]);
return $response->toArray();
} catch (\Exception $e) {
return ['error' => $e->getMessage()];
}
}
public function ChoixDomaine(string $number)
{
//on recupere la connection
$all=[
"email"=> "djafarasakinatou@gmail.com",
"password"=> "l2323"
];
$dataPost=json_encode($all);
$chemin='api/authentification';
$response=$this->fonct->execPost('',$chemin,$dataPost);
//on recupere les domaines
$cheminDomaine='api/appuis/conseil/domaine';
$responseDomaine=$this->fonct->execGet($response['data']['token'],$cheminDomaine);
$messageListe = array();
$text="Veuillez choisir un domaine";
foreach ($responseDomaine['data'] as $domaine) {
$messageListe[] = [
"id" => $domaine['id'],
"title" => $domaine['libelle']
];
}
$apiUrl = 'https://graph.facebook.com/v22.0/870067449513702/messages';
$token = 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
$payload = [
"messaging_product" => "whatsapp",
"to" => $number,
"type" => "interactive",
"interactive" => [
"type" => "list",
"body" => [
"text" => $text
],
"footer" => [
"text" => "Pour arrêter le processus tapez merci ou au revoir"
],
"action" => [
"button" => "Choisir un domaine",
"sections" => [
[
"title" => "domaine disponibles",
"rows" => $messageListe
]
]
]
]
];
try {
$response = $this->client->request('POST', $apiUrl, [
'headers' => [
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json',
],
'json' => $payload,
]);
return $response->toArray();
} catch (\Exception $e) {
return ['error' => $e->getMessage()];
}
}
public function EnvoyerListeThematique($choix, $number)
{
// Authentification
$auth = $this->fonct->execPost('', 'api/authentification', json_encode(["email"=> "djafarasakinatou@gmail.com","password"=> "l2323"]));
//thématiques
$responseThematique = $this->fonct->execPost($auth['data']['token'],'api/appuis/conseil/theme',json_encode(["id_domaine" => $choix]));
//$this->envoyerSimpleMessage("DEBUG : \n" . json_encode($responseThematique), $number);
if (!isset($responseThematique['data'])) {
$this->envoyerSimpleMessage("Aucune donnée trouvée pour cette commune.", $number);
return;
}
// texte
$msg = "📚 *Veuillez choisir une thématique :*\n\n";
foreach ($responseThematique['data'] as $theme) {
$msg .= "👉 Tapez *{$theme['N°']}* pour *{$theme['libelle']}*\n";
}
$msg .= "\nPour arrêter tapez *merci* ou *au revoir*.";
// Envoyer
$this->envoyerSimpleMessage($msg, $number);
}
public function thematiqueTrouver($domaine): array
{
// Authentification
$auth = $this->fonct->execPost('','api/authentification',json_encode([
"email"=> "djafarasakinatou@gmail.com",
"password"=> "l2323"
])
);
// Vérification authentification
if (!isset($auth['data']['token'])) {
return [];
}
$token = $auth['data']['token'];
// Récupération thématiques
$response = $this->fonct->execPost($token,'api/appuis/conseil/theme',json_encode(["id_domaine" => $domaine]));
// Vérification statuts
if (!isset($response['status']) || $response['status'] !== 200) {
return [];
}
// Retour du tableau des thématiques
return $response['data'] ?? [];
}
#[Route('/envoyer/fichier', name: 'app_envoyer_fichier', methods: ['POST'])]
public function envoyerFichier(Request $request, EntityManagerInterface $entityManager, UserRepository $UserRepository): Response
{
$data = json_decode($request->getContent(), true);
$obligatoire = ['id_theme','numero'];
foreach ($obligatoire as $champs) {
if (empty($data[$champs])) {
return $this->json([
'status' => 400,
'message' => 'failed',
'data' => ['error_message' => "Le champ $champs est obligatoire."],
]);
}
}
$apiUrl = 'https://graph.facebook.com/v22.0/870067449513702/messages';
$token = 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
// Authentification interne
$auth = $this->fonct->execPost('', 'api/authentification', json_encode([
"email"=> "djafarasakinatou@gmail.com",
"password"=> "l2323"
]));
// Récupération des fichiers
$responsefichiers = $this->fonct->execPost(
$auth['data']['token'],
'api/appuis/conseil/fichier',
json_encode(["id_theme"=> $data['id_theme']])
);
if (!isset($responsefichiers['data']) || empty($responsefichiers['data'])) {
return $this->json(['status' => 400, 'message' => 'Aucun fichier trouvé']);
}
//dd($responsefichiers);
$dataFichier = [];
// $i=0;
foreach ($responsefichiers['data'] as $item) {
$dataFichier[] = [
'conseil'=>$item['conseil'],
'fichier'=>$item['fichier'],
'semaine'=>$item['semaine'],
'date_ajout'=>$item['date_ajout'],
];
$extension = pathinfo($item['fichier'], PATHINFO_EXTENSION);
// dd($extension);
$payload = [
"to" => $data['numero'],
"type" => "template",
"messaging_product" => "whatsapp",
"template" => [
"name" => "model_garbal_format_document",
"language" => ["code" => "fr"],
"components" => [
[
"type" => "header",
"parameters" => [
[
"type" => "document",
"document" => [
"link" => $item['fichier'],
"filename" => $item['conseil']
]
]
]
],
[
"type" => "body",
"parameters" => [
[
"type" => "text",
"text" => $item['conseil']
]
]
]
]
]
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer '.$token,
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
file_put_contents("whatsapp_response.log", "RESPONSE: ".$response." | ERROR: ".$error.PHP_EOL, FILE_APPEND);
// usleep(300000); // pause 0.3s pour ne pas se faire bloquer
}
return $this->json([
'status' => 200,
'message' => 'Fichiers envoyés avec succès'
// 'data' => $dataFichier
]);
}
public function envoyerFichierTheme($numero, $id_theme)
{
$apiUrl = 'https://graph.facebook.com/v22.0/870067449513702/messages';
$token = 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
// Authentification interne
$auth = $this->fonct->execPost('', 'api/authentification', json_encode([
"email"=> "djafarasakinatou@gmail.com",
"password"=> "l2323"
]));
//$this->envoyerSimpleMessage("Aucune donnée trouvée pour cette commune.", $numero);
// Récupération des fichiers
$responsefichiers = $this->fonct->execPost(
$auth['data']['token'],
'api/appuis/conseil/fichier',
json_encode(["id_theme"=> $id_theme])
);
//$this->envoyerSimpleMessage("DEBUG : \n" . json_encode($responsefichiers), $numero);
if (!isset($responsefichiers['data']) || empty($responsefichiers['data'])) {
$this->envoyerSimpleMessage("Aucune donnée trouvée .", $numero);
return;
}
$this->envoyerSimpleMessage("Veuillez patienter quelques instants, les fichiers sont en cours d'envoi…", $numero);
//dd($responsefichiers);
$dataFichier = [];
// $i=0;
foreach ($responsefichiers['data'] as $item) {
// $this->envoyerSimpleMessage("TEST : ".$item['fichier'], $numero);
$dataFichier[] = [
'conseil'=>$item['conseil'],
'fichier'=>$item['fichier'],
'semaine'=>$item['semaine'],
'date_ajout'=>$item['date_ajout'],
];
$extension = pathinfo($item['fichier'], PATHINFO_EXTENSION);
// dd($extension);
$payload = [
"to" => $numero,
"type" => "template",
"messaging_product" => "whatsapp",
"template" => [
"name" => "model_garbal_format_document",
"language" => ["code" => "fr"],
"components" => [
[
"type" => "header",
"parameters" => [
[
"type" => "document",
"document" => [
"link" => $item['fichier'],
"filename" => $item['conseil']
]
]
]
],
[
"type" => "body",
"parameters" => [
[
"type" => "text",
"text" => $item['conseil']
]
]
]
]
]
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer '.$token,
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
file_put_contents("whatsapp_response.log", "RESPONSE: ".$response." | ERROR: ".$error.PHP_EOL, FILE_APPEND);
// usleep(300000); // pause 0.3s pour ne pas se faire bloquer
}
}
public function envoyerMessagePlusDocument(string $numero, string $nombre)
{
$apiUrl = 'https://graph.facebook.com/v22.0/870067449513702/messages';
$token = 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcS';
$payload = [
"messaging_product" => "whatsapp",
"to" => "$numero",
"type" => "template",
"template" => [
"name" => "model_garbal_format_document ",
"language" => ["code" => "FR"],
"components" => [
[
"type" => "body",
"parameters" => [
["type" => "text", "text" => $nombre],
],
],
],
],
];
try {
$response = $this->client->request('POST', $apiUrl, [
'headers' => [
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json',
],
'json' => $payload,
]);
return $response->toArray();
} catch (\Exception $e) {
return ['error' => $e->getMessage()];
}
}
public function envoyerMessage(string $numero, string $contenus ,string $titre)
{
$apiUrl = 'https://graph.facebook.com/v22.0/870067449513702/messages';
$token = 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
$payload = [
"messaging_product" => "whatsapp",
"to" => "$numero",
"type" => "template",
"template" => [
"name" => "model_garbal_message",
"language" => ["code" => "fr"],
"components" => [
[
"type" => "header",
"parameters" => [
[
"type" => "text",
"text" => $titre,
]
]
],
[
"type" => "body",
"parameters" => [
["type" => "text", "text" => $contenus],
],
],
],
],
];
try {
$response = $this->client->request('POST', $apiUrl, [
'headers' => [
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json',
],
'json' => $payload,
]);
return $response->toArray();
} catch (\Exception $e) {
return ['error' => $e->getMessage()];
}
}
private function validateToken(Request $request, JWTEncoderInterface $JWTDecodeManager, EntityManagerInterface $entityManager, UserRepository $UserRepository)
{
$authorizationHeader = $request->headers->get('Authorization');
if (!$authorizationHeader) {
return new JsonResponse(['status' => 401, 'message' => 'Token non fourni'], 401);
}
$tokenParts = explode(' ', $authorizationHeader);
if (count($tokenParts) !== 2 || $tokenParts[0] !== 'Bearer') {
return new JsonResponse(['status' => 401, 'message' => 'Format du token invalide'], 401);
}
$token = $tokenParts[1];
try {
$userData = $JWTDecodeManager->decode($token);
} catch (\Exception $e) {
return new JsonResponse(['status' => 401, 'message' => 'Token invalide'], 401);
}
if (!isset($userData['username'])) {
return new JsonResponse(['status' => 401, 'message' => 'Token mal formé (username manquant)'], 401);
}
// dd($userData);
$user = $UserRepository->findOneBy(['email' => $userData['username']]);
if (!$user) {
return new JsonResponse(['status' => 401, 'message' => 'Utilisateur non trouvé'], 401);
}
if ($user->getStatut() != 1) {
return new JsonResponse(['status' => 401, 'message' => 'Compte inactif'], 401);
}
if (isset($userData['exp']) && $userData['exp'] < time()) {
return new JsonResponse(['status' => 401, 'message' => 'Token expiré'], 401);
}
// Tout est bon, on retourne les infos de l'utilisateur
return [
'id' => $user->getId(),
'role' => $user->getRoles(),
'email' => $user->getEmail()
];
}
}