<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Doctrine\Persistence\ManagerRegistry;
use App\Service\Utils;
use App\Entity\Products;
use App\Entity\Requests;
use App\Entity\Reviews;
use App\Entity\ReviewData;
class MainController extends AbstractController
{
private $numMonthPrev;
public function __construct(){
$this->numMonthPrev = 5;
}
/**
* @Route("/", name="main_page", methods={"GET"})
*
*/
public function mainPage(Request $request, ManagerRegistry $doctrine, Utils $utils): Response
{
$user = $this->getUser();
if (!$user) {
return $this->redirectToRoute('app_login');
}
return $this->redirectToRoute('product_detail', array('id' => 1));
$utils->addLog($doctrine, $user, "", "view-panel");
$em = $doctrine->getManager();
$productsRepository = $em->getRepository(Products::class);
$requestsRepository = $em->getRepository(Requests::class);
$reviewsRepository = $em->getRepository(Reviews::class);
$products = $productsRepository->findBy(array("status"=>1));
$listProducts = array();
if($products && count($products) > 0){
foreach($products as $product){
$global = $reviewsRepository->getReviewsInfo($product);
$sentimentGlobal = 0;
if($global){
if($global[0]["positive"] > $global[0]["neutral"] && $global[0]["positive"] > $global[0]["negative"]){
$sentimentGlobal = 1;
}else if($global[0]["negative"] > $global[0]["neutral"] && $global[0]["negative"] > $global[0]["positive"]){
$sentimentGlobal = 2;
}
}
$total = $reviewsRepository->getReviewsTotal($product);
if($total){
$total = $total[0]["total"];
}else{
$total = 0;
}
$requests = $requestsRepository->getRequestByProduct($product);
$channelsInfo = array();
if($requests){
foreach($requests as $request){
$channel = $reviewsRepository->getReviewsInfo($product, $request);
$alias = ($request->getType() == 0)? "walmart" : "amazon";
$quantity = 0;
$sentiment = 0;
if($channel){
if($channel[0]["positive"] > $channel[0]["neutral"] && $channel[0]["positive"] > $channel[0]["negative"]){
$sentiment = 1;
}else if($channel[0]["negative"] > $channel[0]["neutral"] && $channel[0]["negative"] > $channel[0]["positive"]){
$sentiment = 2;
}
}
$quantity = $reviewsRepository->getReviewsTotal($product, $request);
if($quantity){
$quantity = $quantity[0]["total"];
}else{
$total = 0;
}
$channelsInfo[$alias] = array(
"quantity" => number_format($quantity , 0, ',', '.'),
"sentiment" => $sentiment
);
}
}
$aux = array(
"info" => $product,
"data" => array(
"channels" => $channelsInfo,
"global" => array(
"quantity" => number_format($total, 0, ',', '.'),
"sentiment" => $sentimentGlobal,
)
)
);
$listProducts[] = $aux;
}
}
return $this->render('panel.html.twig', array(
"listProducts" => $listProducts
));
}
/**
* @Route("/logged", name="main_page_logged", methods={"GET"})
*
*/
public function mainPageLogged(Request $request, ManagerRegistry $doctrine, Utils $utils): Response
{
$user = $this->getUser();
if (!$user) {
return $this->redirectToRoute('app_login');
}
$utils->addLog($doctrine, $user, "", "login");
return $this->redirectToRoute('main_page');
}
/**
* @Route("/product/{id}", name="product_detail", methods={"GET","POST"})
*
*/
public function productDetail(Request $request, ManagerRegistry $doctrine, Utils $utils, $id): Response
{
$user = $this->getUser();
if (!$user) {
return $this->redirectToRoute('app_login');
}
$utils->addLog($doctrine, $user, json_encode(array("id"=>$id, "channel"=>$request->get("channel"))), "view-detail");
$em = $doctrine->getManager();
$numMonthPrev = $this->numMonthPrev;
$now = new \DateTime('now');
$now->setTimezone(new \DateTimeZone('Europe/Madrid'));
$productsRepository = $em->getRepository(Products::class);
$requestsRepository = $em->getRepository(Requests::class);
$reviewsRepository = $em->getRepository(Reviews::class);
$reviewDataRepository = $em->getRepository(ReviewData::class);
$product = $productsRepository->find($id);
if($product){
$filter_channel = ($request->get("channel") === 0 || $request->get("channel") === 1 || $request->get("channel") === "1" || $request->get("channel") === "0")? $request->get("channel") : null;
$total = $reviewsRepository->getReviewsTotal($product, null, $filter_channel);
if($total){
$total = $total[0]["total"];
}else{
$total = 0;
}
$totalTemporal = [];
$ratingInfoTemporal = array(
"average" => [],
"bayes" => []
);
$labelPrev = array();
$dateStartPrev = $now->format("Y-m-01 00:00:00");
$dateEndPrev = $now->format("Y-m-t 23:59:59");
$dateStart = $dateStartPrev;
$dateEnd = $dateEndPrev;
for($i = $numMonthPrev; $i >= 0; $i--){
$dateStartPrev = date("Y-m-01 00:00:00", strtotime("-".$i." months",strtotime($dateStart)));
$dateEndPrev = date("Y-m-t 23:59:59", strtotime("-".$i." months",strtotime($dateEnd)));
$labelPrev[] = date("m-Y",strtotime($dateStartPrev));
$accTotal = $reviewsRepository->getReviewsTotal($product, null, $filter_channel, $dateStartPrev, $dateEndPrev);
if($accTotal){
$accTotal = $accTotal[0]["total"];
}else{
$accTotal = 0;
}
$totalTemporal[] = $accTotal;
$rating = $reviewsRepository->getReviewsRating($product, null, $filter_channel, $dateStartPrev, $dateEndPrev);
if($rating){
$ratingInfoTemporal["average"][] = ($rating[0]["rating"])? $rating[0]["rating"] : 0;
$ratingInfoTemporal["bayes"][] = ($rating[0]["bayes"])? $rating[0]["bayes"] : 0;
}
}
$global = $reviewsRepository->getReviewsInfo($product, null, $filter_channel);
$sentiments = array(
"positive" => 0,
"neutral" => 0,
"negative" => 0
);
if($global){
$sentiments["positive"] = str_replace(".",",",round($global[0]["positive"],2));
$sentiments["neutral"] = str_replace(".",",",round($global[0]["neutral"],2));
$sentiments["negative"] = str_replace(".",",",round($global[0]["negative"],2));
}
$rating = $reviewsRepository->getReviewsRating($product, null, $filter_channel);
$ratingInfo = array(
"average" => 0,
"bayes" => 0
);
if($rating){
$ratingInfo["average"] = str_replace(".",",",round($rating[0]["rating"],2));
$ratingInfo["bayes"] = str_replace(".",",",round($rating[0]["bayes"],2));
}
$requests = $requestsRepository->getRequestByProduct($product, $filter_channel);
$channelsInfo = array();
$types = array();
if($requests){
foreach($requests as $requestProduct){
$channel = $reviewsRepository->getReviewsInfo($product, $requestProduct);
$alias = ($requestProduct->getType() == 0)? "walmart" : "amazon";
$types[] = $requestProduct->getType();
$quantity = 0;
$sentiment = 0;
if($channel){
if($channel[0]["positive"] > $channel[0]["neutral"] && $channel[0]["positive"] > $channel[0]["negative"]){
$sentiment = 1;
}else if($channel[0]["negative"] > $channel[0]["neutral"] && $channel[0]["negative"] > $channel[0]["positive"]){
$sentiment = 2;
}
}
$quantity = $reviewsRepository->getReviewsTotal($product, $requestProduct);
if($quantity){
$quantity = $quantity[0]["total"];
}else{
$total = 0;
}
$channelsInfo[$alias] = array(
"quantity" => number_format($quantity , 0, ',', '.'),
"sentiment" => $sentiment
);
}
}
$temporal = array(
"labels" => array()
);
$typeTemporal = "months";
// if($start_date != "" && $start_date == $end_date){
// $type = "hours";
// }else{
// if($start_date != ""){
// if($end_date == ""){
// $end_date = date("Y-m-d");
// }
// $diff = date_diff(new \DateTime($start_date." 00:00:00"), new \DateTime($end_date." 23:59:59"));
// if($diff->days > 61){
// $type = "months";
// }
// }
// }
$temporalData = $reviewsRepository->getReviewsTemporal($product, $filter_channel);
foreach($temporalData as $data){
if($typeTemporal == "months") $date = str_pad($data["month"], 2, '0', STR_PAD_LEFT)."/".$data["year"];
if(!in_array($date,$temporal["labels"])){
$temporal["labels"][] = $date;
foreach($types as $type){
if(!isset($temporal["data_".$type][$date])) $temporal["data_".$type][$date] = 0;
}
}
$temporal["data_".$data["type"]][$date] = $data["qtt"];
}
foreach($temporal as $key => $t){
$temporal[$key] = array_values($temporal[$key]);
}
$temporalRating = array(
"labels" => array()
);
$temporalRatingData = $reviewsRepository->getReviewsTemporalRating($product, $filter_channel);
$ratingsType = array(1,2,3,4,5);
foreach($temporalRatingData as $data){
if($typeTemporal == "months") $date = str_pad($data["month"], 2, '0', STR_PAD_LEFT)."/".$data["year"];
if(!in_array($date,$temporalRating["labels"])){
$temporalRating["labels"][] = $date;
foreach($ratingsType as $rt){
if(!isset($temporalRating["data_".$rt][$date])) $temporalRating["data_".$rt][$date] = 0;
}
}
$temporalRating["data_".$data["rating"]][$date] = $data["qtt"];
}
foreach($temporalRating as $key => $t){
$temporalRating[$key] = array_values($temporalRating[$key]);
}
$topics = array("topic_price","topic_usage", "topic_fragrance","topic_clean");
$topicsData = array();
if($topics){
foreach($topics as $topic){
$topicsData[] = $reviewDataRepository->getReviewsDataTopics($product, $topic, $filter_channel);
}
}
foreach($topicsData as $key => $topic){
$topicsData[$key] = $topicsData[$key][0];
$topicsData[$key]["topic"] = $topics[$key];
}
usort($topicsData,function($first,$second){
return $first["positive"] < $second["positive"];
});
$topicsDataResult = array(
"labels" => array(),
"positive" => array(),
"negative" => array()
);
foreach($topicsData as $topic){
$topicsDataResult["labels"][] = ucfirst(str_replace("topic_","",$topic["topic"]));
$topicsDataResult["positive"][] = $topic["positive"];
$topicsDataResult["negative"][] = $topic["negative"]*-1;
}
$keywords = $reviewDataRepository->getReviewsDataKeywords($product, $filter_channel);
$usedIn = $reviewDataRepository->getReviewsDataProducts($product, $filter_channel);
$insight = $reviewDataRepository->getReviewsDataInsight($product, $filter_channel);
$emotions = $reviewDataRepository->getReviewsDataEmotions($product, $filter_channel);
$emotionsData = array(
"labels" => array(),
"data" => array()
);
if($emotions){
foreach($emotions as $emotion){
$emotionsData["labels"][] = ucfirst($emotion["text"]);
$emotionsData["data"][] = round(($emotion["count"]*100)/$total,2);
}
}
$messagesLastBest = $reviewsRepository->getReviewsMessagesLastBest($product, $filter_channel);
if($messagesLastBest){
$messagesLastBest = $messagesLastBest[0];
}
$messagesLastWorse = $reviewsRepository->getReviewsMessagesLastWorse($product, $filter_channel);
if($messagesLastWorse){
$messagesLastWorse = $messagesLastWorse[0];
}
$reviewsNeutral = $reviewsRepository->getReviewsNeutral($product, $filter_channel);
$reviewsPositive = $reviewsRepository->getReviewsPositive($product, $filter_channel);
$reviewsNegative = $reviewsRepository->getReviewsNegative($product, $filter_channel);
$dataResponse = array(
"product" => $product,
"total" => $total,
"channels" => $channelsInfo,
"sentiments" => $sentiments,
"rating" => $ratingInfo,
"temporal" => json_encode($temporal),
"temporalRating" => json_encode($temporalRating),
"topics" => json_encode($topicsDataResult),
"keywords" => json_encode($keywords),
"usedIn" => json_encode($usedIn),
"insight" => json_encode($insight),
"emotions" => json_encode($emotionsData),
"messagesLastBest" => $messagesLastBest,
"messagesLastWorse" => $messagesLastWorse,
"reviewsNeutral" => $reviewsNeutral,
"reviewsPositive" => $reviewsPositive,
"reviewsNegative" => $reviewsNegative,
"totalTemporal" => json_encode($totalTemporal),
"ratingInfoTemporal" => json_encode($ratingInfoTemporal["average"]),
"ratingInfoTemporalBayes" => json_encode($ratingInfoTemporal["bayes"]),
"labelPrev" => json_encode($labelPrev)
);
if($request->get("ajax")){
return new JsonResponse([
"status" => "success",
"data" => $dataResponse
] , Response::HTTP_OK);
}else{
return $this->render('detail.html.twig', $dataResponse);
}
}else{
return $this->redirectToRoute('main_page');
}
}
}