<?php
namespace App\Controller\Front;
use App\Entity\Category;
use App\Entity\File;
use App\Entity\Produit;
use App\Entity\ProduitDeclinationValue;
use Doctrine\ORM\EntityManagerInterface;
use phpDocumentor\Reflection\Types\Array_;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Doctrine\ORM\Tools\Pagination\Paginator;
class ProductController extends AbstractController
{
use ImageTrait;
/** @var EntityManagerInterface */
private $em;
public function __construct(EntityManagerInterface $manager)
{
$this->em = $manager;
}
/**
* @Route("api/v0/product/{id}", name="product")
*/
public function index(Produit $produit, Request $request): Response
{
return $this->json( [
'product' => $produit
]);
}
/**
* @Route("/product/{id}/{name?}", name="product_new", options={"expose"=true}, methods={"GET"})
*/
public function indexNew(Request $request,$id): Response
{
//$categories = $this->em->getRepository(Category::class)->findAll();
// Recupérer la catégorie du produit
$produit = $this->em->getRepository(Produit::class)->find($id);
if (!$produit) {
throw $this->createNotFoundException('Product Not Found');
}
$relatedProduct = $this->em->getRepository(Produit::class)->findBy(['categories'=>$produit->getCategories(),'showInWebSite'=>1,'deletedAt' => null],null,4);
$categorie = $this->em->getRepository(Category::class)->find($produit->getCategories()->getId());
foreach ($relatedProduct as $product) {
$product->image = $this->getDefaultImage($product);
};
return $this->render('front/product/index.html.twig', [
'id' => $id,
'categorie' => $categorie,
'product' => $produit,
'relatedProduct' =>$relatedProduct,
'productName' => $produit->getName(),
'productImg' => $this->getDefaultImage($produit, null)
]);
}
/**
* @Route("/product-dec/{id}/{idDec}/{name?}", name="product_new_dec", options={"expose"=true}, methods={"GET"})
*/
public function indexNewDec(Request $request,$id,$idDec): Response
{
//$categories = $this->em->getRepository(Category::class)->findAll();
// Recupérer la catégorie du produit
$produit = $this->em->getRepository(Produit::class)->find($id);
$relatedProduct = $this->em->getRepository(Produit::class)->findBy(['categories'=>$produit->getCategories(),'showInWebSite'=>1,'deletedAt' => null],null,4);
$categorie = $this->em->getRepository(Category::class)->find($produit->getCategories()->getId());
foreach ($relatedProduct as $product) {
$product->image = $this->getDefaultImage($product);
};
return $this->render('front/product/indexDec.html.twig', [
'id' => $id,
'idDec' => $idDec,
'categorie' => $categorie,
'product' => $produit,
'relatedProduct' =>$relatedProduct,
'productName' => $produit->getName(),
'productImg' => $this->getDefaultImage($produit, null)
]);
}
/**
* @Route("/productByDec/{id}", name="product_by_dec", options={"expose"=true}, methods={"GET"})
*/
public function productByDec(Request $request, $id): Response
{
// Recupérer le produit par id declinaison
$declinaison = $this->em->getRepository(ProduitDeclinationValue::class)->find($id);
return $this->redirectToRoute('product_new', ['id' => $declinaison->getProduit()->getId()]);
}
/**
* @Route("/api/product-get", name="product_get", options={"expose"=true}, methods={"GET"})
*/
public function getAPI(Request $request): Response
{
$id = $request->query->get('id');
$product = $this->em->getRepository(Produit::class)->findOneById($id);
$response = [
'res' => 'OK',
'data' => $product,
'message' => 'Produit récupéré avec succès.',
];
return new jsonResponse($response);
}
/**
* @Route("api/v0/productByCategory/{id}", name="productByCategory")
*/
public function productByCategory(Category $category, Request $request): Response
{
$products = $this->em->getRepository(Produit::class)->findBy(array('categories' => $category), [], 20);
return $this->json([
'products' => $products
]);
}
/**
* @Route("api/v0/productByDeclinaison", options={"expose"=true},name="productDeclinaison")
*/
public function productDeclinaison(Request $request): Response
{
$size=$request->request->get('size');
$product=$request->request->get('product');
$produitDeclinaisonValue = $this->em->getRepository(ProduitDeclinationValue::class)->findDeclinationValueWithDeclination($size,$product);
return $this->json([
'produitDeclinaisonValue' => $produitDeclinaisonValue
]);
}
/**
* @Route("api/v0/productImage", options={"expose"=true},name="productImage")
*/
public function productImage(Request $request): Response
{
$imageId = $request->request->get('image');
$image = $this->em->getRepository(File::class)->find($imageId);
return $this->json([
'image' => $image
]);
}
private function comparator($object1, $object2)
{
return $object2->getId() > $object1->getId();
}
/**
* @Route("/api/product/{idProduit}/declinaison-value", name="product-declinaison-value", options={"expose"=true}, methods={"GET"})
*/
public function getdeclinaisonValuePerProduct($idProduit, Request $request): Response
{
$product = $this->em->getRepository(Produit::class)->findOneById($idProduit);
$dec = [];
$output = [];
foreach ($product->getProduitDeclinationValues() as $entity){
foreach ($entity->getGroupDeclinationValues() as $group) {
$key = strtolower($group->getDeclination()->getName());
$value = ($key == "couleur") ? $group->getValue() : $group->getValue()->getName();
$data[$key] = $value;
$dec[$key][] = $value;
}
$quantity = 0;
foreach ($entity->getStocks() as $stock)
$quantity = $quantity + ($stock->getQtStock() - $stock->getQtReserved());
$priceTtc = $entity->getProduit()->getPriceTtc();
$in_promo=false;
if( $entity->getProduit()->getPromotion()) {
$promotion = $entity->getProduit()->getPromotion();
$date = new \DateTime('now');
if( $promotion->getStartAt() <= $date && $promotion->getEndAt() >= $date){
$priceTtc =($promotion->getDiscountType() == 'percent')?
$entity->getProduit()->getPriceTtc() - ((($entity->getProduit()->getPriceTtc() / 100) * $promotion->getDiscountValue()))
: $entity->getProduit()->getPriceTtc() - $promotion->getDiscountValue();
$in_promo=true;
}
}
$output[] = array_merge([
'id' => $entity->getId(),
"qty" => $quantity,
"price_ttc" => number_format($priceTtc, 3),
"in_promo" => $in_promo,
'price_ht' => number_format($entity->getPriceHt(), 3),
"picture" => $this->getDefaultImage(null, $entity),
"ref" => $entity->getReference(),
"name" => $entity->getName()
], $data);
}
// Récuérer les tags reliés
$Tags = $product->getTags();
$produitsTags = [];
// Récupérer les produit reliés au tag
foreach ($Tags as $tag) {
foreach ($tag->getProduits() as $prod) {
/*if(sizeof($produitsTags) == 4 ){
break;
}*/
if( $prod->getId() != $product->getId()) {
array_push($produitsTags, $prod);
}
}
/*if(sizeof($produitsTags) == 4 ){
break;
}*/
}
// Trier par id décroissant et récupérer les 4 dernier
usort($produitsTags, array($this, "comparator"));
$tags = [];
foreach ($produitsTags as $prod) {
if( sizeof($tags) == 4) break;
$prod->image = $this->getDefaultImage( $prod);
array_push($tags, $prod);
}
foreach ($dec as $k=>$v)
$dec[$k] = array_values(array_unique($dec[$k], SORT_REGULAR));
$response = [
'res' => 'OK',
'data' => ["produit" => $product, "declinaisons_produit" => $output, "declinaisons" => $dec, 'tags' => $tags],
'message' => 'Produit Dec récupéré avec succès.',
];
return new jsonResponse($response);
}
/**
* @Route("/api/product/{idProduit}/{idDec}/declinaison-value-new", name="product-declinaison-value_new", options={"expose"=true}, methods={"GET"})
*/
public function getdeclinaisonValuePerProductNew($idProduit,$idDec, Request $request): Response
{
$product = $this->em->getRepository(Produit::class)->findOneById($idProduit);
$dec = [];
$output = [];
foreach ($product->getProduitDeclinationValues() as $entity){
foreach ($entity->getGroupDeclinationValues() as $group) {
$key = strtolower($group->getDeclination()->getName());
$value = ($key == "couleur") ? $group->getValue() : $group->getValue()->getName();
$data[$key] = $value;
$dec[$key][] = $value;
}
$quantity = 0;
foreach ($entity->getStocks() as $stock)
$quantity = $quantity + ($stock->getQtStock() - $stock->getQtReserved());
$priceTtc = $entity->getProduit()->getPriceTtc();
$in_promo=false;
if( $entity->getProduit()->getPromotion()) {
$promotion = $entity->getProduit()->getPromotion();
$date = new \DateTime('now');
if( $promotion->getStartAt() <= $date && $promotion->getEndAt() >= $date){
$priceTtc =($promotion->getDiscountType() == 'percent')?
$entity->getProduit()->getPriceTtc() - ((($entity->getProduit()->getPriceTtc() / 100) * $promotion->getDiscountValue()))
: $entity->getProduit()->getPriceTtc() - $promotion->getDiscountValue();
$in_promo=true;
}
}
// Mettre la declinaison choisi dans la première position
if ($entity->getId() == $idDec){
array_unshift($output, array_merge([
'id' => $entity->getId(),
"qty" => $quantity,
"price_ttc" => number_format($priceTtc, 3),
"in_promo" => $in_promo,
'price_ht' => number_format($entity->getPriceHt(), 3),
"picture" => $this->getDefaultImage(null, $entity,true),
"ref" => $entity->getReference(),
"name" => $entity->getName()
], $data));
}else {
$output[] = array_merge([
'id' => $entity->getId(),
"qty" => $quantity,
"price_ttc" => number_format($priceTtc, 3),
"in_promo" => $in_promo,
'price_ht' => number_format($entity->getPriceHt(), 3),
"picture" => $this->getDefaultImage(null, $entity,true),
"ref" => $entity->getReference(),
"name" => $entity->getName()
], $data);
}
}
// Récuérer les tags reliés
$Tags = $product->getTags();
$produitsTags = [];
// Récupérer les produit reliés au tag
foreach ($Tags as $tag) {
foreach ($tag->getProduits() as $prod) {
/*if(sizeof($produitsTags) == 4 ){
break;
}*/
if( $prod->getId() != $product->getId()) {
array_push($produitsTags, $prod);
}
}
/*if(sizeof($produitsTags) == 4 ){
break;
}*/
}
// Trier par id décroissant et récupérer les 4 dernier
usort($produitsTags, array($this, "comparator"));
$tags = [];
foreach ($produitsTags as $prod) {
if( sizeof($tags) == 4) break;
$prod->image = $this->getDefaultImage( $prod);
array_push($tags, $prod);
}
foreach ($dec as $k=>$v)
$dec[$k] = array_values(array_unique($dec[$k], SORT_REGULAR));
$response = [
'res' => 'OK',
'data' => ["produit" => $product, "declinaisons_produit" => $output, "declinaisons" => $dec, 'tags' => $tags],
'message' => 'Produit Dec récupéré avec succès.',
];
return new jsonResponse($response);
}
}