<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use App\Repository\UserRepository;
use App\Repository\VillesRepository;
use App\Repository\PaysRepository;
use App\Repository\CategoriesRepository;
use App\Repository\AnnoncesRepository;
use App\Repository\NotesEnseignesRepository;
use App\Repository\NotesAnnoncesRepository;
use App\Repository\ImagesRepository;
use App\Repository\FavorisRepository;
use App\Repository\FacturesRepository;
use App\Repository\CommandesRepository;
use App\Repository\AlertesRepository;
use Datetime;
use App\Entity\User;
use App\Entity\Annonces;
use App\Entity\Images;
use App\Entity\Alertes;
use App\Entity\NotesAnnonces;
use App\Entity\Favoris;
class ApiController extends AbstractController
{
/**
* @Route("/api/login", name="app_apiLogin")
*/
public function app_apiLogin(UserRepository $userRepository): Response
{
//Ajoute une mairie en favoris en fonction de l'id de la mairie et de l'UUID
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// Passer id de la mairie en GET['id']
$reponse = array();
$data = json_decode(file_get_contents('php://input'), true);
if ($data) {
$email = $data['mail'];
$password = $data['password'];
$user = $userRepository->findOneBy(['email' => $email]);
if ($user && password_verify($password, $user->getPassword())) {
$token = bin2hex(random_bytes(16));
$user->setTokenMobile($token);
$userRepository->add($user, true);
// Les informations d'identification sont valides, vous pouvez utiliser l'objet $user
$reponse['user']['idUser'] = $user->getId();
$reponse['user']['token'] = $user->getTokenMobile();
$reponse['user']['type'] = $user->getType();
$reponse['user']['mail'] = $user->getEmail();
$reponse['message'] = 'Connexion réussie';
} else {
$reponse['user'] = null;
$reponse['message'] = 'Identifiants invalides';
}
return new Response(json_encode($reponse));
} elseif ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
return (new Response())->setStatusCode(200);
}
return (new Response())
->setStatusCode(401)
->withBody('Unauthorized');
}
/**
* @Route("/api/token", name="app_apiToken")
*/
public function app_apiToken(UserRepository $userRepository): Response
{
//Ajoute une mairie en favoris en fonction de l'id de la mairie et de l'UUID
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// Passer id de la mairie en GET['id']
$reponse = array();
$data = json_decode(file_get_contents('php://input'), true);
if ($data) {
$token = $data['token'];
$email = $data['mail'];
$user = $userRepository->findOneBy(['email' => $email]);
if($user->getTokenMobile() != $token)
{
$user->setTokenMobile($token);
$userRepository->add($user, true);
}
return new Response(json_encode($reponse));
} elseif ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
return (new Response())->setStatusCode(200);
}
return (new Response())
->setStatusCode(401)
->withBody('Unauthorized');
}
/**
* @Route("/api/inscription", name="app_apiInscription")
*/
public function app_apiInscription(UserRepository $userRepository, VillesRepository $villesRepository, PaysRepository $paysRepository): Response
{
//Ajoute une mairie en favoris en fonction de l'id de la mairie et de l'UUID
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// Passer id de la mairie en GET['id']
$client = new User();
$res = new Response();
$data = json_decode(file_get_contents('php://input'), true);
if ($data) {
$ville = $data['cityId'];
$pays = $data['country'];
$email = $data['mail'];
$password = $data['password'];
$type = $data['type'] ?? 'particuliers';
$genre = $data['gender'];
$nom = $data['name'];
$prenom = $data['surname'];
$raisonSociale = $data['socialReason'] ?? null;
$siret = $data['siret'] ?? null;
$tva = $data['tva'] ?? null;
$adresse = $data['address'];
$codePostal = $data['postalCode'];
$telephone = $data['phone'];
$credit = 0;
if ($type == 'particuliers') {
$role = array("ROLE_PART");
} else {
$role = array("ROLE_PRO");
$credit = 100;
}
$ville = $villesRepository->findOneById($ville);
$pays = $paysRepository->findOneById($pays);
$clientExist = $userRepository->findOneBy(array('email' => $email));
if ($type == 'professionnel') {
// upload du logo dans le dossier public/uploads/logos
$logoBase64 = $data['logo'];
[$imgType, $logoBase64] = explode(';', $logoBase64);
[, $logoBase64] = explode(',', $logoBase64);
[, $extension] = explode('/', $imgType);
$logo = base64_decode($logoBase64);
$logoName = uniqid('logo') . '.' . $extension;
file_put_contents(dirname(__DIR__, 2) . '/uploads/logos/' . $logoName, $logo);
$client->setLogo($logoName);
}
if (!empty($clientExist)) {
$res->setStatusCode(301)
->setContent(json_encode(array(
'message' => 'L\'email existe déjà'
)));
} else {
$pass = password_hash($password, PASSWORD_BCRYPT);
$client->setPassword($pass);
$client->setType($type);
$client->setEmail($email);
$client->setRoles($role);
$client->setCivilite($genre);
$client->setPays($pays);
$client->setVilles($ville);
$client->setCredits($credit);
$client->setCreated(new DateTime());
$client->setNom($nom);
$client->setPrenom($prenom);
$client->setRaisonSociale($raisonSociale);
$client->setSiret($siret);
$client->setTva($tva);
$client->setAdresse($adresse);
$client->setCodePostal($codePostal);
$client->setTelephone($telephone);
$client->setActif(1);
$userRepository->add($client, true);
$res->setStatusCode(200)
->setContent(json_encode(array(
'message' => 'Le compte est ajouté avec succès'
)));
}
} else {
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
$res->setStatusCode(200)
->setContent(json_encode(array(
'message' => 'OK'
)));
} else {
$res->setStatusCode(301)
->setContent(json_encode(array(
'message' => 'Aucune donnée reçue'
)));
}
}
return $res;
}
/**
* @Route("/api/searchCities", name="searchCities")
*/
public function searchCities(UserRepository $userRepository, VillesRepository $villesRepository, PaysRepository $paysRepository): Response
{
//Ajoute une mairie en favoris en fonction de l'id de la mairie et de l'UUID
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// Passer id de la mairie en GET['id']
$chaine = $_GET["q"];
$villes = $villesRepository->findByExampleField($chaine);
$i = -1;
$ville = array();
foreach ($villes as $res) {
$i++;
$ville[$i]['id'] = $res->getId();
$ville[$i]['nom'] = $res->getVilleNom();
$ville[$i]['cp'] = $res->getVilleCodePostal();
}
return new Response(json_encode($ville));
}
/**
* @Route("/api/categories", name="categoriesList")
*/
public function categoriesList(UserRepository $userRepository, CategoriesRepository $categoriesRepository): Response
{
//Ajoute une mairie en favoris en fonction de l'id de la mairie et de l'UUID
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$cats = $categoriesRepository->findBy([], ['Libelle' => 'asc']);
$i = -1;
$categories = array();
foreach ($cats as $res) {
$i++;
$categories[$i]['id'] = $res->getId();
$categories[$i]['libelle'] = $res->getLibelle();
}
return new Response(json_encode($categories));
}
/**
* @Route("/api/searchAnnonces", name="searchAnnonces")
*/
public function searchAnnonces(FavorisRepository $favorisRepository, UserRepository $userRepository, VillesRepository $villesRepository, CategoriesRepository $categoriesRepository, AnnoncesRepository $annoncesRepository, NotesEnseignesRepository $notesEnseignesRepository): Response
{
//Ajoute une mairie en favoris en fonction de l'id de la mairie et de l'UUID
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$categoriesSearch = '';
$citiesRes = '';
if (isset($_GET['token'])) {
$token = $_GET['token'];
$user = $userRepository->findOneBy(['TokenMobile' => $token]);
} else {
$user = array();
$token = '';
}
if (isset($_GET['tri'])) {
$triSearch = $_GET['tri'];
} else {
$triSearch = '';
}
if (isset($_GET['nbParPage'])) {
$nbParPage = $_GET['nbParPage'];
} else {
$nbParPage = 25;
}
if (isset($_GET['pro'])) {
$pro = $_GET['pro'] === "true" ? 1 : 0;
} else {
$pro = 0;
}
if (isset($_GET['motscles'])) {
$motscles = $_GET['motscles'];
} else {
$motscles = '';
}
$villes = array();
$citiesRes = array();
$em = $this->getDoctrine()->getManager();
// Fin
if (isset($_GET['categories'])) {
$categoriesSearch = $_GET['categories'];
} else {
$categoriesSearch = array();
}
if (isset($_GET['ville'])) {
$ville = $_GET['ville'];
} else {
$ville = '';
}
$villes = $villesRepository->findOneById($ville);
if (isset($_GET['rayon'])) {
$distance = $_GET['rayon'];
} else {
$distance = 50;
}
// Il faut ajouter le repertoire doctrine/dql dans src
// Il faut ajouter les lignes dans services.yaml
// Il faut ajouter les lignes dans doctrine.yaml
if (!empty($villes)) {
// RECUPERER LES VILLES DANS UN RAYON
$lat = $villes->getVilleLatitudeDeg();
$lng = $villes->getVilleLongitudeDeg();
$formule = '(6371 * ACOS(COS(RADIANS(:lat)) * COS(RADIANS(c.VilleLatitudeDeg)) * COS(RADIANS(c.VilleLongitudeDeg) - RADIANS(:lng)) + SIN(RADIANS(:lat)) * SIN(RADIANS(c.VilleLatitudeDeg))))';
$query = $em->createQuery("
SELECT c.id,c.VilleNom, $formule as dist
FROM App\Entity\Villes c
WHERE $formule <= :distance order by dist asc ")->setParameters([
'lat' => $lat,
'lng' => $lng,
'distance' => $distance,
]);
$cities = $query->getResult();
foreach ($cities as $resVille) {
array_push($citiesRes, $resVille['id']);
}
}
$annoncesReq = $annoncesRepository->findByMultiCriteresMobile($categoriesSearch, $citiesRes, $pro, $triSearch, $motscles);
$i = -1;
$annonces = array();
foreach ($annoncesReq as $res) {
$i++;
$favoris = $favorisRepository->findOneBy(['Annonces' => $res->getId(), 'User'=>$user]);
if($favoris)
{
$annonces[$i]['favoris'] = true;
$annonces[$i]['favorisId'] = $favoris->getId();
}
else
{
$annonces[$i]['favoris'] = false;
}
$annonces[$i]['id'] = $res->getId();
$annonces[$i]['boost'] = $res->isBooster();
$annonces[$i]['titre'] = $res->getTitre();
$annonces[$i]['enseigne'] = $res->getUser()->getRaisonSociale();
$annonces[$i]['logo'] = 'https://modixom.fr/uploads/logos/' . $res->getUser()->getLogo();
$images = $res->getImages();
$annonces[$i]['images'] = (count($images) > 0) ? 'https://modixom.fr/uploads/annonces/' . $images[0]->getLien() : 'default.jpg'; // Utilisez une image par défaut si aucune image n'est disponible
$annonces[$i]['pourcentRemise'] = $res->getPourcentRemise();
$annonces[$i]['prix'] = $res->getPrix();
$annonces[$i]['description'] = $res->getDescription();
$pourcent = 1 - $res->getPourcentRemise() / 100;
$annonces[$i]['newprix'] = $res->getPrix() * $pourcent;
$fin = strtotime($res->getDateFin()->format('Y-m-d H:i:s'));
$debut = strtotime(date('Y-m-d H:i:s'));
$diff = abs($debut - $fin); // abs pour avoir la valeur absolute, ainsi éviter d'avoir une différence négative
$retour = array();
$tmp = $diff;
$retour['second'] = $tmp % 60;
$tmp = floor(($tmp - $retour['second']) / 60);
$retour['minute'] = $tmp % 60;
$tmp = floor(($tmp - $retour['minute']) / 60);
$retour['hour'] = $tmp % 24;
$tmp = floor(($tmp - $retour['hour']) / 24);
$retour['day'] = $tmp * 24;
$annonces[$i]['heures'] = $tmp * 24 + $retour['hour'];
$annonces[$i]['minutes'] = $retour['minute'];
$annonces[$i]['secondes'] = $retour['second'];
// CALCUL DE LA MOYENNE DE LANNONCE
$sum = 0;
$moy = 0;
$y = 0;
foreach ($res->getNotesAnnonces() as $res2) {
$y++;
$sum = $sum + $res2->getNote();
}
if ($y > 0) {
$moy = $sum / $y;
$moyAnnonce = (round($moy * 2) / 2);
} else {
$moyAnnonce = 0;
}
$annonces[$i]['moyAnnonce'] = $moyAnnonce;
$annonces[$i]["nbNoteAnnonce"] = $y;
// CALCUL DE LA MOYENNE DE ENSEIGNE
$sum = 0;
$moy = 0;
$y = 0;
$notesEns = $notesEnseignesRepository->findBy(array('Enseigne' => $res->getUser()));
foreach ($notesEns as $res2) {
$y++;
$sum = $sum + $res2->getNote();
}
$maxNote = $y * 5;
if ($maxNote > 0) {
$noteEnseigne = ($sum * 100) / $maxNote;
} else {
$noteEnseigne = 0;
}
$annonces[$i]['moyEnseigne'] = $noteEnseigne;
}
return new Response(json_encode($annonces));
}
/**
* @Route("/api/getFactures", name="getFactures")
*/
public function getFactures(FacturesRepository $facturesRepository,UserRepository $userRepository, CommandesRepository $commandesRepository): Response
{
//Ajoute une mairie en favoris en fonction de l'id de la mairie et de l'UUID
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$_GET['token'] = '095421a4e2fead6820d921862592f1ad';
if (isset($_GET['token'])) {
$token = $_GET['token'];
$user = $userRepository->findOneBy(['TokenMobile' => $token]);
$factures = $facturesRepository->findBy(['User'=>$user]);
$i = -1;
$facts = array();
foreach ($factures as $res) {
$i++;
$facts[$i]['id'] = $res->getId();
$facts[$i]['date'] = $res->getCreated()->format('d-m-Y');
$facts[$i]['fichier'] = 'https://modixom.fr/factures/'.$res->getLienDoc();
}
return new Response(json_encode($facts));
}
}
/**
* @Route("/api/getFavoris", name="getFavoris")
*/
public function getFavoris(FavorisRepository $favorisRepository, UserRepository $userRepository, VillesRepository $villesRepository, CategoriesRepository $categoriesRepository, AnnoncesRepository $annoncesRepository, NotesEnseignesRepository $notesEnseignesRepository): Response
{
//Ajoute une mairie en favoris en fonction de l'id de la mairie et de l'UUID
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$categoriesSearch = '';
$citiesRes = '';
if (isset($_GET['token'])) {
$token = $_GET['token'];
$user = $userRepository->findOneBy(['TokenMobile' => $token]);
} else {
$user = array();
$token = '';
}
if (isset($_GET['tri'])) {
$triSearch = $_GET['tri'];
} else {
$triSearch = '';
}
if (isset($_GET['nbParPage'])) {
$nbParPage = $_GET['nbParPage'];
} else {
$nbParPage = 25;
}
if (isset($_GET['pro'])) {
$pro = $_GET['pro'] === "true" ? 1 : 0;
} else {
$pro = 0;
}
if (isset($_GET['motscles'])) {
$motscles = $_GET['motscles'];
} else {
$motscles = '';
}
$villes = array();
$citiesRes = array();
$em = $this->getDoctrine()->getManager();
// Fin
if (isset($_GET['categories'])) {
$categoriesSearch = $_GET['categories'];
} else {
$categoriesSearch = array();
}
$citiesRes = array();
$annoncesReq = $annoncesRepository->findByMultiCriteresMobile($categoriesSearch, $citiesRes, $pro, $triSearch, $motscles);
$i = -1;
$annonces = array();
foreach ($annoncesReq as $res) {
$favoris = $favorisRepository->findOneBy(['Annonces' => $res->getId(), 'User'=>$user]);
if($favoris)
{
$i++;
$annonces[$i]['favoris'] = true;
$annonces[$i]["favorisId"] = $favoris->getId();
$annonces[$i]['id'] = $res->getId();
$annonces[$i]['boost'] = $res->isBooster();
$annonces[$i]['titre'] = $res->getTitre();
$annonces[$i]['enseigne'] = $res->getUser()->getRaisonSociale();
$annonces[$i]['logo'] = 'https://modixom.fr/uploads/logos/' . $res->getUser()->getLogo();
$images = $res->getImages();
$annonces[$i]['images'] = (count($images) > 0) ? 'https://modixom.fr/uploads/annonces/' . $images[0]->getLien() : 'default.jpg'; // Utilisez une image par défaut si aucune image n'est disponible
$annonces[$i]['pourcentRemise'] = $res->getPourcentRemise();
$annonces[$i]['prix'] = $res->getPrix();
$annonces[$i]['description'] = $res->getDescription();
$pourcent = 1 - $res->getPourcentRemise() / 100;
$annonces[$i]['newprix'] = $res->getPrix() * $pourcent;
$fin = strtotime($res->getDateFin()->format('Y-m-d H:i:s'));
$debut = strtotime(date('Y-m-d H:i:s'));
$diff = abs($debut - $fin); // abs pour avoir la valeur absolute, ainsi éviter d'avoir une différence négative
$retour = array();
$tmp = $diff;
$retour['second'] = $tmp % 60;
$tmp = floor(($tmp - $retour['second']) / 60);
$retour['minute'] = $tmp % 60;
$tmp = floor(($tmp - $retour['minute']) / 60);
$retour['hour'] = $tmp % 24;
$tmp = floor(($tmp - $retour['hour']) / 24);
$retour['day'] = $tmp * 24;
$annonces[$i]['heures'] = $tmp * 24 + $retour['hour'];
$annonces[$i]['minutes'] = $retour['minute'];
$annonces[$i]['secondes'] = $retour['second'];
// CALCUL DE LA MOYENNE DE LANNONCE
$sum = 0;
$moy = 0;
$y = 0;
foreach ($res->getNotesAnnonces() as $res2) {
$y++;
$sum = $sum + $res2->getNote();
}
if ($y > 0) {
$moy = $sum / $y;
$moyAnnonce = (round($moy * 2) / 2);
} else {
$moyAnnonce = 0;
}
$annonces[$i]['moyAnnonce'] = $moyAnnonce;
$annonces[$i]["nbNoteAnnonce"] = $y;
// CALCUL DE LA MOYENNE DE ENSEIGNE
$sum = 0;
$moy = 0;
$y = 0;
$notesEns = $notesEnseignesRepository->findBy(array('Enseigne' => $res->getUser()));
foreach ($notesEns as $res2) {
$y++;
$sum = $sum + $res2->getNote();
}
$maxNote = $y * 5;
if ($maxNote > 0) {
$noteEnseigne = ($sum * 100) / $maxNote;
} else {
$noteEnseigne = 0;
}
$annonces[$i]['moyEnseigne'] = $noteEnseigne;
}
}
return new Response(json_encode($annonces));
}
/**
* @Route("/api/annonceDetail", name="annonceDetail")
*/
public function annonceDetail(UserRepository $userRepository, VillesRepository $villesRepository, CategoriesRepository $categoriesRepository, AnnoncesRepository $annoncesRepository, NotesEnseignesRepository $notesEnseignesRepository): Response
{
//Ajoute une mairie en favoris en fonction de l'id de la mairie et de l'UUID
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$id = $_GET['id'] ?? 10;
$annoncesReq = $annoncesRepository->findOneById($id);
$annoncesReq->setNbvues($annoncesReq->getNbVues() + 1);
$annoncesRepository->add($annoncesReq, true);
$annonces['id'] = $annoncesReq->getId();
$annonces['booste'] = $annoncesReq->isBooster();
$annonces['titre'] = $annoncesReq->getTitre();
$annonces['enseigne'] = $annoncesReq->getUser()->getRaisonSociale();
$annonces['logo'] = 'https://modixom.fr/uploads/logos/' . $annoncesReq->getUser()->getLogo();
$annonces['adresse'] = $annoncesReq->getUser()->getAdresse();
$annonces['cp'] = $annoncesReq->getVilles()->getVilleCodePostal();
$annonces['telephone'] = $annoncesReq->getUser()->getTelephone();
$annonces['ville'] = $annoncesReq->getVilles()->getVilleNom();
$annonces['images'] = 'https://modixom.fr/uploads/annonces/' . $annoncesReq->getImages()[0]->getLien();
$annonces['pourcentRemise'] = $annoncesReq->getPourcentRemise();
$annonces['prix'] = $annoncesReq->getPrix();
$annonces['description'] = $annoncesReq->getDescription();
$annonces['quantite'] = $annoncesReq->getQuantite();
$annonces['debut'] = $annoncesReq->getDateDebut()->format('d-m-Y H:i');
$annonces['fin'] = $annoncesReq->getDateFin()->format('d-m-Y H:i');
// $annonces['pourcentRemise'] = $annoncesReq->getPourcentRemise();
$pourcent = 1 - $annoncesReq->getPourcentRemise() / 100;
$annonces['newprix'] = $annoncesReq->getPrix() * $pourcent;
$fin = strtotime($annoncesReq->getDateFin()->format('Y-m-d H:i:s'));
$debut = strtotime(date('Y-m-d H:i:s'));
$diff = abs($debut - $fin); // abs pour avoir la valeur absolute, ainsi éviter d'avoir une différence négative
$retour = array();
$tmp = $diff;
$retour['second'] = $tmp % 60;
$tmp = floor(($tmp - $retour['second']) / 60);
$retour['minute'] = $tmp % 60;
$tmp = floor(($tmp - $retour['minute']) / 60);
$retour['hour'] = $tmp % 24;
$tmp = floor(($tmp - $retour['hour']) / 24);
$retour['day'] = $tmp * 24;
$annonces['heures'] = $tmp * 24 + $retour['hour'];
$annonces['minutes'] = $retour['minute'];
$annonces['secondes'] = $retour['second'];
// CALCUL DE LA MOYENNE DE LANNONCE
$sum = 0;
$moy = 0;
$y = 0;
foreach ($annoncesReq->getNotesAnnonces() as $res2) {
$y++;
$sum = $sum + $res2->getNote();
}
if ($y > 0) {
$moy = $sum / $y;
$moyAnnonce = (round($moy * 2) / 2);
} else {
$moyAnnonce = 0;
}
$annonces['moyAnnonce'] = $moyAnnonce;
// CALCUL DE LA MOYENNE DE ENSEIGNE
$sum = 0;
$moy = 0;
$y = 0;
$notesEns = $notesEnseignesRepository->findBy(array('Enseigne' => $annoncesReq->getUser()));
foreach ($notesEns as $res2) {
$y++;
$sum = $sum + $res2->getNote();
}
$maxNote = $y * 5;
if ($maxNote > 0) {
$noteEnseigne = ($sum * 100) / $maxNote;
} else {
$noteEnseigne = 0;
}
$annonces['moyEnseigne'] = $noteEnseigne;
return new Response(json_encode($annonces));
}
/**
* @Route("/api/profil", name="profilDetail")
*/
public function profilDetail(Request $request, UserRepository $userRepository, VillesRepository $villesRepository, CategoriesRepository $categoriesRepository, AnnoncesRepository $annoncesRepository, NotesEnseignesRepository $notesEnseignesRepository): Response
{
//Ajoute une mairie en favoris en fonction de l'id de la mairie et de l'UUID
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$token = $_GET['token'];
$user = $userRepository->findOneBy(array('TokenMobile' => $token));
$userArray = array();
$userArray['id'] = $user->getId();
$userArray['nom'] = $user->getNom();
$userArray['prenom'] = $user->getPrenom();
$userArray['civilite'] = $user->getCivilite();
$userArray['email'] = $user->getEmail();
$userArray['telephone'] = $user->getTelephone();
$userArray['raisonSociale'] = $user->getRaisonSociale();
$userArray['siret'] = $user->getSiret();
$userArray['tva'] = $user->getTva();
$userArray['adresse'] = $user->getAdresse();
$userArray['codePostal'] = $user->getCodePostal();
$userArray['ville'] = $user->getVilles()->getVilleNom();
$userArray['credit'] = $user->getCredits();
$userArray['type'] = $user->getType();
$userArray['logo'] = 'https://modixom.fr/uploads/logos/' . $user->getLogo();
return new Response(json_encode($userArray));
}
/**
* @Route("/api/profilUpdate", name="profilUpdate")
*/
public function profilUpdate(Request $request, UserRepository $userRepository, VillesRepository $villesRepository, CategoriesRepository $categoriesRepository, AnnoncesRepository $annoncesRepository, NotesEnseignesRepository $notesEnseignesRepository): Response
{
//Ajoute une mairie en favoris en fonction de l'id de la mairie et de l'UUID
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$res = new Response();
$token = $_GET['token'];
$data = json_decode(file_get_contents('php://input'), true);
$user = $userRepository->findOneBy(array('TokenMobile' => $token));
//Si la method est OPTIONS, on renvoie un code 200
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
$res->setStatusCode(200)
->setContent(json_encode(array(
'message' => 'OK'
)));
return $res;
}
if (!isset($data['password']) or empty($data['password'])) {
$res->setStatusCode(301)
->setContent(json_encode(array(
'message' => 'Le mot de passe est obligatoire'
)));
return $res;
} else {
$passwordCheck = password_verify($data['password'], $user->getPassword());
if (!$passwordCheck) {
$res->setStatusCode(301)
->setContent(json_encode(array(
'message' => 'Le mot de passe est incorrect'
)));
return $res;
}
}
isset($data['name']) && $user->setNom($data['name']);
isset($data['surname']) && $user->setPrenom($data['surname']);
isset($data['gender']) && $user->setCivilite($data['gender']);
isset($data['phone']) && $user->setTelephone($data['phone']);
isset($data['socialReason']) && $user->setRaisonSociale($data['socialReason']);
isset($data['siret']) && $user->setSiret($data['siret']);
isset($data['tva']) && $user->setTva($data['tva']);
isset($data['address']) && $user->setAdresse($data['address']);
isset($data['postalCode']) && $user->setCodePostal($data['postalCode']);
if (!empty($data['cityId'])) {
$v = $villesRepository->findOneById($data['cityId']);
$user->setVilles($v);
}
if (!empty($data['logo'])) {
$logoBase64 = $data['logo'];
[$imgType, $logoBase64] = explode(';', $logoBase64);
[, $logoBase64] = explode(',', $logoBase64);
[, $extension] = explode('/', $imgType);
$logo = base64_decode($logoBase64);
$logoName = uniqid('logo') . '.' . $extension;
$oldLogo = $user->getLogo();
if (!empty($oldLogo)) {
unlink(dirname(__DIR__, 2) . '/uploads/logos/' . $oldLogo);
}
file_put_contents(dirname(__DIR__, 2) . '/uploads/logos/' . $logoName, $logo);
$user->setLogo($logoName);
}
if (!empty($data['newPassword']) && !empty($data['confirmNewPassword']) && $data['newPassword'] == $data['confirmNewPassword']) {
$pass = password_hash($data['newPassword'], PASSWORD_BCRYPT);
$user->setPassword($pass);
}
$userRepository->add($user, true);
//logo
$res->setStatusCode(200)
->setContent(json_encode(array(
'message' => 'Le compte est mis à jour avec succès'
)));
return $res;
}
/**
* @Route("/api/addAnnonce", name="addAnnonce")
*/
public function addAnnonce(Request $request, UserRepository $userRepository, ImagesRepository $imagesRepository, VillesRepository $villesRepository, CategoriesRepository $categoriesRepository, AnnoncesRepository $annoncesRepository, NotesEnseignesRepository $notesEnseignesRepository): Response
{
//Ajoute une mairie en favoris en fonction de l'id de la mairie et de l'UUID
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$res = new Response();
if($_SERVER['REQUEST_METHOD'] === 'OPTIONS'){
$res->setStatusCode(200)
->setContent(json_encode(array(
'message' => 'OK'
)));
return $res;
}
$credit = 1;
$token = $_GET['token'];
$data = json_decode(file_get_contents('php://input'), true);
$user = $userRepository->findOneBy(array('TokenMobile' => $token));
$ville = $user->getVilles();
$cat = $categoriesRepository->findOneById($data['categorie']);
$annonce = new Annonces();
$annonce->setCategories($cat);
if (in_array("pro", $data['client'])) {
$annonce->setVisiblePro(1);
}
$annonce->setNbVues(0);
$dDebut = str_replace('T', ' ', $data['dateHeureDebut']);
$dFin = str_replace('T', ' ', $data['dateHeureFin']);
$annonce->setDateDebut(new Datetime($dDebut));
$annonce->setDateFin(new Datetime($dFin));
$annonce->setUser($user);
$annonce->setVilles($ville);
if (isset($data['booster']) && $data["booster"] == true) {
$annonce->setBooster(1);
$credit = $credit + 4;
}
if ($user->getCredits() >= $credit) {
$newCredit = $user->getCredits() - $credit;
//Les champs mis en commentaire n'existe pas dans la maquette de l'application mobile.
$annonce->setTitre($data['titre']);
$annonce->setPrix($data['prix']);
$annonce->setDescription($data['descriptif']);
$annonce->setPourcentRemise($data['pourcent']);
$annonce->setQuantite($data['quantite']);
$annoncesRepository->add($annonce, true);
// METTRE LES IMAGES DANS public/uploads
/*$file = $form->get('image')->getData();
if ($file != 'null') {
$path = '/';
$fileName = uniqid() . '-' . $file->getClientOriginalName();
$file->move(
$this->getParameter('annonces_directory') . $path,
$fileName
);
}*/
$image = $data['logo'];
[$imgType, $image] = explode(';', $image);
[, $image] = explode(',', $image);
[, $extension] = explode('/', $imgType);
$image = base64_decode($image);
$fileName = uniqid('image') . '.' . $extension;
file_put_contents(dirname(__DIR__, 2) . '/public/uploads/annonces/' . $fileName, $image);
$dbImage = new Images();
$dbImage->setLien($fileName);
$dbImage->setAnnonces($annonce);
$imagesRepository->add($dbImage, true);
$user->setCredits($newCredit);
$userRepository->add($user, true);
$res->setStatusCode(200)
->setContent(json_encode(array(
'message' => 'Annonce ajoutée'
)));
} else {
$res->setStatusCode(301)
->setContent(json_encode(array(
'message' => 'Pas assez de crédit pour cette annonce'
)));
}
return $res;
}
/**
* @Route("/api/updateAnnonce", name="updateAnnonce")
*/
public function updateAnnonce(Request $request, UserRepository $userRepository, ImagesRepository $imagesRepository, VillesRepository $villesRepository, CategoriesRepository $categoriesRepository, AnnoncesRepository $annoncesRepository, NotesEnseignesRepository $notesEnseignesRepository): Response
{
//Ajoute une mairie en favoris en fonction de l'id de la mairie et de l'UUID
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$credit = 1;
$ville = $villesRepository->findOneById($_GET['ville']);
$cat = $categoriesRepository->findOneById($_GET['categorie']);
$annonce = $annoncesRepository->findOneById($_GET['id']);
$annonce->setCategories($cat);
if (isset($_GET['pro'])) {
$annonce->setVisiblePro(1);
}
$annonce->setNbVues(0);
$annonce->setVilles($ville);
if (isset($_GET['booster'])) {
$annonce->setBooster(1);
$credit = $credit + 4;
}
$newCredit = $user->getCredits() - $credit;
if ($user->getCredits() >= $credit) {
$annonce->setTitre($_GET['titre']);
$annonce->setPrix($_GET['prix']);
$annonce->setDescription($_GET['description']);
$annonce->setPourcentRemise($_GET['pourcent']);
$annonce->setQuantite($_GET['quantite']);
$annoncesRepository->add($annonce, true);
// METTRE LES IMAGES DANS public/uploads
// POUR AJOUT DE L'IMAGE
/*$file = $form->get('image')->getData();
if ($file != 'null') {
$path = '/';
$fileName = uniqid() . '-' . $file->getClientOriginalName();
$file->move(
$this->getParameter('annonces_directory') . $path,
$fileName
);
}*/
/*$image = new Images();
$image->setLien($fileName);
$image->setAnnonces($annonce);
$imagesRepository->add($image, true);*/
$user->setCredits($newCredit);
$userRepository->add($user, true);
$res->setStatusCode(200)
->setContent(json_encode(array(
'message' => 'Annonce modifiée'
)));
} else {
$res->setStatusCode(301)
->setContent(json_encode(array(
'message' => 'Pas assez de crédit pour modifier cette annonce'
)));
}
}
/**
* @Route("/api/deleteAnnonce", name="deleteAnnonce")
*/
public function deleteAnnonce(Request $request, NotesAnnoncesRepository $notesAnnoncesRepository, UserRepository $userRepository, ImagesRepository $imagesRepository, VillesRepository $villesRepository, CategoriesRepository $categoriesRepository, AnnoncesRepository $annoncesRepository, NotesEnseignesRepository $notesEnseignesRepository): Response
{
//Ajoute une mairie en favoris en fonction de l'id de la mairie et de l'UUID
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$annonce = $annoncesRepository->findOneById($_GET['id']);
$notes = $notesAnnoncesRepository->findBy(array('Annonces' => $annonce));
foreach ($notes as $res) {
$notesAnnoncesRepository->remove($res, true);
}
$images = $imagesRepository->findBy(array('Annonces' => $annonce));
foreach ($images as $res) {
$imagesRepository->remove($res, true);
}
$annoncesRepository->remove($annonce, true);
$res->setStatusCode(200)
->setContent(json_encode(array(
'message' => 'Annonce supprimée'
)));
return new Response(json_encode($res));
}
/**
* @Route("/api/annoncesProfil", name="annoncesProfil")
*/
public function annoncesProfil(Request $request, NotesAnnoncesRepository $notesAnnoncesRepository, UserRepository $userRepository, ImagesRepository $imagesRepository, VillesRepository $villesRepository, CategoriesRepository $categoriesRepository, AnnoncesRepository $annoncesRepository, NotesEnseignesRepository $notesEnseignesRepository): Response
{
//Ajoute une mairie en favoris en fonction de l'id de la mairie et de l'UUID
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$token = $_GET['token'] ?? 'test';
$user = $userRepository->findOneBy(array('TokenMobile' => $token));
$annoncesReq = $annoncesRepository->findBy(array('User' => $user));
$i = -1;
$annonces = array();
foreach ($annoncesReq as $res) {
$i++;
$annonces[$i]['id'] = $res->getId();
$annonces[$i]['boost'] = $res->isBooster();
$annonces[$i]['titre'] = $res->getTitre();
$annonces[$i]['enseigne'] = $res->getUser()->getRaisonSociale();
$annonces[$i]['logo'] = 'https://modixom.fr/uploads/logos/' . $res->getUser()->getLogo();
$annonces[$i]['images'] = sizeof($res->getImages()) > 0 ? 'https://modixom.fr/uploads/annonces/' . $res->getImages()[0]->getLien() : 'https://modixom.fr/uploads/annonces/default.jpg';
$annonces[$i]['pourcentRemise'] = $res->getPourcentRemise();
$annonces[$i]['prix'] = $res->getPrix();
$annonces[$i]['description'] = $res->getDescription();
$annonces[$i]["quantity"] = $res->getQuantite();
$pourcent = 1 - $res->getPourcentRemise() / 100;
$annonces[$i]['newprix'] = $res->getPrix() * $pourcent;
$fin = strtotime($res->getDateFin()->format('Y-m-d H:i:s'));
$debut = strtotime(date('Y-m-d H:i:s'));
$diff = abs($debut - $fin); // abs pour avoir la valeur absolute, ainsi éviter d'avoir une différence négative
$retour = array();
$tmp = $diff;
$retour['second'] = $tmp % 60;
$tmp = floor(($tmp - $retour['second']) / 60);
$retour['minute'] = $tmp % 60;
$tmp = floor(($tmp - $retour['minute']) / 60);
$retour['hour'] = $tmp % 24;
$tmp = floor(($tmp - $retour['hour']) / 24);
$retour['day'] = $tmp * 24;
$annonces[$i]['heures'] = $tmp * 24 + $retour['hour'];
$annonces[$i]['minutes'] = $retour['minute'];
$annonces[$i]['secondes'] = $retour['second'];
// CALCUL DE LA MOYENNE DE LANNONCE
$sum = 0;
$moy = 0;
$y = 0;
foreach ($res->getNotesAnnonces() as $res2) {
$y++;
$sum = $sum + $res2->getNote();
}
if ($y > 0) {
$moy = $sum / $y;
$moyAnnonce = (round($moy * 2) / 2);
} else {
$moyAnnonce = 0;
}
$annonces[$i]['moyAnnonce'] = $moyAnnonce;
// CALCUL DE LA MOYENNE DE ENSEIGNE
$sum = 0;
$moy = 0;
$y = 0;
$notesEns = $notesEnseignesRepository->findBy(array('Enseigne' => $res->getUser()));
foreach ($notesEns as $res2) {
$y++;
$sum = $sum + $res2->getNote();
}
$maxNote = $y * 5;
if ($maxNote > 0) {
$noteEnseigne = ($sum * 100) / $maxNote;
} else {
$noteEnseigne = 0;
}
$annonces[$i]['moyEnseigne'] = $noteEnseigne;
if (strtotime($res->getDateDebut()->format('Y-m-d H:i:s')) <= time()
&& strtotime($res->getDateFin()->format('Y-m-d H:i:s')) > time()) {
$annonces[$i]['statut'] = 'active';
} else {
$annonces[$i]['statut'] = 'expire';
}
}
return new Response(json_encode($annonces));
}
/**
* @Route("/api/noteProduit", name="noteProduit")
*/
public function noteProduit(Request $request, NotesAnnoncesRepository $notesAnnoncesRepository, UserRepository $userRepository, ImagesRepository $imagesRepository, VillesRepository $villesRepository, CategoriesRepository $categoriesRepository, AnnoncesRepository $annoncesRepository, NotesEnseignesRepository $notesEnseignesRepository): Response
{
//Ajoute une mairie en favoris en fonction de l'id de la mairie et de l'UUID
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
if($_SERVER['REQUEST_METHOD'] === 'OPTIONS'){
$res = new Response();
$res->setStatusCode(200)
->setContent(json_encode(array(
'message' => 'OK'
)));
return $res;
}
$token = $_GET['token'];
$data = json_decode(file_get_contents('php://input'), true);
$user = $userRepository->findOneBy(array('TokenMobile' => $token));
$produit = $data['produit'];
$note = $data['note'];
$produit = $annoncesRepository->findOneById($produit);
$noteAnnonce = $notesAnnoncesRepository->findOneBy(['User'=>$user, 'Annonces'=>$produit]);
if(empty($noteAnnonce))
{
$prod = new NotesAnnonces();
//$prod = $notesAnnoncesRepository->findOneById($produit);
$prod->setAnnonces($produit);
$prod->setNote($note);
$prod->setDate(new Datetime());
$prod->setUser($user);
$notesAnnoncesRepository->add($prod, true);
return new Response('ok');
}
else
{
return new Response('produit déjà noté');
}
}
/**
* @Route("/api/addAlertes", name="addAlertesApi")
*/
public function addAlertes(Request $request, AnnoncesRepository $annoncesRepository, VillesRepository $villesRepository, CategoriesRepository $categoriesRepository, UserRepository $userRepository): Response
{
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$res = new Response();
if($_SERVER['REQUEST_METHOD'] === 'OPTIONS'){
$res->setStatusCode(200)
->setContent(json_encode(array(
'message' => 'OK'
)));
return $res;
}
$entityManager = $this->getDoctrine()->getManager();
$data = json_decode(file_get_contents('php://input'), true);
$villeId = $data['ville'];
$rayon = $data['rayon'];
$categorieId = $data['category'];
$mail = $data['mail'];
// Récupérer les instances des entités liées (Villes, Categories, User)
$ville = $villesRepository->find($villeId);
$user = $userRepository->findOneBy(['email' => $mail]);
foreach($categorieId as $i_value) {
$categorie = $categoriesRepository->find($i_value);
// Créer une nouvelle alerte avec les données du formulaire
$alerte = new Alertes();
$alerte->setVilles($ville);
$alerte->setRayon($rayon);
$alerte->setCategories($categorie);
$alerte->setUser($user);
// Enregistrer l'alerte dans la base de données
$entityManager->persist($alerte);
$entityManager->flush();
}
// Retourner une réponse indiquant que l'alerte a été ajoutée avec succès
return new Response("Alerte ajoutée avec succès", Response::HTTP_CREATED);
}
/**
* @Route("/api/getAlertes", name="getAlertes")
*/
public function getAlertes(Request $request, AlertesRepository $alerteRepository, UserRepository $userRepository): Response {
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$res = new Response();
if($_SERVER['REQUEST_METHOD'] === 'OPTIONS'){
$res->setStatusCode(200)
->setContent(json_encode(array(
'message' => 'OK'
)));
return $res;
}
$token = $_GET['token'] ?? null;
$user = $userRepository->findOneBy(array('TokenMobile' => $token));
$rawAlertes = $alerteRepository->findBy(array("User" => $user));
$hydratedAlertes = [];
foreach ($rawAlertes as $alerte) {
$alerteArray = [];
$alerteArray["id"] = $alerte->getId();
$alerteArray["ville"] = $alerte->getVilles()->getVilleNomReel();
$alerteArray["rayon"] = $alerte->getRayon();
$alerteArray["category"] = $alerte->getCategories()->getLibelle();
$hydratedAlertes[] = $alerteArray;
}
$res->setStatusCode(200)
->setContent(json_encode($hydratedAlertes));
return $res;
}
/**
* @Route("/api/updateFavoris", name="updateFavoris")
*/
public function updateFavoris(Request $request, AnnoncesRepository $annoncesRepository, FavorisRepository $favorisRepository, UserRepository $userRepository): Response {
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$res = new Response();
if($_SERVER['REQUEST_METHOD'] === 'OPTIONS'){
$res->setStatusCode(200)
->setContent(json_encode(array(
'message' => 'OK'
)));
return $res;
}
$data = json_decode(file_get_contents("php://input"), true);
$favorisId = $data["favorisId"] ?? null;
if ($favorisId) {
$favoris = $favorisRepository->findOneById($favorisId);
$favorisRepository->remove($favoris, true);
return new Response("favoris retiré", Response::HTTP_CREATED);
}
$user = $userRepository->findOneById($data["userId"]);
$annonce = $annoncesRepository->findOneById($data["annonceId"]);
$favoris = new Favoris();
$favoris->setAnnonces($annonce);
$favoris->setUser($user);
$favoris->setDate(new Datetime());
$favorisRepository->add($favoris, true);
return new Response("favoris ajouté", Response::HTTP_CREATED);
}
}