<?php
namespace App\Controller\Api;
use App\Entity\Adherent\Annuaire\MagasinContact;
use App\Entity\Adherent\Magasin;
use App\Entity\Adherent\MagasinCoordonnees;
use App\Entity\Adherent\MagasinUrl;
use App\Entity\Image\Image;
use App\Entity\TraficMagasin\NotifReport;
use App\Entity\TraficMagasin\RdvOpc;
use App\Entity\Webfactory\Opc\OpcImage;
use App\Manager\NotificationManager;
use App\Manager\OpcManager;
use App\Manager\TraficMagasin\SmsApiManager;
use Brick\PhoneNumber\PhoneNumberFormat;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Finder\Exception\AccessDeniedException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
#[Route(path: '/api')]
class ApiOpcController extends AbstractController
{
public function __construct(private readonly EntityManagerInterface $entityManager, private readonly NotificationManager $notificationManager)
{
}
#[Route(path: '/no-permission', name: 'no_permission')]
public function noPermission(): never
{
throw new AccessDeniedException();
}
/**
* @param Request $request
* @param EntityManagerInterface $entityManager
* @param $code
* @return JsonResponse|void
*/
#[Route(path: '/get-url-fiche/{code}', name: 'get_url_fiche')]
public function getUrlFiche(Request $request, EntityManagerInterface $entityManager, $code)
{
$url = $entityManager->getRepository(MagasinUrl::class)->findOneBy(["type" => "OPC/OZC", "magasin" => $code]);
if (!empty($url)) {
return $this->json(['code' => $url->getMagasin()->getKAdherent(), 'url' => $url->getUrl()]);
} else {
return $this->json([]);
}
}
/**
* @param Request $request
* @param EntityManagerInterface $entityManager
* @param OpcManager $manager
* @param $code
* @return JsonResponse|void
*/
#[Route(path: '/get-url-rdv/{code}', name: 'get_url_rdv')]
public function getUrlRDV(Request $request, EntityManagerInterface $entityManager, OpcManager $manager, $code)
{
$urlRdv = $this->entityManager->getRepository(MagasinUrl::class)->findOneBy(['magasin' => $code, 'type' => 'rdv']);
if (!is_null($urlRdv)) {
return $this->json(['code' => $code, 'url' => $urlRdv]);
} else {
$magasinCoordonnees = $entityManager->getRepository(MagasinCoordonnees::class)->findOneBy(['K_ADHERENT' => $code]);
if (!empty($magasinCoordonnees)) {
$url = $manager->getAdhOpcUrl($magasinCoordonnees, priseDeRdv: true);
return $this->json(['code' => $code, 'url' => $url]);
}
}
}
/**
* @param EntityManagerInterface $entityManager
* @return JsonResponse
*/
#[Route(path: '/image/vignettes', name: 'get_vignettes')]
public function getVignettes(Request $request)
{
$tab = [];
$parameters = json_decode($request->getContent(), true);
if (isset($parameters['adherents']) && !empty($parameters['adherents'])) {
$vignettes = $this->entityManager->getRepository(Image::class)->getVignettes($parameters['adherents']);
foreach ($vignettes as $vignette) {
$tab[$vignette->getAdherent()] = [
'img' => $vignette->getName(),
'ext' => $vignette->getExtension(),
'type' => $vignette->getType()->getName(),
'logo' => $vignette->getLogoDefault(),
'vignette' => $vignette->getProfileDefault(),
];
}
return new JsonResponse(['Status' => "200", 'datas' => $tab]);
} else {
return new JsonResponse(['Status' => "400", 'errors' => "Parametre adherents manquant"]);
}
}
/**
* @param $adherent
* @return JsonResponse
*/
#[Route(path: '/image/photos/{magasin}', name: 'get_photos_by_adherents')]
public function getPhotos(Request $request, Magasin $magasin)
{
$tab = [];
$photos = $this->entityManager->getRepository(OpcImage::class)->findBy(['kAdh' => $magasin->getKAdherent()], ['sort' => 'ASC']);
foreach ($photos as $photo) {
$tab[strtoupper((string)$photo->getIdImage()->getAdherent())][] = [
'img' => $photo->getIdImage()->getName(),
'ext' => $photo->getIdImage()->getExtension(),
'type' => $photo->getIdImage()->getType()->getName(),
'logo' => $photo->getIdImage()->getLogoDefault(),
'vignette' => $photo->getIdImage()->getProfileDefault()
];
}
return new JsonResponse(['Status' => "200", 'datas' => $tab]);
}
/**
* Insère en base les demandes de rendez-vous depuis OPC
*/
#[Route(path: '/sendRdvOpc', name: 'sendrdvopc')]
public function sendRdvOpc(Request $request): JsonResponse
{
//on récupère les data
$datas = json_decode($request->getContent(), true);
if ($datas) {
//on les enregistre sur la table rdv_optician sur espace adhérent
$new_rdv = new RdvOpc();
$new_rdv->setKAdherent($datas[0]['codeAdh']);
$new_rdv->setFirstName($datas[0]['prenom']);
$new_rdv->setLastName($datas[0]['nom']);
$new_rdv->setPhone($datas[0]['tel']);
$new_rdv->setIndicatif($datas[0]['indicatif']);
if ($datas[0]['email'] != null) {
$new_rdv->setEmail($datas[0]['email']);
}
$new_rdv->setObject($datas[0]['objet']);
$new_rdv->setDate(new \DateTime($datas[0]['date']['date']));
$new_rdv->setDateNaissance(new \DateTime($datas[0]['date_naissance']['date']));
$new_rdv->setMoment($datas[0]['moment']);
$new_rdv->setLang($datas[0]['lang']);
$new_rdv->setAlreadyCustomer($datas[0]['client'] == "Non" ? 0 : 1);
$new_rdv->setComment($datas[0]['comment'] ?: '');
$new_rdv->setNumDemande($datas[0]['numDemande'] ?: '');
$new_rdv->setPrenomProche($datas[0]['prenom_proche']);
$new_rdv->setNomProche($datas[0]['nom_proche']);
$new_rdv->setDateNaissanceProche(($datas[0]['date_naissance_proche']) ? new \DateTime($datas[0]['date_naissance_proche']['date']) : null);
$new_rdv->setIsForMe((int)$datas[0]['rdvPourMoi']);
$new_rdv->setRepresentantLegals($datas[0]['representant_legals']);
$this->entityManager->persist($new_rdv);
$this->entityManager->flush();
return new JsonResponse(['status' => 200, 'datas' => $datas]);
} else {
return new JsonResponse(['status' => 400, 'error' => "Aucune donnée envoyée"]);
}
}
/**
* Crée les notifications pour les rendez-vous
*/
#[Route(path: '/pushNotif', name: 'pushnotif')]
public function pushNotificationAction(Request $request): JsonResponse
{
//on récupère les data
$datas = json_decode($request->getContent(), true);
if ($datas) {
$this->notificationManager->popNotification(
$datas[0]['codeAdh'],
strtolower($datas[0]['langue']),
'trafic_magasin',
'trafic_magasin_new_rdv',
((strtolower($datas[0]['langue']) == "fr") ? 'Mon trafic magasin' : 'Mijn winkelverkeer'),
$this->generateUrl('trafic_index'),
$datas[0]['objet'],
true
);
return new JsonResponse(['status' => 200, 'datas' => $datas]);
} else {
return new JsonResponse(['status' => 400, 'error' => "Aucune donnée envoyée"]);
}
}
/**
* @return JsonResponse|void
* @throws \Exception
*/
#[Route(path: '/send-sms', name: 'send_sms')]
public function sendSms(Request $request, SmsApiManager $smsApiManager)
{
if ($request->isMethod("POST")) {
$errors = [];
if (!$request->request->has('codeAdherent')) {
$errors["errors"][] = "codeAdherent not found";
}
if ($request->request->has('deliveryTime')) {
$request->request->set('deliveryTime', new \DateTime($request->request->get('deliveryTime')));
}
if (!$request->request->has('destinationAddress')) {
$errors["errors"][] = "Field destinationAddress not found !";
}
if (!$request->request->has('messageText')) {
$errors["errors"][] = "Field messageText not found !";
}
if (!$request->request->has('campaignName')) {
$errors["errors"][] = "Field campaignName not found !";
}
if (!$request->request->has('originatingAddress')) {
$errors["errors"][] = "Field originatingAddress not found !";
}
if (empty($errors)) {
if ($request->request->get('destinationAddress') == "false" && $request->request->get('searchPhone') == "true") {
$phoneNumber = $this->entityManager->getRepository(MagasinContact::class)->getSpecificContact($request->request->get('codeAdherent'), 'rdv_sms');
$phoneNumber = $smsApiManager->getFormatSmsNumber($phoneNumber);
if ($phoneNumber) {
$request->request->set('destinationAddress', $phoneNumber);
} else {
$errors["errors"][] = "Invalid phone number or not found";
return new JsonResponse($errors);
}
}
if ($smsApiManager->canISendSms($request->request->get('codeAdherent'))) {
$notifReport = new NotifReport();
$notifReport->setKAdherent($request->request->get('codeAdherent'));
$notifReport->setKPays((substr(strtoupper($request->request->get('codeAdherent')), 0, 1) == "B") ? "BE" : 'FR');
$notifReport->setType("SMS");
$notifReport->setDeliveryDate(new \DateTime());
$notifReport->setDestination($request->request->get('destinationAddress'));
$notifReport->setMessageText($request->request->get('messageText'));
$notifReport->setCampaign($request->request->get('campaignName'));
$this->entityManager->persist($notifReport);
$this->entityManager->flush();
$rep = $smsApiManager->sendSms(
$request->request->get('destinationAddress'),
$request->request->get('messageText'),
$request->request->get('campaignName'),
$request->request->get('originatingAddress'),
($request->request->has('deliveryTime')) ? $request->request->get('deliveryTime') : null
);
return new JsonResponse(json_decode($rep));
} else {
$errors["errors"][] = "Impossible d'envoyer le sms ce jour.";
return new JsonResponse($errors);
}
} else {
return new JsonResponse($errors);
}
}
}
/**
* @return JsonResponse|void
* @throws \Exception
*/
#[Route(path: '/send-sms-client', name: 'send_sms_client')]
public function sendSmsClient(Request $request, SmsApiManager $smsApiManager)
{
if ($request->isMethod("POST")) {
$errors = [];
if ($request->request->has('deliveryTime')) {
$request->request->set('deliveryTime', new \DateTime($request->request->get('deliveryTime')));
}
if (!$request->request->has('destinationAddress')) {
$errors["errors"][] = "Field destinationAddress not found !";
}
if (!$request->request->has('messageText')) {
$errors["errors"][] = "Field messageText not found !";
}
if (!$request->request->has('campaignName')) {
$errors["errors"][] = "Field campaignName not found !";
}
if (!$request->request->has('originatingAddress')) {
$errors["errors"][] = "Field originatingAddress not found !";
}
if (!$request->request->has('phone')) {
$errors["errors"][] = "Phone number not found !";
}
if (empty($errors)) {
if ($request->request->get('destinationAddress') == "false" && $request->request->get('searchPhone') == "true") {
$phoneNumber = $request->request->get('phone');
$formattedPhoneNumber = $smsApiManager->getFormatSmsNumberClient($phoneNumber, $request->request->get('lang'));
if ($formattedPhoneNumber) {
$request->request->set('destinationAddress', $formattedPhoneNumber);
} else {
$errors["errors"][] = "Invalid phone number or not found";
return new JsonResponse($errors);
}
}
$rep = $smsApiManager->sendSms(
$request->request->get('destinationAddress'),
$request->request->get('messageText'),
$request->request->get('campaignName'),
$request->request->get('originatingAddress'),
);
return new JsonResponse(json_decode($rep));
} else {
return new JsonResponse($errors);
}
}
}
}