<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use App\Service\sessionManager;
use App\Service\dbincl;
use App\Service\elasticCon;
use App\Service\elasticTrends;
use Elastic\EnterpriseSearch\AppSearch\Request as eRequest;
use Elastic\EnterpriseSearch\AppSearch\Schema as eSchema;
class basePages extends AbstractController
{
/**
* @Route("/", name="index_site")
*/
public function index_site(dbincl $db_i): Response
{
$acc = new sessionManager([0, 1]);
$recommendations = [];
$db = $db_i->set();
$resultsIds = mysqli_query($db[0], "SELECT DISTINCT t1.product_id, t1.id FROM variations as t1 INNER JOIN products as t2 ON t1.product_id=t2.id WHERE t1.active=1 AND t2.active=1 AND t2.inindex=1 ORDER BY id DESC LIMIT 40");
$products = [];
while ($row = mysqli_fetch_assoc($resultsIds)) {
$products[] = $row['id'];
}
shuffle($products);
$products = implode(",", array_slice($products, 0, 12));
$newestResults = mysqli_query($db[0], "SELECT t1.id, IF(t1.about_photos = '[]', t2.about_photos, t1.about_photos) as photos, t1.price_mode, t1.price_normal, t1.price_discount, IF(t1.about_name = '', t2.about_name, t1.about_name) as a_name FROM variations as t1 INNER JOIN products as t2 ON t1.product_id=t2.id WHERE t1.id IN ($products)");
$products = [];
while ($row = mysqli_fetch_assoc($newestResults)) {
$photos = json_decode($row['photos'], true);
if(isset($photos[0])){
$photoUrl = $photos[0]['url'];
}else{
$photoUrl = "https://srv1.cnts.venderes.com/resources/uploads/items/@default.png";
}
$row['photos'] = $photoUrl;
$row['productHash'] = substr(bin2hex(base64_decode(md5(($row['id']*3) . "vndpri"))), 0, 10);
$products[] = $row;
}
$recommendations['newest'] = $products;
$eltrends = new elasticTrends($db);
$allData = $eltrends->trendsDefault();
$recommendations['popular'] = $allData;
return $this->render('basePages/template.html.twig', [
'contentType' => "index_page",
'acc' => ['if' => $acc->isLogged(), 'data' => $acc->data()],
'title' => "Pagrindinis",
'content' => [
'recommendations' => $recommendations
]
]);
}
/**
* @Route("/search", name="search_site")
*/
public function search_site(Request $request): Response
{
$acc = new sessionManager([0, 1]);
$term = $request->query->get('q');
$config = [
'@term' => ($term === null ? '' : $term),
'@data' => new \stdClass()
];
return $this->render('basePages/template.html.twig', [
'contentType' => "search_page",
'acc' => ['if' => $acc->isLogged(), 'data' => $acc->data()],
'title' => "Paieška - " . $term,
'content' => [
'term' => $term,
'config' => $config
]
]);
}
/**
* @Route("/product/{id}-{hash}", name="product_site", requirements={"id"="\d+", "hash"="^[a-z0-9]{10}$"})
*/
public function product_site($id, $hash, dbincl $db_i): Response
{
$acc = new sessionManager([0, 1]);
$db = $db_i->set();
$contentType = 'product_page';
if($hash != substr(bin2hex(base64_decode(md5(($id*3) . "vndpri"))), 0, 10)){
$contentType = 'product_page@notfound';
}else{
$product = mysqli_query($db[0], "SELECT
t1.id, t1.product_id, t1.seller_id, t1.brand, t1.price_mode, t1.price_normal, t1.price_discount, t1.about_photos as t1_a_photos, t2.about_photos as t2_a_photos,
IF(t1.about_name = '', t2.about_name, t1.about_name) as a_name,
IF(t1.about_description = '', t2.about_description, t1.about_description) as a_description,
IF(t1.about_redirect = '[]', t2.about_redirect, t1.about_redirect) as a_redirect_temp
FROM variations as t1 INNER JOIN products as t2 ON t1.product_id=t2.id WHERE t1.id='$id' AND t1.active=1 AND t2.active=1 AND t2.inindex=1 LIMIT 1");
if(mysqli_num_rows($product) == 0){
$contentType = 'product_page@notfound';
}
}
$content = [];
$allok = ($contentType == 'product_page');
$titleVal = 'Prekė nerasta';
if($allok){
$product_info = mysqli_fetch_assoc($product);
$content['aboutProduct'] = $product_info;
$content['aboutProduct']['about_photos'] = array_map(function($v) { return ['url' => $v['url']]; }, array_merge(json_decode($product_info['t1_a_photos'], true), json_decode($product_info['t2_a_photos'], true)));
//$content['aboutProduct']['about_photos'] = array_merge($content['aboutProduct']['about_photos'], $content['aboutProduct']['about_photos']);
//$content['aboutProduct']['about_photos'] = array_merge($content['aboutProduct']['about_photos'], $content['aboutProduct']['about_photos']);
$content['wish'] = [];
$content['wish']['hash'] = ($acc->isLogged() ? $id . "-" . rtrim(base64_encode(hex2bin(md5("wish-vnd-" . $id . "-" . $acc->data()['id']))), "=") : '');
$content['wish']['status'] = false;
if($acc->isLogged()){
$my_id = $acc->data()['id'];
$wishlistit = mysqli_query($db[0], "SELECT id FROM users_wishlist WHERE owner='$my_id' AND product='$id' LIMIT 1");
if(mysqli_num_rows($wishlistit) > 0){
$content['wish']['status'] = true;
}
}
$titleVal = $product_info['a_name'];
$sellerNameTemp = json_decode($product_info['a_redirect_temp'], true)['d'];
$content['aboutSeller']['name'] = parse_url($sellerNameTemp)['host'];
$todayhuman = date('Ymd'); $allStats = ['days' => [], 'vals' => []]; $metaStats = [];
$stats = mysqli_query($db[0], "SELECT value, day FROM price_changes WHERE variation_id={$id} AND NOT day='{$todayhuman}' ORDER BY day DESC LIMIT 7");
while($statrow = mysqli_fetch_assoc($stats)){
$date = substr($statrow['day'], 0, 4) . "-" . substr($statrow['day'], 4, 2) . "-" . substr($statrow['day'], 6, 2);
$allStats['days'][] = $date;
$allStats['vals'][] = number_format($statrow['value'] / 100, 2, '.', '');
$metaStats[] = $statrow['value'];
}
$allStats['days'] = array_reverse($allStats['days']);
$allStats['vals'] = array_reverse($allStats['vals']);
//Today stats
$today_price = ($product_info['price_mode'] == 1 ? $product_info['price_discount'] : $product_info['price_normal']);
$allStats['days'][] = date('Y-m-d');
$allStats['vals'][] = number_format($today_price / 100, 2, '.', '');
$metaStats[] = $today_price;
//*Today stats
$allStats['yax'] = [0,0];
if(isset($metaStats[0])){
$allStats['yax'] = [floor(min($metaStats) / 100) - 5, ceil(max($metaStats) / 100) + 5];
$allStats['yax'][0] = ($allStats['yax'][0] < 0 ? 0 : $allStats['yax'][0]);
}
$content['stats'] = $allStats;
}else{
$eltrends = new elasticTrends($db);
$content['trends'] = $eltrends->trendsDefault();
}
return $this->render('basePages/template.html.twig', [
'contentType' => $contentType,
'acc' => ['if' => $acc->isLogged(), 'data' => $acc->data()],
'title' => $titleVal,
'content' => $content
]);
}
/**
* @Route("/product/fromSearch/{id}-{hash}", name="product_site_stats", requirements={"id"="\d+", "hash"="^[a-z0-9]{10}$"})
*/
public function product_site_stats($id, $hash, Request $request): Response
{
if($hash == substr(bin2hex(base64_decode(md5(($id*3) . "vndpri"))), 0, 10)){
$source = $request->query->get('_source');
$requestid = $request->query->get('requestId');
$sign = $request->query->get('idSign');
$posBef = $request->query->get('posBef');
$pos = $request->query->get('pos');
$query = $request->query->get('query');
if(!in_array(null, [$source, $requestid, $sign, $posBef, $pos])){
$query = urldecode($query);
$sign = bin2hex(base64_decode($sign));
if(
in_array($source, ['organicSearch']) &&
filter_var($pos, FILTER_VALIDATE_INT) && filter_var($posBef, FILTER_VALIDATE_INT) !== false &&
$pos > $posBef &&
md5($requestid . "vndrs-search-sign" . dechex($posBef) . "/" . $query) == $sign
){
$clientCon = new elasticCon();
$client = $clientCon->client();
$appSearch = $client->appSearch();
$actReq = new eSchema\ClickParams($query, $id);
$actReq->request_id = $requestid;
$actReq->tags = ['source:', 'source:'.$source];
$result = $appSearch->logClickthrough(
new eRequest\LogClickthrough('prices-items', $actReq)
);
}
}
}
//Check and insert stats
return $this->redirectToRoute('product_site', ['id' => $id, 'hash' => $hash]);
}
/**
* @Route("/product/redirect/{id}/{hash}", name="productredirect_site", requirements={"id"="\d+", "hash"="^[a-z0-9]{10}$"})
*/
public function productredirect_site($id, $hash, dbincl $db_i): Response
{
if($hash == substr(bin2hex(base64_decode(md5(($id*3) . "vndpri"))), 0, 10)){
$db = $db_i->set();
$product = mysqli_query($db[0], "SELECT IF(t1.about_redirect = '[]', t2.about_redirect, t1.about_redirect) as a_redirect
FROM variations as t1 INNER JOIN products as t2 ON t1.product_id=t2.id WHERE t1.id='$id' AND t1.active=1 AND t2.active=1 AND t2.inindex=1 LIMIT 1");
if(mysqli_num_rows($product) > 0){
$product_info = mysqli_fetch_assoc($product);
$redirect_path = json_decode($product_info['a_redirect'], true);
if(isset($redirect_path['d']) && isset($redirect_path['p'])){
return $this->redirect($redirect_path['d'] . $redirect_path['p']);
}
}
}
return $this->redirectToRoute('product_site', ['id' => $id, 'hash' => $hash]);
}
/**
* @Route("/auth/{log_type}", name="auth_site", requirements={"log_type"="login|register|recover"})
*/
public function auth_site($log_type, Request $request): Response
{
$acc = new sessionManager([0]);
$routeTo = urldecode($request->query->get('routeTo'));
$index_path = $this->generateUrl('index_site');
return $this->redirect($acc->toAuth($index_path, ($routeTo == '' ? $index_path : $routeTo), $log_type));
}
}
?>