<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use App\Entity\BannedDomainEntity;
use App\Entity\BannedUserEntity;
use App\Entity\BonusEntity;
use App\Entity\GeneratedWalletEntity;
use App\Entity\MessageEntity;
use App\Entity\NotificationEntity;
use App\Entity\RecycledWalletEntity;
use App\Entity\ReferralEntity;
use App\Entity\SettingEntity;
use App\Entity\SupportTicketEntity;
use App\Entity\SupportTicketResponseEntity;
use App\Entity\UserAdjustedTokenEntity;
use App\Entity\UserBonusTokenEntity;
use App\Entity\UserEntity;
use App\Entity\UserOrderTokenEntity;
use App\Entity\UserStakeTokenEntity;
use App\Entity\VisitorEntity;
use App\Entity\EmailEntity;
use App\Entity\UserUsdtEntity;
use App\Service\AuthService;
use App\Service\BlockIoService;
use App\Service\TOTPService;
#[Route("/ajax")]
class AjaxController extends AbstractController
{
private $totpService;
public function __construct(TOTPService $totpService)
{
$this->totpService = $totpService;
}
#[Route("/stake_cancel", name:"ajax_stake_cancel")]
public function stakeCancelAction(Request $request, AuthService $authService)
{
$result = ['success' => false, ];
$id = $request->request->get('id');
if(is_null($id)){
return new JsonResponse(['success' => false, 'msg' => 'Opps something went wrong please try again.']);
}
$em = $this->getDoctrine()->getManager();
$stake = $em->getRepository(UserStakeTokenEntity::class)->find($id);
if(!$stake){
$result['msg'] = 'Ooops something went wrong please try again later.';
} else {
$result['success'] = true;
$stake->setStatus('Cancelled');
$em->flush();
if((($stake->getInterestPercent() / 100) * ($authService->calculateDaysEarned($stake->getTokenAmount(), $stake->getStartDate(), $stake->getEndDate()) * $stake->getTokenDollarValue())) - (0.01 / 100) > 0){
//process cancelling
$usdtWallet = new UserUsdtEntity();
$usdtWallet->setUserStakeToken($stake);
$usdtWallet->setAmount((($stake->getInterestPercent() / 100) * ($authService->calculateDaysEarned($stake->getTokenAmount(), $stake->getStartDate(), $stake->getEndDate()) * $stake->getTokenDollarValue())) - (0.01 / 100) );
$em->persist($usdtWallet);
$em->flush();
if($stake->getType() == 3){
$srb = $em->getRepository(BonusEntity::class)->findOneBy(['code' => 'SRB']);
if($srb){
$usrb = new UserBonusTokenEntity();
$usrb->setUser($stake->getUser());
$usrb->setBonus($srb);
$usrb->setAmount($authService->calculateDaysEarned($stake->getTokenAmount(), $stake->getStartDate(), $stake->getEndDate()) - ((0.01 / 100) * $stake->getTokenAmount()));
$usrb->setUserStakeToken($stake);
$em->persist($usrb);
$em->flush();
}
}
}
$this->get('session')->getFlashBag()->add('success_messages', 'Your staking is successfully cancelled.');
}
return new JsonResponse($result);
}
#[Route("/referrer_form", name:"ajax_referrer_form")]
public function referrerFormAction(Request $request, AuthService $authService)
{
$result = ['success' => 'msg'];
$id = $request->request->get('id');
if(is_null($id)){
return new JsonResponse(['success' => false, 'msg' => 'Opps something went wrong please try again.']);
}
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository(UserEntity::class)->find($id);
$result['html'] = $this->renderView('Ajax/referrer_form.html.twig', ['user' => $user]);
return new JsonResponse($result);
}
#[Route("/referrer_form_action", name:"ajax_referrer_form_action")]
public function referrer_form_action(Request $request, AuthService $authService)
{
$result = ['success' => true, 'msg' => ''];
$user = $authService->getUser();
$pr = $request->request->all();
$em = $this->getDoctrine()->getManager();
if(isset($pr['id'])){
$user = $em->getRepository(UserEntity::class)->find($pr['id']);
$referrer = $em->getRepository(UserEntity::class)->findOneBy(['email' => $pr['referrer']]);
if(!$user){
return new JsonResponse(['success' => false , 'msg' => 'Ooops something went wrong please try again later.']);
}
if(!$referrer){
return new JsonResponse(['success' => false , 'msg' => 'Email address is not exists.']);
}
if($user->getReferral() && $user->getReferral()->getReferrer()->getEmail() != $pr['referrer'] || is_null($user->getReferral())){
$referral = new ReferralEntity();
$referral->setReferrer($referrer);
$referral->setlevel(1);
$referral->setStatus('Completed');
$referral->setReferrentEmail($user->getEmail());
$em->persist($referral);
$em->flush();
$user->setReferral($referral);
$em->flush();
$primarySignUpBonus = $em->getRepository(BonusEntity::class)->findOneBy(array('code' => 'PR'));
if($primarySignUpBonus){
$primaryUserBonus = new UserBonusTokenEntity();
$primaryUserBonus->setUser($referral->getReferrer());
$primaryUserBonus->setBonus($primarySignUpBonus);
$primaryUserBonus->setAmount($primarySignUpBonus->getBonusToken());
$primaryUserBonus->setReferral($referral);
$em->persist($primaryUserBonus);
$em->flush();
$notification = new NotificationEntity();
$notification->setType('Level 1 Referral');
$notification->setMessage('You have a new Level 1 Referral');
$notification->setUser($referral->getReferrer());
$em->persist($notification);
$em->flush();
}
$result['msg'] = 'Referral successfully updated.';
}
}
return new JsonResponse($result);
}
#[Route("/get_notification", name:"ajax_get_notification")]
public function get_notificationAction(Request $request, AuthService $authService)
{
$result = ['success' => 'msg'];
$pr = $request->query->all();
$notification = null;
$em = $this->getDoctrine()->getManager();
switch($pr['action']){
case 'markAllAsRead':
$notifications = $em->getRepository(NotificationEntity::class)->findBy(['user' => $authService->getUser()]);
foreach($notifications as $notification){
$notification->setStatus('Read');
$em->flush();
}
return new JsonResponse($result);
break;
case 'get':
$notification = $em->getRepository(NotificationEntity::class)->find($pr['id']);
break;
case 'next':
$qb = $em->createQueryBuilder()
->select('n') // Select the entity
->from('App\Entity\NotificationEntity', 'n') // Use the fully qualified class name
->where('n.id > :id')
->andWhere('n.user = :userId')
->setParameters([
'id' => $pr['id'],
'userId' => $authService->getUser()->getId()
])
->setMaxResults(1) // Limit the result to one entity
->getQuery();
$notification = $qb->getOneOrNullResult();
if(!$notification){
$qb = $em->createQueryBuilder()
->select('n') // Select the entity
->from('App\Entity\NotificationEntity', 'n') // Use the fully qualified class name
->where('n.user = :userId')
->setParameters([
'userId' => $authService->getUser()->getId()
])
->orderBy('n.createdAt', 'ASC')
->setMaxResults(1) // Limit the result to one entity
->getQuery();
$notification = $qb->getOneOrNullResult();
}
break;
case 'previous':
$qb = $em->createQueryBuilder()
->select('n') // Select the entity
->from('App\Entity\NotificationEntity', 'n') // Use the fully qualified class name
->where('n.id < :id')
->andWhere('n.user = :userId')
->setParameters([
'id' => $pr['id'],
'userId' => $authService->getUser()->getId()
])
->orderBy('n.createdAt', 'DESC')
->setMaxResults(1) // Limit the result to one entity
->getQuery();
$notification = $qb->getOneOrNullResult();
if(!$notification){
$qb = $em->createQueryBuilder()
->select('n') // Select the entity
->from('App\Entity\NotificationEntity', 'n') // Use the fully qualified class name
->where('n.user = :userId')
->setParameters([
'userId' => $authService->getUser()->getId()
])
->orderBy('n.createdAt', 'DESC')
->setMaxResults(1) // Limit the result to one entity
->getQuery();
$notification = $qb->getOneOrNullResult();
}
break;
}
if($notification){
$notification->setStatus('Read');
$em->flush();
}
$result['html'] = $this->renderView('Ajax/notification_details.html.twig',['notification' => $notification ]);
return new JsonResponse($result);
}
#[Route("/two_fa_generate", name:"ajax_two_fa_generate")]
public function two_fa_generate(Request $request, AuthService $authService)
{
$result = ['success' => true, 'msg' => ''];
$user = $authService->getUser();
$secret = $this->totpService->getSecret();
$provisioningUri = $this->totpService->getProvisioningUri($user->getEmail());
$qr = $this->totpService->generateQRCode($provisioningUri);
$result['html'] = $this->renderView('Ajax/two_fa_generate.html.twig', ['qr' => $qr]);
return new JsonResponse($result);
}
#[Route("/two_fa_verify", name:"ajax_two_fa_verify")]
public function two_fa_verify(Request $request, AuthService $authService)
{
$result = ['success' => true, 'msg' => ''];
$user = $authService->getUser();
$pr = $request->request->all();
$result['isValid'] = $pr['otp'] == $this->totpService->verifyOTP() ? true : false;
return new JsonResponse($result);
}
#[Route("/save_visitor", name:"ajax_save_visitor")]
public function save_visitor(Request $request, AuthService $authService)
{
$result = array();
$ip = $_SERVER['REMOTE_ADDR'];
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
$em = $this->getDoctrine()->getManager();
$visitor = $em->getRepository(VisitorEntity::class)->findOneBy(['ipAddress' => $ip]);
if(is_null($visitor)){
$visitor = new VisitorEntity();
$visitor->setIpAddress($ip);
$visitor->setCount(1);
$em->persist($visitor);
} else {
$visitor->setCount($visitor->getCount() + 1);
}
$em->flush();
$result['success'] = true;
return new JsonResponse($result);
}
#[Route("/visitor_statistics", name:"ajax_visitor_statistics")]
public function visitor_statistics(Request $request, AuthService $authService)
{
$result = array();
$em = $this->getDoctrine()->getManager();
$days = [];
$stats = [];
$visitorStats = $em->getRepository(VisitorEntity::class)->statistics(7);
foreach($visitorStats as $stat){
$stats[$stat['vDate']]['newVisitor'] = $stat['newVisitor'];
$stats[$stat['vDate']]['oldVisitor'] = $stat['oldVisitor'];
$stats[$stat['vDate']]['date'] = $stat['vDate'];
}
usort($stats, function($a1, $a2) {
$v1 = strtotime($a1['date']);
$v2 = strtotime($a2['date']);
return $v1 - $v2;
});
$result['success'] = true;
return new JsonResponse($stats);
}
#[Route("/get_users_and_orders_stat", name:"ajax_get_users_and_orders_stat")]
public function get_user_and_order_stat(Request $request, AuthService $authService)
{
$result = array();
$em = $this->getDoctrine()->getManager();
$days = [];
$stats = [];
$userStats = $em->getRepository(UserEntity::class)->userStatistics(7);
$orderStats = $em->getRepository(UserOrderTokenEntity::class)->orderStatistics();
foreach($userStats as $stat){
$stats[$stat['regDate']]['regCount'] = $stat['regCount'];
$stats[$stat['regDate']]['date'] = $stat['regDate'];
}
foreach ($orderStats as $k => $stat) {
if(isset($stats[$stat['orderDay']])){
$stats[$stat['orderDay']]['orderCount'] = $stat['orderAmt'];
} else {
$stats[$stat['orderDay']] = ['orderCount' => $stat['orderAmt']];
$stats[$stat['orderDay']]['date'] = $stat['orderDay'];
}
}
//Sort array
usort($stats, function($a1, $a2) {
$v1 = strtotime($a1['date']);
$v2 = strtotime($a2['date']);
return $v1 - $v2;
});
$result['success'] = true;
return new JsonResponse($stats);
}
#[Route("/get_users_stat", name:"ajax_get_users_stat")]
public function get_user_stat(Request $request, AuthService $authService)
{
$result = array();
$em = $this->getDoctrine()->getManager();
$days = [];
$stats = [];
$userStats = $em->getRepository(UserEntity::class)->userStatistics(7);
foreach($userStats as $stat){
array_push($days, $stat['regDate']);
array_push($stats, $stat['regCount']);
}
$result['days'] = $days;
$result['stats'] = $stats;
$result['success'] = true;
return new JsonResponse($result);
}
#[Route("/get_orders_stat", name:"ajax_get_orders_stat")]
public function get_orders_stat(Request $request, AuthService $authService)
{
$result = array();
$em = $this->getDoctrine()->getManager();
$days = [];
$stats = [];
$orderStats = $em->getRepository(UserOrderTokenEntity::class)->orderStatistics();
foreach($orderStats as $stat){
array_push($days, $stat['orderDate']);
array_push($stats, $stat['orderCount']);
}
$result['days'] = $days;
$result['stats'] = $stats;
$result['success'] = true;
return new JsonResponse($result);
}
#[Route("/get_active_users_ctr", name:"ajax_get_active_users_ctr")]
public function get_active_users_ctr(Request $request, AuthService $authService)
{
$result = array();
$em = $this->getDoctrine()->getManager();
$result['ctr'] = $em->getRepository(UserEntity::class)->userCount();
$result['success'] = true;
return new JsonResponse($result);
}
#[Route("/get_coin_value", name:"ajax_get_coin_value")]
public function get_coin_value(Request $request, AuthService $authService, BlockIoService $blockIoService)
{
$result = array();
$result['success'] = true;
$result['price'] = $blockIoService->getNetworkPrice($request->get('pm'));
return new JsonResponse($result);
}
#[Route("/stage_info", name:"ajax_stage_info")]
public function stage_info_Action(Request $request, AuthService $authService)
{
$data = array();
$em = $this->getDoctrine()->getManager();
$stagePurchase = $em->getRepository(UserOrderTokenEntity::class)->stagePurchase();
$stageBonus = $em->getRepository(UserBonusTokenEntity::class)->totalDistribution();
$data['stagePurchase'] = $stagePurchase['stagePurchase'] + $stageBonus;
$data['stageToken'] = 888000000000;
$data['remainingStageToken'] = $data['stageToken'] - $stagePurchase['stagePurchase'] + $stageBonus;
return new JsonResponse($data);
}
#[Route("/profits", name:"ajax_user_profits")]
public function userProfits_Action(Request $request, AuthService $authService)
{
$em = $this->getDoctrine()->getManager();
$profits = ['bonus' => $authService->getUser()->getTotalBonus(), 'purchase' => $authService->getUser()->getTotalPurchase() ];
return new JsonResponse($profits);
}
#[Route("/graph_data", name:"ajax_graph_data")]
public function graph_data_Action(Request $request, AuthService $authService)
{
$data = array();
$em = $this->getDoctrine()->getManager();
$purchaseStats = $em->getRepository(UserOrderTokenEntity::class)->orderStatistics();
$bonusStats = $em->getRepository(UserBonusTokenEntity::class)->statistics(7);
$stats = array();
/*Get the purchase stats*/
foreach ($purchaseStats as $k => $purchaseStat) {
$stats[$purchaseStat['orderDate']]['purchaseTokenAmt'] = $purchaseStat['orderAmt'];
$stats[$purchaseStat['orderDate']]['day'] = $purchaseStat['orderDay'];
$stats[$purchaseStat['orderDate']]['date'] = $purchaseStat['orderDate'];
}
/*Get the bonus stats*/
foreach ($bonusStats as $k => $bonusStat) {
if(isset($stats[$bonusStat['bonusDate']])){
$stats[$bonusStat['bonusDate']]['bonusTokenAmt'] = $bonusStat['totalBonusToken'];
} else {
$stats[$bonusStat['bonusDate']] = ['bonusTokenAmt' => $bonusStat['totalBonusToken']];
$stats[$bonusStat['bonusDate']]['day'] = $bonusStat['bonusDay'];
$stats[$bonusStat['bonusDate']]['date'] = $bonusStat['bonusDate'];
}
}
//Sort array
usort($stats, function($a1, $a2) {
$v1 = strtotime($a1['date']);
$v2 = strtotime($a2['date']);
return $v1 - $v2;
});
return new JsonResponse(array_reverse($stats));
}
#[Route("/email_list", name:"ajax_email_list")]
public function email_Action(Request $request, AuthService $authService)
{
$get = $request->query->all();
$result = array(
"draw" => intval($get['draw']),
"recordsTotal" => 0,
"recordsFiltered" => 0,
"data" => array()
);
$authService =$authService;
if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
if($authService->getUser()->getType() == 'Super Admin') {
$data = $this->getDoctrine()->getManager()->getRepository(EmailEntity::class)->ajax_list($get);
foreach($data['results'] as $row) {
$url = $this->generateUrl('manage_email_form', array(
'id' => base64_encode($row['id']),
'action' => 'u'
));
$values = array(
$row['subject'],
$row['message'],
'',
"<a class='action-button-style' href='$url'>Update</a>"
);
$result['data'][] = $values;
}
$result['recordsTotal'] = $data['total'];
$result['recordsFiltered'] = $data['total'];
}
return new JsonResponse($result);
}
#[Route("/user_adjusted_token_list", name:"ajax_user_adjusted_token_list")]
public function user_adjusted_tokenList_Action(Request $request, AuthService $authService)
{
$get = $request->query->all();
$result = array(
"draw" => intval($get['draw']),
"recordsTotal" => 0,
"recordsFiltered" => 0,
"data" => array()
);
$authService =$authService;
if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
if($authService->getUser()->getType() == 'Super Admin') {
$data = $this->getDoctrine()->getManager()->getRepository(UserAdjustedTokenEntity::class)->ajax_list($get);
foreach($data['results'] as $row) {
$values = array(
$row['name'],
$row['createdDate'],
$row['amt']
);
$result['data'][] = $values;
}
$result['recordsTotal'] = $data['total'];
$result['recordsFiltered'] = $data['total'];
}
return new JsonResponse($result);
}
#[Route("/user_remove/{id}", name:"ajax_remove_user")]
public function remove_Action(Request $request, AuthService $authService, $id)
{
$result = ['success' => true, 'msg' => ''];
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository(UserEntity::class)->find(base64_decode($id));
if(!$user){
$result = ['success' => false, 'msg' => 'Oooops something went wrong please try again later.'];
} else {
$user->setStatus('Banned');
$em->flush();
$projectDir = $this->getParameter('kernel.project_dir');
// $process = Process::fromShellCommandline('php '. $projectDir. '/bin/console app:banned-user-command ' . base64_encode($emailForm['id']) ); //window
$process = Process::fromShellCommandline('php '. $projectDir. '/bin/console app:banned-user-command ' . $user->getId() . ' > /dev/null 2>&1 &' ); //linux
$process->start();
//window
// $process->waitUntil(function ($type, $output): bool {
// return $output === 'Ready. Waiting for commands...';
// });
$result['success'] = true;
$result['msg'] = 'User successfully remove';
}
return new JsonResponse($result);
}
#[Route("/user_list", name:"ajax_user_list")]
public function userList_Action(Request $request, AuthService $authService)
{
$get = $request->query->all();
$result = array(
"draw" => intval($get['draw']),
"recordsTotal" => 0,
"recordsFiltered" => 0,
"data" => array()
);
$authService =$authService;
if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
if($authService->getUser()->getType() == 'Super Admin') {
$data = $this->getDoctrine()->getManager()->getRepository(UserEntity::class)->ajax_list($get);
foreach($data['results'] as $row) {
$url = $this->generateUrl('manage_user_referrals', array(
'id' => $row['id']
));
$url2 = $this->generateUrl('manage_user_transactions', array(
'id' => $row['id']
));
$removeUser = $this->generateUrl('ajax_remove_user', array(
'id' => base64_encode($row['id'])
));
$userRefAction = "<a class='action-button-style' href='$url'>".($row['userTotalReferral'] ? $row['userTotalReferral'] : 0)."</a>";
$userTransactionAction = "<a class='action-button-style' href='$url2'>".($row['userTotalToken'] ? $row['userTotalToken'] : 0)."</a>";
$values = array(
$row['id'],
$row['email'],
$row['name'],
$row['joinDate'],
'<a href="javascript:void(0);" class="href-modal" data-action="referrer" data-id="'.$row["id"].'">' . ($row['referrer'] ? $row['referrer'] : "Set Referrer") . '</a>',
$row['status'],
$userTransactionAction,
$userRefAction,
'<a href="javascript:void(0);" class="href-remove-user" data-url="'.$removeUser.'"> Banned</a>',
);
$result['data'][] = $values;
}
$result['recordsTotal'] = $data['total'];
$result['recordsFiltered'] = $data['total'];
}
return new JsonResponse($result);
}
#[Route("/recycled_wallet_list", name:"ajax_recycled_wallet_list")]
public function recycledWalletList_Action(Request $request, AuthService $authService)
{
$get = $request->query->all();
$result = array(
"draw" => intval($get['draw']),
"recordsTotal" => 0,
"recordsFiltered" => 0,
"data" => array()
);
$authService =$authService;
if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
if($authService->getUser()->getType() == 'Super Admin') {
$data = $this->getDoctrine()->getManager()->getRepository(RecycledWalletEntity::class)->ajax_list($get);
foreach($data['results'] as $row) {
$values = array(
$row['network'],
$row['address'],
$row['status']
);
$result['data'][] = $values;
}
$result['recordsTotal'] = $data['total'];
$result['recordsFiltered'] = $data['total'];
}
return new JsonResponse($result);
}
#[Route("/order_list", name:"ajax_order_list")]
public function orderList_Action(Request $request, AuthService $authService)
{
$get = $request->query->all();
$result = array(
"draw" => intval($get['draw']),
"recordsTotal" => 0,
"recordsFiltered" => 0,
"data" => array()
);
$authService =$authService;
if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
if($authService->getUser()->getType() == 'Super Admin') {
$data = $this->getDoctrine()->getManager()->getRepository(UserOrderTokenEntity::class)->ajax_list($get);
$tokenDollarValue = $this->getParameter('app.token_dollar_value');
foreach($data['results'] as $row) {
$action = '';
$url = $this->generateUrl('manage_confirm_transaction', array(
'id' => base64_encode($row['id'])
));
$adjustTransacrionUrl = $this->generateUrl('manage_transaction_adjust', array(
'id' => base64_encode($row['id'])
));
$cancelUrl = $this->generateUrl('manage_cancel_transaction', array(
'id' => base64_encode($row['id'])
));
$action .= "<a class='action-button-style text-primary' href='$url'>Confirm</a>" ;
$action .= "<a class='action-button-style text-primary' href='$cancelUrl'>| Cancel</a>" ;
$action .= "<a class='action-button-style text-primary' href='$adjustTransacrionUrl'> | Adjust</a>" ;
$values = array(
$row['id'],
$row['member'],
$row['email'],
$row['transactionDate'],
'<a class="text-primary" href="https://chain.so/address/' . $row['network'] . '/' . $row['address'].'" target="_blank">'. $row['address'].'</a>',
$row['currency'],
number_format(($row['tokenAmt'] * $tokenDollarValue) , 2, '.',','),
$row['amount'],
empty($row['amountReceived']) ? '0.00' : $row['amountReceived'],
$row['status'],
$row['status'] == 'Pending' ? $action : ''
);
$result['data'][] = $values;
}
$result['recordsTotal'] = $data['total'];
$result['recordsFiltered'] = $data['total'];
}
return new JsonResponse($result);
}
#[Route("/bonus_list", name:"ajax_bonus_list")]
public function bonusList_Action(Request $request, AuthService $authService)
{
$get = $request->query->all();
$result = array(
"draw" => intval($get['draw']),
"recordsTotal" => 0,
"recordsFiltered" => 0,
"data" => array()
);
$authService =$authService;
if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
if($authService->getUser()->getType() == 'Super Admin') {
$data = $this->getDoctrine()->getManager()->getRepository(BonusEntity::class)->ajax_list($get);
foreach($data['results'] as $row) {
$action = '';
$url = $this->generateUrl('manage_bonus_form', array(
'id' => base64_encode($row['id']),
'action' => 'u'
));
$action .= "<a class='action-button-style' href='$url'>Update</a>" ;
$values = array(
$row['code'],
$row['description'],
$row['percent'],
$row['bonus_token'],
$action
);
$result['data'][] = $values;
}
$result['recordsTotal'] = $data['total'];
$result['recordsFiltered'] = $data['total'];
}
return new JsonResponse($result);
}
#[Route("/setting_list", name:"ajax_setting_list")]
public function settingList_Action(Request $request, AuthService $authService)
{
$get = $request->query->all();
$result = array(
"draw" => intval($get['draw']),
"recordsTotal" => 0,
"recordsFiltered" => 0,
"data" => array()
);
$authService =$authService;
if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
if($authService->getUser()->getType() == 'Super Admin') {
$data = $this->getDoctrine()->getManager()->getRepository(SettingEntity::class)->ajax_list($get);
foreach($data['results'] as $row) {
$action = '';
$url = $this->generateUrl('manage_setting_form', array(
'id' => base64_encode($row['id']),
'action' => 'u'
));
$action .= "<a class='action-button-style' href='$url'>Update</a>" ;
$values = array(
$row['description'],
$row['settingValue'],
$action
);
$result['data'][] = $values;
}
$result['recordsTotal'] = $data['total'];
$result['recordsFiltered'] = $data['total'];
}
return new JsonResponse($result);
}
#[Route("/banned_domain_list", name:"ajax_banned_domain_list")]
public function banned_domain_listAction(Request $request, AuthService $authService)
{
$get = $request->query->all();
$result = array(
"draw" => intval($get['draw']),
"recordsTotal" => 0,
"recordsFiltered" => 0,
"data" => array()
);
$authService =$authService;
if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
if($authService->getUser()->getType() == 'Super Admin') {
$data = $this->getDoctrine()->getManager()->getRepository(BannedDomainEntity::class)->ajax_list($get);
foreach($data['results'] as $row) {
$action = '';
$url = $this->generateUrl('manage_banned_domain_form', array(
'id' => base64_encode($row['id']),
'action' => 'u'
));
$action .= "<a class='action-button-style' href='$url'>Update</a>" ;
$values = array(
$row['description'],
$action
);
$result['data'][] = $values;
}
$result['recordsTotal'] = $data['total'];
$result['recordsFiltered'] = $data['total'];
}
return new JsonResponse($result);
}
#[Route("/user_order_list", name:"ajax_user_order_list")]
public function user_order_listAction(Request $request, AuthService $authService)
{
$get = $request->query->all();
$result = array(
"draw" => intval($get['draw']),
"recordsTotal" => 0,
"recordsFiltered" => 0,
"data" => array()
);
$authService =$authService;
if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
$data = $this->getDoctrine()->getManager()->getRepository(UserOrderTokenEntity::class)->userOrderList($get, $authService->getUser());
foreach($data['results'] as $row) {
$url = $this->generateUrl('dashboard_order_details', array(
'id' => base64_encode($row['id'])
));
$transid = base64_encode( ($row['id']) );
$GLN = "GLN" ;
$action = "<a class='action-button-style text-primary' href='$url'>".substr($row['address'],0,5) . (strlen($row['address']) > 7 ? '...' : '') ."</a>" ;
$values = array(
"<a class='orderList' data-transaction='".$row['id']."'>".sprintf($row['id'])."</a>" ,
$row['created_at'],
$row['token_value'] . $row['network'],
number_format($row['tokenAmt'], 0, '' , ',') . ".$GLN.",
"<a class='orderList' data-transaction='".$row['status']."'>".sprintf($row['status'])."</a>" ,
"<a href='https://gleancoin.com/purchase/details/".$transid."' class='btn btn-primary'>View Details</a>",
"<a class='orderList' href='javascript:void(0);' data-transaction='".$row['id']."'><em class='ti ti-more-alt'></em></a>"
);
$result['data'][] = $values;
}
$result['recordsTotal'] = $data['total'];
$result['recordsFiltered'] = $data['total'];
return new JsonResponse($result);
}
#[Route("/user_reward_list", name:"ajax_user_reward_list")]
public function user_reward_listAction(Request $request, AuthService $authService)
{
$get = $request->query->all();
$result = array(
"draw" => intval($get['draw']),
"recordsTotal" => 0,
"recordsFiltered" => 0,
"data" => array()
);
$authService =$authService;
if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
$data = $this->getDoctrine()->getManager()->getRepository(UserBonusTokenEntity::class)->userBonusList($get, $authService->getUser());
foreach($data['results'] as $row) {
$values = array(
$row['bonus'],
$row['amt'],
);
$result['data'][] = $values;
}
$result['recordsTotal'] = $data['total'];
$result['recordsFiltered'] = $data['total'];
return new JsonResponse($result);
}
#[Route("/user_referral_list", name:"ajax_user_referral_list")]
public function user_referral_listAction(Request $request, AuthService $authService)
{
$get = $request->query->all();
$result = array(
"draw" => intval($get['draw']),
"recordsTotal" => 0,
"recordsFiltered" => 0,
"data" => array()
);
$authService =$authService;
if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
$data = $this->getDoctrine()->getManager()->getRepository(UserBonusTokenEntity::class)->getReferralByLevel($get, $authService->getUser());
foreach($data['results'] as $row) {
$values = array(
$row['name'],
$row['amount'],
$row['email'],
$row['createdDate'],
$row['status'],
);
$result['data'][] = $values;
}
$result['recordsTotal'] = $data['total'];
$result['recordsFiltered'] = $data['total'];
return new JsonResponse($result);
}
#[Route("/user_support_ticket_list", name:"ajax_user_support_ticket_list")]
public function user_support_ticket_listAction(Request $request, AuthService $authService)
{
$get = $request->query->all();
$result = array(
"draw" => intval($get['draw']),
"recordsTotal" => 0,
"recordsFiltered" => 0,
"data" => array()
);
$authService =$authService;
if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
$data = $this->getDoctrine()->getManager()->getRepository(SupportTicketEntity::class)->ajaxListByUser($get, $authService->getUser());
foreach($data['results'] as $row) {
$url = $this->generateUrl('dashboard_support_ticket_details', array(
'id' => base64_encode($row['id'])
));
$action = "<a class='action-button-style' href='$url'>Review Ticket</a>" ;
if($authService->getUser()->getType() == 'Super Admin'){
$values = array(
$row['id'],
$row['name'],
$row['email'],
$row['title'],
$row['message'],
$action
);
} else {
$values = array(
$row['id'],
$row['title'],
$row['message'],
$action
);
}
$result['data'][] = $values;
}
$result['recordsTotal'] = $data['total'];
$result['recordsFiltered'] = $data['total'];
return new JsonResponse($result);
}
#[Route("/user_notification_lists", name:"ajax_user_notification_lists")]
public function user_notification_listsAction(Request $request, AuthService $authService)
{
$result = array("success" => true);
if(!$authService->isLoggedIn()){
$result['success'] = false;
$result['msg'] = 'Opps something went wrong please try again later.';
} else {
$em = $this->getDoctrine()->getManager();
$notifications = $em->getRepository(NotificationEntity::class)->findBy(['user' => $authService->getUser()->getId()], ['createdAt' => 'DESC']);
$newNotications = $em->getRepository(NotificationEntity::class)->findBy(['user' => $authService->getUser()->getId(), 'status' => 'New']);
$result['html'] = $this->renderView('Ajax/user_notification_lists.html.twig', ['notifications' => $notifications]);
$result['ctr'] = count($newNotications);
}
return new JsonResponse($result);
}
#[Route("/user_notification_list", name:"ajax_user_notification_list")]
public function user_notification_listAction(Request $request, AuthService $authService)
{
$get = $request->query->all();
$result = array(
"draw" => intval($get['draw']),
"recordsTotal" => 0,
"recordsFiltered" => 0,
"data" => array()
);
$authService =$authService;
if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
$data = $this->getDoctrine()->getManager()->getRepository(NotificationEntity::class)->ajaxListByUser($get, $authService->getUser());
foreach($data['results'] as $row) {
$url = $this->generateUrl('dashboard_notification_details', array(
'id' => base64_encode($row['id'])
));
$action = "<a class='action-button-style' href='$url' " . ( $row['status'] != 'New' ? 'style="color:#858796;"' : '') ." >View</a>" ;
$values = array(
$row['type'],
$row['message'],
$action
);
$result['data'][] = $values;
}
$result['recordsTotal'] = $data['total'];
$result['recordsFiltered'] = $data['total'];
return new JsonResponse($result);
}
#[Route("/banned_user_list", name:"ajax_banned_user_list")]
public function banned_user_listAction(Request $request, AuthService $authService)
{
$get = $request->query->all();
$result = array(
"draw" => intval($get['draw']),
"recordsTotal" => 0,
"recordsFiltered" => 0,
"data" => array()
);
$authService =$authService;
if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
if($authService->getUser()->getType() == 'Super Admin') {
$data = $this->getDoctrine()->getManager()->getRepository(BannedUserEntity::class)->ajax_list($get);
foreach($data['results'] as $row) {
$values = array(
$row['name'],
$row['email']
);
$result['data'][] = $values;
}
$result['recordsTotal'] = $data['total'];
$result['recordsFiltered'] = $data['total'];
}
return new JsonResponse($result);
}
#[Route("/user_autocomplete", name:"user_autocomplete")]
public function user_autocomplete_suggestions(Request $request, AuthService $authService) {
$q = $request->get('query');
$result = array(
'query' => 'descriptions',
'suggestions' => $this->getDoctrine()->getManager()->getRepository(UserEntity::class)->autocomplete_suggestions($q)
);
return new JsonResponse($result);
}
#[Route("/transaction_form", name:"ajax_transaction_form")]
public function transaction_formAction(Request $request, AuthService $authService, BlockIoService $blockIoService)
{
$result = array();
if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
if($request->getMethod() == 'POST'){
$formData = $request->request->get('formData');
$errors = '';
if($formData['tokenAmt'] < 1500){
$errors .= 'The minimum amount per transaction is 1,500.' . '\n';
}
if(!in_array(strtoupper($formData['network']), ['BTC' , 'LTC', 'DOGE', 'ETH'])){
$errors .= 'Opps something went wrong please try again.' . '\n';
}
if(!empty($errors)){
$result['success'] = false;
$result['msg'] = $errors;
} else {
$em = $this->getDoctrine()->getManager();
$label = time() . '-' . $this->generateRandomString();
$walletAddress = 'ltc1qmzvkz3j2f75u3wa8lyfghs43xffc83cjvprmtc';
// if($formData['network'] == 'eth'){
// $walletAddress = '0x361d637c55752d95339b5b179c534adb2ae542f8';
// } else {
// $generatedWallet = $blockIoService->generateWallet($formData['network'], $label);
// $walletAddress = $generatedWallet->data->address;
// }
$networkPriceInUsd = $blockIoService->getNetworkPrice($formData['network']);
$tokenUsdValue = $this->getParameter('app.token_dollar_value');
$tokenNetworkValue = (float) $tokenUsdValue / (float) $networkPriceInUsd;
$newOrderToken = new UserOrderTokenEntity();
$newOrderToken->setTokenValue($tokenNetworkValue);
$newOrderToken->setTokenAmount($formData['tokenAmt']);
$newOrderToken->setLabel($label);
$newOrderToken->setAddress($walletAddress);
$newOrderToken->setAmount($tokenNetworkValue * (float) $formData['tokenAmt']);
$newOrderToken->setNetwork(strtoupper($formData['network']));
$newOrderToken->setUser($authService->getUser());
$em->persist($newOrderToken);
$em->flush();
$notification = new NotificationEntity();
$notification->setType('Token Order Placed');
$notification->setMessage('Your Token Order ' .$formData['tokenAmt'] . 'Has Been Received');
$notification->setUser($authService->getUser());
$em->persist($notification);
$em->flush();
$pb = $em->getRepository(BonusEntity::class)->findOneBy(array('code' => 'PB'));
$result['success'] = true;
$result['token_amount'] = $newOrderToken->getTokenAmount();
$result['bonus_token'] = $newOrderToken->getTokenAmount() * ( $pb->getBonusPercent() / 100);
$result['view'] = $this->renderView('Ajax/order_preview.html.twig',array(
'network' => $newOrderToken->getNetwork(),
'amount' => $newOrderToken->getAmount(),
'label' => str_replace( '-', '', $newOrderToken->getLabel()),
'token_amount' => $newOrderToken->getTokenAmount(),
'address' => $newOrderToken->getAddress(),
'bonus_token' => $newOrderToken->getTokenAmount() * ( $pb->getBonusPercent() / 100)
));
$result['view2'] = $this->renderView('Ajax/order_preview2.html.twig',array(
'network' => $newOrderToken->getNetwork(),
'amount' => $newOrderToken->getAmount(),
'label' => str_replace( '-', '', $newOrderToken->getLabel()),
'token_amount' => $newOrderToken->getTokenAmount(),
'address' => $newOrderToken->getAddress(),
'bonus_token' => $newOrderToken->getTokenAmount() * ( $pb->getBonusPercent() / 100)
));
}
}
return new JsonResponse($result);
}
#[Route("/transaction_details", name:"ajax_transaction_details")]
public function transaction_detailsAction(Request $request, AuthService $authService)
{
$result = array(
'success' => true
);
$authService =$authService;
if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
if($request->getMethod() == 'POST'){
$id = $request->request->get('id');
$em = $this->getDoctrine()->getManager();
$order = $em->getRepository(UserOrderTokenEntity::class)->find($id);
$pb = $em->getRepository(BonusEntity::class)->findOneBy(array('code' => 'PB'));
if(!$order){
$result['success'] = false;
$result['msg'] = 'Something went wrong please try again.';
} else {
$result['success'] = true;
$result['view'] = $this->renderView('Ajax/order_preview2.html.twig',array(
'network' => $order->getNetwork(),
'amount' => $order->getAmount(),
'label' => str_replace( '-', '', $order->getLabel()),
'token_amount' => $order->getTokenAmount(),
'address' => $order->getAddress(),
'bonus_token' => $order->getTokenAmount() * ( $pb->getBonusPercent() / 100),
'status' => $order->getStatus()
));
}
}
return new JsonResponse($result);
}
private function generateRandomString($length = 6) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
$em = $this->getDoctrine()->getManager();
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
$orderTokenAddressExists = $em->getRepository(UserOrderTokenEntity::class)->findOneBy(array('label' => $randomString));
if($orderTokenAddressExists){
$this->generateRandomString();
}
return $randomString;
}
#[Route("/kyc_application", name:"ajax_kyc_application")]
public function kyc_applicationAction(Request $request, AuthService $authService)
{
$get = $request->query->all();
$result = array(
"draw" => intval($get['draw']),
"recordsTotal" => 0,
"recordsFiltered" => 0,
"data" => array()
);
$authService =$authService;
if(!$authService->isLoggedIn()) return $authService->redirectToLogin();
if($authService->getUser()->getType() == 'Super Admin') {
$data = $this->getDoctrine()->getManager()->getRepository(UserEntity::class)->kyc_application($get);
foreach($data['results'] as $row) {
$values = array(
$row['name'],
$row['birthDate'],
$row['address'],
"<a href='/uploads/file/".urlencode($row['id'])."'>".$row['id']."</a>",
"<a href='/manage/kyc_application_verification?status=confirm&id=".$row['uid']."'>Confirm</a> | <a href='/ajax/kyc_application_verification?status=reject&id=".$row['uid']."'>Reject</a>"
);
$result['data'][] = $values;
}
$result['recordsTotal'] = $data['total'];
$result['recordsFiltered'] = $data['total'];
}
return new JsonResponse($result);
}
#[Route("/upload_profile_photo", name:"ajax_upload_profile_photo")]
public function upload_profile_photoAction(Request $request, AuthService $authService)
{
$result = array(
'success' => false
);
if(!$authService->isLoggedIn()){
$result['msg'] = 'Unauthorized access please contact Administrator';
} else {
$user = $authService->getUser();
if($request->getMethod() == 'POST'){
if(isset($_FILES['profile-img']) && !empty($_FILES['profile-img']['tmp_name'])) {
$basename = $user->getId() . '-' . time() . '.' . pathinfo($_FILES['profile-img']['name'], PATHINFO_EXTENSION);
$uploadFile = $user->getUploadRootDir() . '/' . $baseName;
if(move_uploaded_file($_FILES['profile-img']['tmp_name'], $uploadFile)) {
$em = $this->getDoctrine()->getManager();
$user->setIdFile($_FILES['profile-img']['name']);
$user->setIdFileParse($baseName);
$em->flush();
}
$result['success'] = true;
}
} else {
$result['msg'] = 'Oppps something went wrong please try again';
}
}
return new JsonResponse($result);
}
#[Route("/country_holder_list", name:"ajax_country_holder_list")]
public function countryHolderListAction(Request $request, AuthService $authService, BlockIoService $blockIoService)
{
$result = array();
if(!$authService->isLoggedIn()){
$result['success'] = false;
$result['msg'] = 'Unauthorize access please call a system administrator.';
return new JsonResponse($result);
}
$em = $this->getDoctrine()->getManager();
$countryHolders = $em->getRepository(UserEntity::class)->countryHolders();
$result['success'] = true;
$result['html'] = $this->renderView('Ajax/country_holder_list.html.twig',array(
'tokenSupply' => $this->getParameter('app.token_supply'),
'countryHolders' => $countryHolders
));
return new JsonResponse($result);
}
#[Route("/user_wallet_transaction_list", name:"ajax_user_wallet_transaction_list")]
public function user_wallet_transaction_listAction(Request $request, AuthService $authService, SessionInterface $session)
{
$get = $request->query->all();
$result = array(
'success' => true
);
$userData = $session->get('userData');
$data = $request->query->all();
if(!$authService->isLoggedIn()){
return new JsonResponse([
'success' => false,
'message' => 'Unauthorized access please contact a System Administrator.'
]);
}
$em = $this->getDoctrine()->getManager();
$transactions = $em->getRepository(UserEntity::class)->walletTransaction($userData, $data);
$result['html'] = $this->renderView('Ajax/user_wallet_transaction_list.html.twig', [
'transactions' => $transactions
]);
return new JsonResponse($result);
}
}