<?php
namespace App\Controller;
use App\Entity\Prestation;
use App\Entity\Recette;
use App\Entity\Paiement;
use App\Repository\CategorieRepository;
use App\Repository\PrestationRepository;
use App\Repository\RecetteRepository;
use App\Repository\TypePaiementRepository;
use App\Service\RecetteService;
use App\Service\TelegramService;
use Doctrine\ORM\EntityManagerInterface;
use IntlDateFormatter;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class RecetteController extends AbstractController
{
public function __construct(
private readonly EntityManagerInterface $entityManager,
private readonly CategorieRepository $categorieRepository,
private readonly PrestationRepository $prestationRepository,
private readonly RecetteRepository $recetteRepository,
private readonly TypePaiementRepository $typePaiementRepository,
private readonly RecetteService $recetteService,
private readonly LoggerInterface $logger
) {}
/**
* @throws \Exception
*/
#[Route('/admin/recette/', name: 'app_recette', methods: ['GET'])]
public function indexByDate(Request $request): Response
{
if (!$this->isGranted('ROLE_ADMIN')) {
return new JsonResponse(['error' => 'Accès non autorisé'], Response::HTTP_FORBIDDEN);
}
$dateParam = $request->query->get('date');
$date = $dateParam ? \DateTime::createFromFormat('d/m/Y', $dateParam) : new \DateTime();
if (!$date) {
throw new \Exception("Format de date invalide.");
}
$recettes = $this->recetteRepository->findByDate($date);
$total = $this->recetteService->calculateTotals($date);
// Récupérer uniquement les catégories non supprimées
$categories = $this->categorieRepository->findBy(
['deleted' => false],
['nom' => 'ASC']
);
return $this->render('admin/recette.html.twig', [
'categories' => $categories,
'recettes' => $recettes,
'totalJour' => $total['totalJour'],
'totalAcompte' => $total['totalAcompte'],
'totalEspece' => $total['totalEspece'],
'totalCarteBancaire' => $total['totalCarteBancaire'],
]);
}
#[Route('/admin/recette/ajax', name: 'app_recette_ajax', methods: ['POST'])]
public function handleAjax(Request $request): Response
{
if (!$this->isGranted('ROLE_ADMIN')) {
return new JsonResponse(['error' => 'Accès non autorisé'], Response::HTTP_FORBIDDEN);
}
$data = json_decode($request->getContent(), true);
$processedData = $this->recetteService->processRecetteData($data);
return new JsonResponse($processedData);
}
#[Route('/admin/delete/recette/{id}', name: 'delete_recette', methods: ['DELETE'])]
public function deleteRecette(int $id): JsonResponse
{
if (!$this->isGranted('ROLE_ADMIN')) {
return new JsonResponse(['error' => 'Accès non autorisé'], Response::HTTP_FORBIDDEN);
}
$recette = $this->recetteRepository->find($id);
if (!$recette) {
return new JsonResponse(['error' => 'Recette non trouvée'], 404);
}
$date = $recette->getDate();
$this->entityManager->remove($recette);
$this->entityManager->flush();
$totals = $this->recetteService->calculateTotals($date);
return new JsonResponse(['status' => 'success', 'totals' => $totals]);
}
#[Route('/admin/prestations/{categorieId}', name: 'get_prestations_by_categorie', methods: ['GET'])]
public function getPrestationsByCategorie(
int $categorieId,
PrestationRepository $prestationRepository,
CategorieRepository $categorieRepository,
EntityManagerInterface $entityManager
): JsonResponse
{
if (!$this->isGranted('ROLE_ADMIN')) {
return new JsonResponse(['error' => 'Accès non autorisé'], Response::HTTP_FORBIDDEN);
}
// Vérifier si la catégorie existe et n'est pas supprimée
$categorie = $categorieRepository->findOneBy(['id' => $categorieId, 'deleted' => false]);
if (!$categorie) {
return new JsonResponse(['error' => 'Catégorie non trouvée ou supprimée'], Response::HTTP_NOT_FOUND);
}
// Initialiser toutes les prestations de la catégorie
$entityManager->initializeObject($categorie->getPrestations());
// Récupérer les prestations actives de la catégorie
$prestations = $categorie->getPrestations()->filter(function($prestation) {
return !$prestation->isDeleted();
})->toArray();
// Trier les prestations par prix
usort($prestations, function($a, $b) {
return $a->getPrix() <=> $b->getPrix();
});
$data = [];
foreach ($prestations as $prestation) {
$data[] = [
'id' => $prestation->getId(),
'nom' => $prestation->getNom(),
'prix' => $prestation->getPrix(),
];
}
return new JsonResponse($data);
}
private const CHAT_ID_A = '936988470';
private const CHAT_ID_J = '1078874149';
/**
* @throws \Exception
*/
#[Route('/admin/recette/send', name: 'send_recette', methods: ['POST'])]
public function sendTelegramNotification(Request $request): JsonResponse
{
if (!$this->isGranted('ROLE_ADMIN')) {
return new JsonResponse(['error' => 'Accès non autorisé'], Response::HTTP_FORBIDDEN);
}
$telegramService = new TelegramService($_ENV['TELEGRAM_BOT_TOKEN']);
try {
$date = json_decode($request->getContent(), true)['date'];
$date = $date ? \DateTime::createFromFormat('d/m/Y', $date) : new \DateTime();
if (!$date) {
throw new \Exception("Format de date invalide.");
}
$recettes = $this->recetteRepository->findByDate($date);
$totals = $this->recetteService->calculateTotals($date);
$prestations = [];
$nombreClientes = count($recettes);
$prestationCounts = [];
foreach ($recettes as $recette) {
$prestationDetails = [];
foreach ($recette->getPrestations() as $prestation) {
$prestationDetails[] = $prestation->getNom();
$prestationCounts[$prestation->getNom()] = ($prestationCounts[$prestation->getNom()] ?? 0) + 1;
}
$prestations[] = "- {$recette->getNomClient()} :\n " . implode("\n ", $prestationDetails);
}
$prestationPopulaire = !empty($prestationCounts) ? array_search(max($prestationCounts), $prestationCounts) : 'Aucune';
$formatter = new IntlDateFormatter('fr_FR', IntlDateFormatter::FULL, IntlDateFormatter::NONE);
$dateFormatee = $formatter->format($date);
$dateFormatee = ucwords(mb_strtolower($dateFormatee, 'UTF-8'));
$message = "🌟 Récapitulatif des recettes du jour 🌟\n";
$message .= "📅 Date : " . $dateFormatee . "\n\n";
$message .= "💇♀️ Prestations réalisées :\n" . (!empty($prestations) ? implode("\n", $prestations) : "Aucune prestation") . "\n\n";
$message .= "💰 Totaux par mode de paiement :\n";
$message .= "💵 Espèces : {$totals['totalEspece']} €\n";
$message .= "💳 Carte Bancaire : {$totals['totalCarteBancaire']} €\n";
$message .= "🖥️ Planity : {$totals['totalAcompte']} €\n\n";
$message .= "🎉 Total du jour : {$totals['totalJour']} €\n\n";
$message .= "👩💼 Nombre de clientes : {$nombreClientes}\n\n";
$message .= "🔝 Prestation la plus demandée : {$prestationPopulaire}\n\n";
$telegramService->sendMessage(self::CHAT_ID_A, $message);
$telegramService->sendMessage(self::CHAT_ID_J, $message);
return new JsonResponse(['status' => 'Message envoyé']);
} catch (\Exception $e) {
$this->logger->error('Erreur lors de l\'envoi du message Telegram', ['error' => $e->getMessage()]);
return new JsonResponse(['error' => $e->getMessage()], 500);
}
}
}