<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Datetime;
use Psr\Log\LoggerInterface;
use App\Entity\Notification;
use App\Entity\ProposedArticle;
use App\Repository\ArticleRepository;
use App\Repository\ProposedArticleRepository;
use App\Repository\NotificationRepository;
use Symfony\Component\HttpFoundation\Request;
use App\Entity\Article;
use App\Repository\UserPackageRepository;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Doctrine\ORM\EntityManagerInterface;
class HomeController extends AbstractController
{
private $logger;
private $httpClient;
public function __construct(HttpClientInterface $httpClient, LoggerInterface $logger)
{
$this->logger = $logger;
$this->httpClient = $httpClient;
}
#[Route('/home', name: 'app_home')]
public function index(UserPackageRepository $userPackageRepository, ProposedArticleRepository $proposedArticleRepository, ArticleRepository $articleRepository, NotificationRepository $notificationRepository, Request $request): Response
{
// Je récupères les articles du client
$packages = $userPackageRepository->findByUser($this->getUser());
$notifications = $notificationRepository->findBy(['user' => $this->getUser()], ['dateCreated' => 'DESC']);
$proposedArticles = $proposedArticleRepository->findBy(['user' => $this->getUser()], ['dateCreated' => 'DESC']);
$articles = $articleRepository->findBy(['user' => $this->getUser(), 'deleted' => false], ['orderDate' => 'DESC']);
$articlesDelivered = $articleRepository->findBy(['user' => $this->getUser(), 'deleted' => false, 'status' => 'Livré'], ['orderDate' => 'DESC']);
$articlesOnline = $articleRepository->findBy(['user' => $this->getUser(), 'deleted' => false, 'status' => 'En ligne'], ['orderDate' => 'DESC']);
//dump($articles);
$seoPackages = null;
foreach($packages as $userPackage) {
$articleType = $userPackage->getPackage()->getArticleType()->getId();
//dump($articleType);
if($articleType === 6 && $userPackage->getSolde() > 0) {
$seoPackages[] = $userPackage;
}
}
if ($this->isGranted('ROLE_ADMIN')) {
$articles = $articleRepository->findBy(['deleted' => false], ['orderDate' => 'DESC']);
/*$unreads = $articleRepository->findBy(['user' => $this->getUser(), 'readed' => false, 'deleted' => false]);
$numberUnRead = null;
//dump($unreads);
foreach($unreads as $unread) {
if($unread->getContent() !== null) {
$numberUnRead++;
}
}*/
}
return $this->render('home/index.html.twig', [
'articles' => $articles,
'numberArticle' => count($articles),
'numberArticleDelivered' => count($articlesDelivered),
'numberArticleOnline' => count($articlesOnline),
'notifications' => $notifications,
'titles' => $proposedArticles,
'seoPackages' => $seoPackages,
]);
}
#[Route('/', name: 'app_day')]
public function error(): Response
{
return $this->redirectToRoute('app_home');
}
// La commande des exemples de titres
#[Route('/ask/titles', name: 'ask_title')]
public function orderTitles(Request $request, EntityManagerInterface $entityManager): Response
{
$user = $this->getUser();
if ($request->get('keyWord') != null) {
$keyWord = $request->get('keyWord');
$keyIdeas = $request->get('keyIdeas');
try {
$orderDate = new Datetime('now');
$jsonData = [
'authentication_key' => $_ENV['AUTHENTICATION_KEY'],
'idcustomer' => $this->getUser()->getId(),
'customerkey' => $this->getUser()->getCustomerKey(),
'keyword' => $keyWord,
'keyideas' => $keyIdeas,
];
//dump($jsonData);
try {
// J'envoie les données de demande d'article au backoffice
$response = $this->httpClient->request('POST', 'https://www.groupe-saven.fr/api.cpe/gettitles.php', [
'json' => $jsonData
]);
//dump($response);
$statusCode = $response->getStatusCode();
$content = $response->getContent(false);
$data = json_decode($content, true);
//dump($statusCode);
//dump($data);
// Je gère les erreurs de transmission avec le back
if ($statusCode !== 200 && $statusCode !== 201) {
$this->addFlash('danger', 'Problème de transmission de votre commande');
// Lancer une exception avec le contenu de la réponse si le code de statut n'est pas 200
throw new \Exception("Erreur HTTP $statusCode: " . $content);
}
if ($data['titles']) {
try {
//dump($data['titles']);
// Je cree la notification pour l'historique d'activité
$notification = new Notification();
$creationDate = new Datetime('now');
$notification->setDateCreated($creationDate);
$notification->setTitle('Demande de propositions de titres');
$notification->setUser($user);
$notification->setDetail($keyWord);
$notification2 = new Notification();
$creationDate2 = new Datetime('now');
$notification2->setDateCreated($creationDate2);
$notification2->setTitle('Livraisons des propositions de titres');
$notification2->setUser($user);
$notification2->setDetail($keyWord);
$entityManager->persist($notification2);
$entityManager->persist($notification);
$entityManager->flush();
foreach ($data['titles'] as $title) {
$proposedArticle = new ProposedArticle();
$creationDate = new Datetime('now');
$proposedArticle->setDateCreated($creationDate);
$proposedArticle->setTitle($title);
$proposedArticle->setUser($user);
$entityManager->persist($proposedArticle);
$entityManager->flush();
}
$this->addFlash('success', 'Vos titres vous ont été livrés');
} catch (Exception $e) {
$this->logger->error('Erreur : '. $e->getMessage());
}
}
$this->addFlash('success', 'Votre commande a été passée (Vous la recevrez dans environ 10 minutes)');
return $this->redirectToRoute('app_home');
} catch (Exception $e) {
//dump($response);
$this->logger->error("danger" . $e->getMessage());
}
} catch (\Exception $e) {
// Vérifiez si l'exception implémente HttpExceptionInterface
if ($e instanceof HttpExceptionInterface) {
// Cas d'erreur côté client, comme une exception `BadRequestHttpException`
$statusCode = $e->getStatusCode();
$message = $e->getMessage();
} else {
// Cas d'erreur côté serveur
$statusCode = Response::HTTP_INTERNAL_SERVER_ERROR;
$message = 'Une erreur interne du serveur s\'est produite.';
}
// Gestion des erreurs
// Log l'erreur
$this->logger->error(sprintf('Erreur %d : %s', $statusCode, $e->getMessage()));
$this->addFlash('danger', 'Erreur : '. $message);
return $this->redirectToRoute('app_home');
}
}
return $this->redirectToRoute('app_home');
}
//
}