<?php
namespace App\Controller;
use App\Entity\Products;
use App\Repository\ContactRepository;
use App\Repository\TarifsRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\String\Slugger\SluggerInterface;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
#[Route('/produits', name: 'products_')]
class ProductsController extends AbstractController
{
#[Route('/', name: 'index')]
public function index(): Response
{
return $this->render('products/index.html.twig');
}
#[Route('/{slug}', name: 'details')]
public function details(Products $product, ContactRepository $contactRepository, TarifsRepository $tarifsRepository): Response
{
$user = $this->getUser();
// Sécurité : si personne n'est connecté
//if (!$user) {
// return $this->redirectToRoute('app_login');
//}
// On récupère les contacts ayant le même email
$contacts = [];
if ($user) {
$contacts = $contactRepository->findBy(['email' => $user->getEmail()]);
}
// Récupère tous les tarifs (ou filtre selon ton besoin)
$tarifs = $tarifsRepository->findBy(['referenceArticle' => $product->getSlug()]);
// On check si c'est un accessoire et si c'est la cas on recherche les produits liés
$productsSources = $product->getAccessoriesSources();
return $this->render('products/details.html.twig', [
'product' => $product,
'user' => $user,
'contacts' => $contacts,
'tarifs' => $tarifs,
'productsSources' => $productsSources,
]);
}
#[Route('/image/{slug}', name: 'mainImage')]
public function mainImage(Products $product, string $slug): Response
{
if ($product) {
$mainImage = $product->getImages()->get(0);
$urlImage = $mainImage ? $mainImage->getName() : null;
if ($urlImage) {
$filePath = __DIR__ . '/../../public/assets/uploads/products/' . $urlImage;
// Vérifiez si le fichier existe
if (file_exists($filePath)) {
// Obtenez le type MIME du fichier
$mimeType = mime_content_type($filePath);
// Vérifiez si le fichier est une image
if (str_starts_with($mimeType, 'image/')) {
// Obtenez l'extension à partir du type MIME
$extension = match ($mimeType) {
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/gif' => 'gif',
'image/webp' => 'webp',
default => null,
};
if ($extension) {
// Chargez l'image avec GD
$image = match ($extension) {
'jpg' => imagecreatefromjpeg($filePath),
'png' => imagecreatefrompng($filePath),
'gif' => imagecreatefromgif($filePath),
'webp' => imagecreatefromwebp($filePath),
default => null,
};
if ($image) {
// Vérifiez les dimensions
$width = imagesx($image);
$height = imagesy($image);
// Taille cible minimale
$targetWidth = 1200;
$targetHeight = 1200;
// Calculer les nouvelles dimensions en respectant les proportions
$scaleFactor = max($targetWidth / $width, $targetHeight / $height);
$newWidth = (int) ceil($width * $scaleFactor);
$newHeight = (int) ceil($height * $scaleFactor);
if ($newWidth > $width || $newHeight > $height) {
// Redimensionner l'image en respectant les proportions
$resizedImage = imagecreatetruecolor($newWidth, $newHeight);
// Conserver la transparence pour les PNG et GIF
if ($extension === 'png' || $extension === 'gif') {
imagecolortransparent($resizedImage, imagecolorallocatealpha($resizedImage, 0, 0, 0, 127));
imagealphablending($resizedImage, false);
imagesavealpha($resizedImage, true);
}
// Redimensionner avec GD
imagecopyresampled(
$resizedImage,
$image,
0, 0, 0, 0,
$newWidth,
$newHeight,
$width,
$height
);
// Remplacez l'image originale par l'image redimensionnée
$image = $resizedImage;
}
// Si l'image est en WebP, convertissez-la en JPEG
$isWebP = $extension === 'webp';
if ($isWebP) {
$extension = 'jpg';
$mimeType = 'image/jpeg';
}
// Enregistrez l'image temporairement
$tempFilePath = sys_get_temp_dir() . '/' . uniqid($slug, true) . '.' . $extension;
match ($extension) {
'jpg' => imagejpeg($image, $tempFilePath, 100), // Qualité maximale
'png' => imagepng($image, $tempFilePath),
'gif' => imagegif($image, $tempFilePath),
};
// Libérez la mémoire
imagedestroy($image);
// Générez le nom de fichier avec le slug et l'extension
$fileName = $slug . '.' . $extension;
$response = new BinaryFileResponse($tempFilePath);
$response->headers->set('Content-Type', $mimeType);
$response->setContentDisposition(
ResponseHeaderBag::DISPOSITION_INLINE, // ou ATTACHMENT pour forcer le téléchargement
$fileName
);
return $response;
} else {
return new Response('Impossible de charger l\'image.', Response::HTTP_INTERNAL_SERVER_ERROR);
}
} else {
return new Response('Type d\'image non supporté.', Response::HTTP_UNSUPPORTED_MEDIA_TYPE);
}
} else {
return new Response('Le fichier n\'est pas une image.', Response::HTTP_UNSUPPORTED_MEDIA_TYPE);
}
}
}
}
return new Response('Image non trouvée', Response::HTTP_NOT_FOUND);
}
}