<?php
namespace App\Controller;
use App\Entity\Clinic\Clinic;
use App\Entity\Clinic\Person\ClinicUser;
use App\Entity\Domain;
use App\Entity\Website;
use App\Entity\Person\Setting;
use App\Entity\Media\Media;
use App\Services\MediaManager;
use App\Aws\SESManager;
use App\Aws\S3Manager;
use App\Entity\Meeting;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Psr\Log\LoggerInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use App\Entity\Person\SuperClinicAdmin;
use App\Entity\Person\User;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
/**
* Class MessageController.
*/
class MessageController extends AbstractController
{
/**
* @var SerializerInterface
*/
private $serializer;
/**
* @var LoggerInterface
*/
private $logger;
/**
* @var SESManager
*/
private $SESManager;
/**
* @var MediaManager
*/
private $mediaManager;
/**
* @var Filesystem
*/
private $filesystem;
/**
* @var string
*/
/**
* @var S3Manager
*/
private $s3Manager;
public function __construct(LoggerInterface $logger,SerializerInterface $serializer, SESManager $SESManager, MediaManager $mediaManager, S3Manager $s3Manager, Filesystem $filesystem)
{
$this->logger = $logger;
$this->SESManager = $SESManager;
$this->mediaManager = $mediaManager;
$this->filesystem = $filesystem;
$this->s3Manager = $s3Manager;
$this->serializer = $serializer;
@date_default_timezone_set(@$_COOKIE['tz']);
}
/**
* @Route("/admin/message/index", name="index")
*/
public function index(Request $request): Response
{
// dd($_COOKIE);
$data = [];
$data['convId'] = (@$_GET['conv_id'] > 0) ? $_GET['conv_id'] : 0;
$data['user'] = $this->getUser();
$data['needLicense'] = false;
if ($data['user']->getRole() != 'ROLE_CONSENTZ_ADMIN') {
if ($data['user']->getClinic() != null) {
$data['clinic'] = $this->getDoctrine()->getRepository(Clinic::class)
->find($data['user']->getClinic());
} else if ($data['user']->getOrganisation() && $data['user']->getOrganisation()->getClinics()->count() > 0 && $data['user']->getRole() == 'ROLE_SUPER_CLINIC_ADMIN') {
$data['clinic'] = $data['user']->getOrganisation()->getClinics()->first();
}
if ($data['clinic']) {
return new RedirectResponse($this->generateUrl('clinic_message_index', ['clinicId' => $data['clinic']->getId()]));
}
return $this->render('message/index.html.twig', $data);
}else{
if($request->get('clinic') > 0){
$clinic = $this->getDoctrine()->getRepository(Clinic::class)
->find( $request->get('clinic'));
$user = $this->getDoctrine()->getRepository(ClinicUser::class)->findOneBy([
'clinic' =>$clinic,
'deleted' => false,
'locked' => false,
'role' => User::ROLE_SUPER_CLINIC_ADMIN
]);
if (!$user && $clinic->getOrganisation()) {
$user = $clinic->getOrganisation()->getAdmins()->first();
}
return new RedirectResponse($this->generateUrl('messagestart') . '?user_id=' . $user->getId());
}
return $this->render('message/admin_index.html.twig', $data);
}
}
/**
* @Route("/admin/message/index/{clinicId}", name="clinic_message_index")
*/
public function clinic_message_index(Request $request, $clinicId): Response
{
$em = $this->getDoctrine()->getManager();
$sql ="UPDATE `template_library` SET `category_id` = ? WHERE `template_library`.`id` = ? ";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([2,99]);
$data = [];
$data['convId'] = (@$_GET['conv_id'] > 0) ? $_GET['conv_id'] : 0;
$data['user'] = $this->getUser();
$data['needLicense'] = false;
if ($data['user']->getRole() != 'ROLE_CONSENTZ_ADMIN') {
$myClinic = false;
if ($data['user']->getOrganisation() && $data['user']->getOrganisation()->getClinics()->count() > 0 && $data['user']->getRole() == 'ROLE_SUPER_CLINIC_ADMIN') {
foreach ($data['user']->getOrganisation()->getClinics() as $cl) {
if ($cl->getId() == $clinicId) {
$myClinic = true;
break;
}
}
} else if ($data['user']->getClinic() != null) {
if ($data['user']->getClinic()->getId() == $clinicId) {
$myClinic = true;
}
}
if (!$myClinic) {
return new JsonResponse(['status' => 'error', 'message' => 'Clinic Not Exist']);
}
$data['clinic'] = $this->getDoctrine()->getRepository(Clinic::class)
->find($clinicId);
if (!$data['clinic']) {
return new RedirectResponse($this->generateUrl('message_index'));
}
}
$clinic = $data['clinic'];
if($clinic->getOrganisation()) {
if($clinic->getOrganisation()->isEnableFeatureLicensingMessage()) {
if(!$clinic->hasLicense(Clinic::FEATURE_MESSAGE)) {
$data['needLicense'] = true;
//return $this->redirectToRoute('need_feature_license', ['clinic' => $clinic->getId(), 'featureCode' => Clinic::FEATURE_MESSAGE]);
}
}
}
return $this->render('message/index.html.twig', $data);
}
/**
* @Route("/admin/message/start", name="messagestart")
*/
public function messagestart(Request $request): Response
{
$opponantId = @$_GET['user_id'];
$data = $this->startNewConversation($opponantId);
if ($request->isXmlHttpRequest()) {
return new JsonResponse($data);
} else {
if ($data['status'] == 1) {
return new RedirectResponse($this->generateUrl('message_index') . '?conv_id=' . $data['convId']);
} else {
return new RedirectResponse($this->generateUrl('message_index'));
}
}
}
/**
* @Route("/admin/message/conversation_list", name="conversation_list")
*/
public function conversation_list(Request $request): Response
{
$user = $this->getUser();
$userId = $user->getId();
$filter = $request->get('filter');
$section = ($request->get('section') > 0) ? $request->get('section') : 0;
$offset = ($request->get('offset') > 0) ? $request->get('offset') : 0;
$em = $this->getDoctrine()->getManager();
$adminConversation = [];
if($user->getRole() != 'ROLE_CONSENTZ_ADMIN'){
$sql = "select id from user where deleted=? and role =?";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([0,'ROLE_CONSENTZ_ADMIN']);
$admins = $ap->fetchAll();
$adminIds = array_column($admins, 'id');
foreach($adminIds as $adminId){
$params = [];
$adminsSql = 'select c.*,m.message,m.type as msgtype from conversation as c left join chat_messages as m on m.id=c.last_chat_id left join user as u on IF(c.from_user_id=?,u.id=c.to_user_id,u.id=c.from_user_id) where FIND_IN_SET(?, c.user_ids) AND FIND_IN_SET(?, c.user_ids) and c.type=? ';
$params[] = $userId;
$params[] = $userId;
$params[] = $adminId;
$params[] = 0;
if ($filter['search'] != '') {
$adminsSql .= ' and (u.first_name like ? or u.last_name like ? or u.email like ? or u.username like ? or c.title like ?)';
$params[] = '%' . trim($filter['search']) . '%';
$params[] = '%' . trim($filter['search']) . '%';
$params[] = '%' . trim($filter['search']) . '%';
$params[] = '%' . trim($filter['search']) . '%';
$params[] = '%' . trim($filter['search']) . '%';
}
$ap = $em->getConnection()->prepare($adminsSql);
$ap->execute($params);
$adminConv = $ap->fetchAssociative();
if($adminConv){
$adminConversation[] = $adminConv;
}
break;
}
$adminConvIds = array_column($adminConversation, 'id');
}else{
$adminConvIds = [];
}
$userRole=$user->getRole();
//end here
$limit = 50;
$query['select'] = 'c.*,m.message,m.type as msgtype';
$query['query'] = 'from conversation as c ';
$query['query'] .= 'left join chat_messages as m on m.id=c.last_chat_id ';
$query['params'] = [];
if ($filter['search'] != '') {
$query['query'] .= 'left join user as u1 on (c.from_user_id=? and u1.id=c.to_user_id) ';
$query['params'][] = $userId;
$query['query'] .= 'left join user as u2 on (c.from_user_id!=? and u2.id=c.from_user_id) ';
$query['params'][] = $userId;
$query['query'] .= ' where (u1.first_name like ? or u2.first_name like ? or u1.last_name like ? or u1.email like ? or u1.username like ? or u2.last_name like ? or u2.email like ? or u2.username like ? or c.title like ?) '; //
$query['params'][] = '%' . trim($filter['search']) . '%';
$query['params'][] = '%' . trim($filter['search']) . '%';
$query['params'][] = '%' . trim($filter['search']) . '%';
$query['params'][] = '%' . trim($filter['search']) . '%';
$query['params'][] = '%' . trim($filter['search']) . '%';
$query['params'][] = '%' . trim($filter['search']) . '%';
$query['params'][] = '%' . trim($filter['search']) . '%';
$query['params'][] = '%' . trim($filter['search']) . '%';
$query['params'][] = '%' . trim($filter['search']) . '%';
$query['query'] .= ' and FIND_IN_SET(?,c.user_ids) ';
$query['params'][] = $userId;
} else {
$query['query'] .= ' where FIND_IN_SET(?,c.user_ids) ';
$query['params'][] = $userId;
}
$query['query'] .= 'AND (c.deleted_by IS NULL OR NOT FIND_IN_SET(?,c.deleted_by)) ';
$query['params'][] = $userId;
if(!empty($adminConversation)){
$query['query'] .= ' and c.id NOT IN (' . implode(',', array_fill(0, count($adminConvIds), '?')) . ') order by c.updated_at desc';
$query['params'] = array_merge($query['params'],$adminConvIds);
}else{
$query['query'] .= ' order by c.updated_at desc';
}
$query['query'] .= ' limit ' . $limit . ' offset ' . $offset . ' ';
$ap = $em->getConnection()->prepare('select ' . $query['select'] . ' ' . $query['query']);
$ap->execute($query['params']);
$conversations = $ap->fetchAll();
$convList = [];
if(!empty($adminConversation) && $offset == 0){
$conversations = array_merge($adminConversation,$conversations);
}
$offset = count($conversations) + $offset;
$hasMore = false;
if ($limit <= count($conversations)) {
$hasMore = true;
}
foreach ($conversations as $conversation) {
if ($conversation['type'] == 0) {
if ($conversation['from_user_id'] == $userId) {
$opponantId = $conversation['to_user_id'];
} else {
$opponantId = $conversation['from_user_id'];
}
$sql = "select user.*,media.url from user left join media on media.id=user.media_id where user.id = ?";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$opponantId]);
$userData = $ap->fetchAssociative();
if (!$userData) {
continue;
}
// dd($userData);
$conversation['title'] = $userData['first_name'] . ' ' . $userData['last_name'];
$conversation['slug'] = $userData['username'];
$conversation['is_online'] = $userData['is_online'];
$conversation['is_available'] = 1;
$conversation['is_online_class'] = ($userData['is_online'] == 1) ? 'greendot' : 'reddot';
$conversation['group_tag'] = '';
$conversation['thumb'] = ($userData['profile_img'] != '') ? $userData['profile_img'] : (($userData['url'] != '')?$userData['url']:'/images/Clinic/solid_gray.png');
$conversation['group_class'] = '';
$conversation['delete_class'] = $userData['role'] == 'ROLE_CONSENTZ_ADMIN'?'withdelete'.(in_array($conversation['id'],$adminConvIds)?' pinnedchat':''):'';
} else {
$conversation['title'] = $conversation['title'];
if ($conversation['clinic_id'] > 0) {
$conversation['group_tag'] = "<span class='badge badge-infobg'>Clinic</span>";
$conversation['delete_class'] = 'withdelete';
} else {
$conversation['group_tag'] = "<span class='badge badge-blue'>Group</span>";
$conversation['delete_class'] = ($user->getRole() == 'ROLE_CONSENTZ_ADMIN' || ($userId == $conversation['from_user_id'])) ? '' : 'withdelete';
}
$conversation['slug'] = '';
$conversation['is_online'] = 0;
$conversation['is_available'] = 0;
$conversation['is_online_class'] = '';
$conversation['group_class'] = 'withbtn';
}
$opponantId = $conversation['from_user_id'] == $userId ? $conversation['to_user_id'] : $conversation['from_user_id'];
$sql = "select count(*) as unread_count from chat_messages where conversation_id =? and not FIND_IN_SET(?,read_user_ids)";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$conversation['id'], $userId]);
$unreadCount = $ap->fetchAssociative();
$time = '';
$msg_date = '';
$msg_time = '';
if($conversation['updated_at']){
$time = ($conversation['updated_at'] > (time() - 86400)) ? date('h:i A', $conversation['updated_at']) : date('Y-m-d h:i A', $conversation['updated_at']);
$msg_date = ($conversation['updated_at'] > (time() - 86400)) ? '' : date('Y-m-d', $conversation['updated_at']);
$msg_time = ($conversation['updated_at'] > (time() - 86400)) ? date('h:i A', $conversation['updated_at']) : date('h:i A', $conversation['updated_at']);
}else if ($conversation['created_at']) {
$time = ($conversation['created_at'] > (time() - 86400)) ? date('h:i A', $conversation['created_at']) : date('Y-m-d h:i A', $conversation['created_at']);
$msg_date = ($conversation['created_at'] > (time() - 86400)) ? '' : date('Y-m-d', $conversation['created_at']);
$msg_time = ($conversation['created_at'] > (time() - 86400)) ? date('h:i A', $conversation['created_at']) : date('h:i A', $conversation['created_at']);
}
if ($conversation['msgtype'] == 2) {
$message = '[Call]';
} else if ($conversation['msgtype'] == 1) {
$message = '[File]';
} else {
$message = $conversation['message'] ? $conversation['message'] : '';
}
if(isset($unreadCount['unread_count']) && $unreadCount['unread_count']){
$this->receiveMessages($em,$userId,$conversation['id']);
}
$convList[] = [
'conv_id' => $conversation['id'],
'conv_type' => $conversation['type'],
'conv_user_ids' => $conversation['user_ids'],
'user_id' => ($conversation['type'] == 0) ? $opponantId : '',
'image' => ($conversation['type'] == 0) ? $conversation['thumb'] : (($conversation['g_image'] != '') ? $conversation['g_image'] : '/images/Clinic/solid_gray.png'),
'name' => $conversation['title'],
'slug' => $conversation['slug'],
'group_tag' => $conversation['group_tag'],
'message' => $message,
'date_msg' => $msg_date ? $msg_date : '',
'time_msg' => $msg_time ? $msg_time : '',
'created_at' => $time,
'unread_count' => isset($unreadCount['unread_count']) && $unreadCount['unread_count'] ? $unreadCount['unread_count'] : '',
'is_online' => ($conversation['is_online'] == 1) ? 1 : 0,
'is_online_class' => $conversation['is_online_class'],
'group_class' => $conversation['group_class'],
'delete_class' => $conversation['delete_class']
];
}
return new JsonResponse(['status' => 1, 'data' => $convList, 'hasMore' => $hasMore, 'offset' => $offset, 'role'=>$userRole]);
}
/**
* @Route("/admin/message/get_total_unread_messages", name="getTotalUnreadMessage")
*/
public function getTotalUnreadMessage(Request $request)
{
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
$clinic = $request->get('clinic');
$sql = "SELECT cm.* FROM `chat_messages` as cm join conversation as c on c.id=cm.conversation_id where not FIND_IN_SET(?,cm.read_user_ids) and FIND_IN_SET(?,c.user_ids) limit 1";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$user->getId(),$user->getId()]);
$chatMessages = $ap->fetchAssociative();
if($clinic > 0){
$sql = "SELECT c.*,pc.clinic_id FROM communication as c join patient_conversation as pc on pc.id=c.conversation_id where pc.clinic_id=? and c.read_status=0 and c.sender_type=? LIMIT 1";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$clinic,1]);
$patientMessages = $ap->fetchAssociative();
$sql = "SELECT c.*,pc.clinic_id FROM prospect_communication as c join prospect_conversation as pc on pc.id=c.conversation_id where pc.clinic_id=? and c.read_status=0 and c.sender_type=? LIMIT 1";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$clinic,1]);
$prospectMessages = $ap->fetchAssociative();
}else{
$patientMessages = NULL;
$prospectMessages = NULL;
}
return new JsonResponse(['chat_unread' => $chatMessages?1:0, 'patient_unread' => $patientMessages?1:0, 'prospect_unread' => $prospectMessages?1:0]);
}
/**
* @Route("/admin/message/list", name="message_list")
*/
public function message_list(Request $request): Response
{
$user = $this->getUser();
$userId = $user->getId();
$em = $this->getDoctrine()->getManager();
$convId = $request->get('conv_id');
$offset = $request->get('offset');
$sql = "select * from conversation where id = ? and FIND_IN_SET(?,user_ids)";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$convId,$userId]);
$conversation = $ap->fetchAssociative();
if (!$conversation) {
return new JsonResponse(['status' => 0, 'message' => 'Conversation Not Found']);
}
$limit = 50;
$query['select'] = "m.*,concat(u.first_name,' ',u.last_name) as name ,u.profile_img as image,media.url as media_url ";
$query['query'] = 'from chat_messages as m ';
$query['query'] .= 'left join user as u on u.id=m.from_user_id ';
$query['query'] .= 'left join media on u.media_id=media.id ';
$query['params'] = [];
$query['query'] .= 'where m.conversation_id=?';
$query['query'] .= 'AND (m.deleted_by IS NULL OR m.deleted_by NOT LIKE ?) ';
$query['query'] .= 'order by m.created_at desc';
$query['params'] = [$convId,'%'.$userId.'%'];
$query['query'] .= ' limit ' . $limit . ' offset ' . $offset . ' ';
$ap = $em->getConnection()->prepare('select ' . $query['select'] . ' ' . $query['query']);
$ap->execute($query['params']);
$messageList = $ap->fetchAll();
foreach ($messageList as $k => $message) {
$message['chat_id'] = $message['id'];
$message['receive_status'] = '';
if($conversation['type'] == 1){
$read_ids = explode(',', @$message['read_user_ids']);
$receiver_ids = explode(',', @$message['receiver_ids']);
$conversation_ids = explode(',', @$conversation['user_ids']);
$hasBeenRead = empty(array_diff($conversation_ids, $read_ids));
if(!$hasBeenRead){
$hasBeenReceived = empty(array_diff($conversation_ids, $receiver_ids));
if($hasBeenReceived){
$message['receive_status'] = 'delivered';
}
}else{
$message['receive_status'] = 'read';
}
}else{
if($message['from_user_id'] == $userId){
$hasBeenRead = in_array($message['to_user_id'],explode(',', $message['read_user_ids']));
if(!$hasBeenRead){
$hasBeenReceived = in_array($message['to_user_id'],explode(',', @$message['receiver_ids']));
if($hasBeenReceived){
$message['receive_status'] = 'delivered';
}
}else{
$message['receive_status'] = 'read';
}
}
}
$messageList[$k] = $this->setData($message, $userId);
}
$messageList = array_reverse($messageList);
try {
$sql = "UPDATE `chat_messages` SET `status` = 1 WHERE `conversation_id`=? and `to_user_id`=? ";
$appointment = $em->getConnection()->prepare($sql);
$appointment->execute([$convId, $userId]);
} catch (\Exception $e) {
}
try {
$sql = "UPDATE `chat_messages` SET `read_user_ids` =concat(read_user_ids,',$userId') WHERE `conversation_id`=? and not FIND_IN_SET(?,read_user_ids) ";
$appointment = $em->getConnection()->prepare($sql);
$appointment->execute([$convId, $userId]);
} catch (\Exception $e) {
}
return new JsonResponse(['status' => 1, 'conversation_id' => $convId, 'data' => $messageList, 'offset' => $offset + 50]);
}
/**
* @Route("/admin/message/read", name="message_read")
*/
public function message_read(Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$convId = $request->get('conv_id');
$user = $this->getUser();
$userId = $user->getId();
$sql = "UPDATE `conversation` SET `status` = 1 WHERE `id`=? and status=0 and to_user_id=?";
$appointment = $em->getConnection()->prepare($sql);
$appointment->execute([$convId, $userId]);
$sql = "UPDATE `chat_messages` SET `read_user_ids` =concat(read_user_ids,',$userId') WHERE `conversation_id`=? and not FIND_IN_SET(?,read_user_ids) ";
$appointment = $em->getConnection()->prepare($sql);
$appointment->execute([$convId, $userId]);
return new JsonResponse(['status' => 1, 'message' => 'success']);
}
/**
* @Route("/admin/message/receive", name="message_receive")
*/
public function message_receive(Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$convId = $request->get('conv_id');
$user = $this->getUser();
$userId = $user->getId();
$sql = "UPDATE `conversation` SET `status` = 1 WHERE `id`=? and status=0 and to_user_id=?";
$appointment = $em->getConnection()->prepare($sql);
$appointment->execute([$convId, $userId]);
$this->receiveMessages($em,$userId,$convId);
return new JsonResponse(['status' => 1, 'message' => 'success']);
}
private function receiveMessages($em,$userId,$convId){
$sql = "UPDATE `chat_messages` SET `receiver_ids` =concat(receiver_ids,',$userId') WHERE from_user_id != ? and `conversation_id`=? and not FIND_IN_SET(?,receiver_ids) and not FIND_IN_SET(?,read_user_ids) ";
$appointment = $em->getConnection()->prepare($sql);
$appointment->execute([$userId,$convId, $userId, $userId]);
return;
}
/**
* @Route("/admin/message/popup_read", name="message_popupread")
*/
public function message_popupread(Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$popup_id = $request->get('popup_id');
$user = $this->getUser();
$userId = $user->getId();
$sql = "UPDATE `advertisements` SET `read_user_ids` =concat(read_user_ids,',$userId') WHERE `id`=? and
not FIND_IN_SET(?,read_user_ids) ";
$appointment = $em->getConnection()->prepare($sql);
$appointment->execute([$popup_id,$userId]);
return new JsonResponse(['status' => 1, 'message' => 'success']);
}
/**
* @Route("/admin/message/popup_unread", name="message_popupunread")
*/
public function message_popupunread(Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$popup_id = $request->get('popup_id');
$user = $this->getUser();
$userId = $user->getId();
$sql = "select * from advertisements where FIND_IN_SET(?,receiver_user_ids) and not FIND_IN_SET(?,read_user_ids)";
$appointment = $em->getConnection()->prepare($sql);
$appointment->execute([$userId, $userId]);
$popups = $appointment->fetchAll();
return new JsonResponse(['status' => 1, 'data' => $popups]);
}
/**
* @Route("/admin/message/send", name="message_send")
*/
public function message_send(Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
$userId = $user->getId();
$name='';
if($userId){
$sql = "select * from user where id=?";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$userId]);
$userData = $ap->fetchAssociative();
if ($userData) {
$name= $userData['first_name'] . ' ' . $userData['last_name'];
}
}
$convId = $request->get('conv_id');
$toUserId = $request->get('to_user_id');
$toUserId = ($toUserId > 0) ? $toUserId : 0;
$message = $request->get('message');
$type = $request->get('type');
$data = $request->get('data');
$data = isset($data) && $data ? json_encode($data) : '';
$time = time();
$sql = "select * from conversation where id = ? and FIND_IN_SET(?,user_ids)";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$convId,$userId]);
$conversation = $ap->fetchAssociative();
if (!$conversation) {
return new JsonResponse(['status' => 0, 'message' => 'Conversation Not Found']);
}
if ($conversation) {
$sql = "UPDATE `conversation` SET `deleted_by` = NULL WHERE `id`=?";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$convId]);
}
if ($conversation['type'] == 1) {
$toUserId = 0;
}
try {
$messageData = [
'conversation_id' => $convId,
'from_user_id' => $userId,
'name'=>$name,
'read_user_ids' => $userId,
'to_user_id' => @$toUserId,
'message' => $message,
'image' => ($user->getProfileImg() != '') ? $user->getProfileImg() : ($user->getMedia()?@$user->getMedia()->getUrl(): '/images/Clinic/solid_gray.png'),
'type' => $type,
'data' => $data,
'created_at' => $time
];
$sql = "INSERT INTO chat_messages (conversation_id, from_user_id, read_user_ids, to_user_id, message, type, data, created_at, receiver_ids)
VALUES (?,?,?,?,?,?,?,?,?)";
$messageInsert = $em->getConnection()->prepare($sql);
$messageInsert->execute([$convId, $userId, $userId, @$toUserId, $message, $type, $data, $time, $userId]);
$lastId = $em->getConnection()->lastInsertId();
$sql = "UPDATE `conversation` SET `last_chat_id` = ?,`updated_at`=? WHERE `id`=?";
$appointment = $em->getConnection()->prepare($sql);
$appointment->execute([$lastId, $time, $convId]);
$messageData['chat_id'] = $lastId;
$message_opponant = $this->setData($messageData, $toUserId);
$messageData['receive_status'] = '';
$message = $this->setData($messageData, $userId);
return new JsonResponse(['status' => 1, 'data' => $message, 'chat_opponant' => $message_opponant, 'conv_user_ids' => $conversation['user_ids']]);
} catch (\Exception $e) {
return new JsonResponse(['status' => 0, 'message' => $e->getMessage()]);
}
}
/**
* @Route("/admin/message/upload_file", name="message_upload_file")
*/
public function message_upload_file(Request $request)
{
// dd($request->files->get('file'));
$fileExtension = $request->files->get('file')->getClientOriginalExtension();
$allowedExtensions = ['jpeg', 'png', 'pdf', 'jpg', 'doc', 'docx', 'xls', 'xlsx', 'zip', 'wav', 'mp4', 'webp', 'mp3', 'mpeg','csv','webm','txt','ppt','pptx','mkv','avi'];
if (!in_array($fileExtension, $allowedExtensions)) {
return new JsonResponse(['status' => '0', 'message' => 'File not valid']);
}
try {
if ($request->files->has('file')) {
$file = $request->files->get('file');
$size = $file->getSize();
if ($size > 50 * 1024 * 1024) {
return $this->json(['status' => 0, 'message' => 'File size is not more than 50 MB'], Response::HTTP_BAD_REQUEST);
}
$fileMimeType = $file->getClientMimeType();
$originalName = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$uniqueFilename = md5(uniqid()) . time() . '.' . $extension;
$filePath = 'chat/' . date('Y') . '/' . date('m') . '/';
// dd($s);
$entityManager = $this->getDoctrine()->getManager();
$media = new Media();
$media->setFile($file);
$media->setNameFile(Media::getPrefixName($media->getFile()->getClientOriginalName()));
$media->setS3key($filePath . $uniqueFilename);
$this->s3Manager->upload($media);
// $entityManager->persist($media);
$entityManager->flush();
if ($media->getUrl() != '') {
$return = ['status' => 1, 'data' => ['name' => $originalName, 'media_url' => $media->getUrl(), 'file_name' => $uniqueFilename, 'extension' => $extension, 'size' => $size, 'type' => $fileMimeType]];
} else {
if (!is_dir($this->getParameter('kernel.project_dir') . '/public/uploads/chat')) {
mkdir($this->getParameter('kernel.project_dir') . '/public/uploads/chat');
}
if (!is_dir($this->getParameter('kernel.project_dir') . '/public/uploads/chat/' . date('Y'))) {
mkdir($this->getParameter('kernel.project_dir') . '/public/uploads/chat/' . date('Y'));
mkdir($this->getParameter('kernel.project_dir') . '/public/uploads/chat/' . date('Y') . '/' . date('m'));
}
if (!is_dir($this->getParameter('kernel.project_dir') . '/public/uploads/chat/' . date('Y') . '/' . date('m'))) {
mkdir($this->getParameter('kernel.project_dir') . '/public/uploads/chat/' . date('Y') . '/' . date('m'));
}
$s = $file->move($filePath, $uniqueFilename);
$appUrl = $_ENV['APP_URl'];
$return = ['status' => 1, 'data' => ['name' => $originalName, 'media_url' => $appUrl . $filePath . $uniqueFilename, 'file_name' => $uniqueFilename, 'extension' => $extension, 'size' => $size, 'type' => $fileMimeType]];
}
return new JsonResponse($return);
} else {
return new JsonResponse(['status' => '0', 'message' => 'File not found']);
}
} catch (\Exception $e) {
return new JsonResponse(['status' => '0', 'message' => $e->getMessage()]);
}
}
/**
* @Route("/admin/message/message_addchats", name="message_addchats")
*/
public function message_addchats(Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
$userId = $user->getId();
$data = [];
if ($user->getRole() == 'ROLE_CLINIC_ADMIN' || $user->getRole() == 'ROLE_SUPER_CLINIC_ADMIN' || $user->getRole() == 'ROLE_PRACTITIONER') {
$clinic = $user->getClinic();
if (!$clinic) {
$clinic = $this->getDoctrine()->getRepository(Clinic::class)
->findOneBy(['organisation_id' => $user->getOrganisation()->getId()]);
}
if ($clinic) {
$clinicId = $clinic->getId();
$organizationId = $clinic->getOrganisation()->getId();
$roles = ['ROLE_CLINIC_ADMIN', 'ROLE_PRACTITIONER', 'ROLE_SUPER_CLINIC_ADMIN'];
$rolesPlaceholder = implode(',', array_fill(0, count($roles), '?'));
$sql = "SELECT id,username,concat(first_name,' ',last_name) as name ,profile_img FROM user WHERE id !=? and deleted= ? AND ((role IN ($rolesPlaceholder) AND clinic_id = ?) OR organisation_id = ?)";
$ap = $em->getConnection()->prepare($sql);
$params = array_merge([$userId, 0], $roles);
$params[] = $clinicId;
$params[] = $organizationId;
$ap->execute($params);
$data = $ap->fetchAll();
}
}
if ($user->getRole() == 'ROLE_CONSENTZ_ADMIN') {
$sql = "select id,username,concat(first_name,' ',last_name) as name ,profile_img from user where deleted=0 and role in ('ROLE_SUPER_CLINIC_ADMIN','ROLE_CLINIC_ADMIN')";
$ap = $em->getConnection()->prepare($sql);
$ap->execute();
$data = $ap->fetchAll();
}
return $this->render('message/chat_create.html.twig', [
'userList' => $data,
]);
}
/**
* @Route("/admin/message/message_groupmodal", name="message_groupmodal")
*/
public function message_groupmodal(Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
$userId = $user->getId();
$data = [];
$userIds = [];
$sql = "select id,type,title,user_ids from conversation where FIND_IN_SET(?,user_ids)";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$userId]);
$conversationUsers = $ap->fetchAll();
$groups = [];
foreach ($conversationUsers as $conv) {
foreach (explode(',', $conv['user_ids']) as $uid) {
if ($uid && $uid != $userId && !in_array($uid, $userIds)) {
$userIds[] = $uid;
}
}
if ($conv['type'] == 1) {
$groups[] = ['chat_id' => $conv['id'], 'chat_title' => $conv['title']];
}
}
$data['userList'] = [];
if ($userIds) {
$placeholders = implode(',', array_fill(0, count($userIds), '?'));
$sql = "select id,username,concat(first_name,' ',last_name) as name ,profile_img from user where deleted=0 and id in($placeholders)";
$ap = $em->getConnection()->prepare($sql);
$ap->execute($userIds);
$data['userList'] = $ap->fetchAll();
}
$data['userClinicAdmins'] = [];
if ($user->getRole() == 'ROLE_CONSENTZ_ADMIN') {
$sql = "select id,username,concat(first_name,' ',last_name) as name ,profile_img from user where deleted=0 and role='ROLE_SUPER_CLINIC_ADMIN'";
$ap = $em->getConnection()->prepare($sql);
$ap->execute($userIds);
$data['userClinicAdmins'] = $ap->fetchAll();
}
// print_r($data);exit;
return $this->render('message/group_create.html.twig', [
'userList' => $data['userList'],
'groups' => $groups,
'userClinicAdmins' => $data['userClinicAdmins'],
'user' => $user
]);
}
/**
* @Route("/admin/message/message_groupcreate", name="message_groupcreate")
*/
public function message_groupcreate(Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
$userId = $user->getId();
$title = trim($request->get('title'));
$userIds = $request->get('user_ids');
$superUserIds = $request->get('super_user_ids');
$croppedImg = $request->get('croppedImage');
$groups = $request->get('groups');
$userIds = !empty($userIds) ? $userIds : [];
$superUserIds = !empty($superUserIds) ? $superUserIds : [];
if (!empty($groups)) {
$placeholders = implode(',', $groups);
$sql = "SELECT user_ids FROM conversation WHERE id IN ($placeholders)";
$ap = $em->getConnection()->prepare($sql);
$ap->execute();
$conversationUsers = $ap->fetchAll();
foreach ($conversationUsers as $conv) {
foreach (explode(',', $conv['user_ids']) as $uid) {
if ($uid && $uid != $userId && !in_array($uid, $userIds)) {
$userIds[] = $uid;
}
}
}
}
if (!empty($superUserIds)) {
foreach ($superUserIds as $superUserId) {
if ($superUserId && $superUserId != $userId && !in_array($superUserId, $userIds)) {
$userIds[] = $superUserId;
}
}
}
try {
if (!$title) {
return new JsonResponse(['status' => 0, 'message' => 'Title is required']);
}
if (empty($userIds) || count($userIds) < 1) {
return new JsonResponse(['status' => 0, 'message' => 'Please select multiple users']);
}
if (isset($croppedImg) && $croppedImg && $croppedImg != 'data:,') {
$imgData = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $croppedImg));
$parts = explode(';', $croppedImg);
$mimePart = explode(':', $parts[0]);
$imageType = $mimePart[1];
$extension = explode('/', $imageType)[1];
$uniqueFilename = md5(uniqid()) . time() . '.' . $extension;
$directory = $this->getParameter('kernel.project_dir') . '/public/uploads/chat/';
if (!is_dir($directory)) {
mkdir($directory, 0777, true);
}
$fileSaved = file_put_contents($directory . $uniqueFilename, $imgData);
$uploadPath = $directory . $uniqueFilename;
$targetFile = $this->changeFilePermission($uploadPath);
$file = new UploadedFile($targetFile, $uniqueFilename, 'image/png');
$entityManager = $this->getDoctrine()->getManager();
$media = new Media();
$media->setFile($file);
$media->setNameFile(Media::getPrefixName($media->getFile()->getClientOriginalName()));
$media->setS3key('groups/' . $uniqueFilename);
$this->s3Manager->upload($media);
$fileUpload = $media->getUrl();
$entityManager->flush();
if ($fileUpload == null) {
$fileUpload = $_ENV['APP_URl'] . 'uploads/chat/' . $uniqueFilename;
} else {
if (isset($uniqueFilename) && $uniqueFilename) {
if (file_exists($this->getParameter('kernel.project_dir') . '/public/uploads/chat/' . $uniqueFilename)) {
unlink($this->getParameter('kernel.project_dir') . '/public/uploads/chat/' . $uniqueFilename);
}
}
}
} else {
$fileUpload = '';
}
$userIds = implode(',', $userIds) . ',' . $userId;
$time = time();
$status = 1;
$sql = "INSERT INTO conversation (type, from_user_id, title, g_image, user_ids, status, created_at, updated_at)VALUES (?,?,?,?,?,?,?,?)";
$messageInsert = $em->getConnection()->prepare($sql);
$messageInsert->execute([1, $userId, $title, $fileUpload, $userIds, $status, $time, $time]);
return new JsonResponse(['status' => 1, 'message' => 'Group created']);
} catch (\Exception $e) {
return new JsonResponse(['status' => 0, 'message' => $e->getMessage()]);
}
}
/**
* @Route("/admin/message/conversation_details", name="conversation_details")
*/
public function conversation_details(Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
$userId = $user->getId();
$convId = $request->get('conv_id');
$sql = "select * from conversation where id = ?";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$convId]);
$conversation = $ap->fetchAssociative();
if ($conversation['type'] == 0) {
if ($conversation['from_user_id'] == $userId) {
$opponantId = $conversation['to_user_id'];
} else {
$opponantId = $conversation['from_user_id'];
}
$sql = "select user.*,media.url from user left join media on media.id=user.media_id where user.id = ?";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$opponantId]);
$userData = $ap->fetchAssociative();
if (!$userData) {
return new JsonResponse(['status' => 0, 'message' => 'Opponant not found']);
}
// dd($userData);
$conversation['user_id'] = $opponantId;
$conversation['title'] = $userData['first_name'] . ' ' . $userData['last_name'];
$conversation['is_online'] = $userData['is_online'];
$conversation['image'] = ($userData['profile_img'] != '') ? $userData['profile_img'] :( $userData['url'] != ''?$userData['url']:'/images/Clinic/solid_gray.png');
} else {
$conversation['title'] = $conversation['title'];
$conversation['user_id'] = 0;
$conversation['title'] = $conversation['title'];
$conversation['is_online'] = 0;
$conversation['image'] = ($conversation['g_image'] != '') ? $conversation['g_image'] : '/images/Clinic/solid_gray.png';
}
return new JsonResponse(['status' => 1, 'data' => $conversation]);
}
/**
* @Route("/admin/message/conversation_delete", name="conversation_delete")
*/
public function conversation_delete(Request $request): Response
{
$user = $this->getUser();
$userId = $user->getId();
$convId = $request->get('conv_id');
$em = $this->getDoctrine()->getManager();
// Fetch all chat messages for the given conversation ID
$sql = "SELECT id, deleted_by FROM conversation WHERE id = ?";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$convId]);
$conversions = $ap->fetchAll(); // Fetch all records in the conversation
foreach ($conversions as $conversion) {
$deletedBy = $conversion['deleted_by'];
$conversionId = $conversion['id'];
// Check if `deleted_by` is empty or does not contain the `userId`
if (empty($deletedBy)) {
// If `deleted_by` is empty, set it to `userId`
$updatedDeletedBy = $userId;
} elseif (strpos($deletedBy, (string)$userId) === false) {
// If `userId` is not in `deleted_by`, append it
$updatedDeletedBy = $deletedBy . ',' . $userId;
} else {
// If `userId` is already in `deleted_by`, no need to update
$updatedDeletedBy = $deletedBy;
}
// Only update if the value was modified
if ($updatedDeletedBy !== $deletedBy) {
$updateSql = "UPDATE conversation SET deleted_by = ? WHERE id = ?";
$updateStmt = $em->getConnection()->prepare($updateSql);
$updateStmt->execute([$updatedDeletedBy, $conversionId]);
}
}
// Fetch all chat messages for the given conversation ID
$sql = "SELECT id, deleted_by FROM chat_messages WHERE conversation_id = ?";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$convId]);
$messages = $ap->fetchAll(); // Fetch all records in the conversation
// Iterate through each message and update the `deleted_by` column
foreach ($messages as $message) {
$deletedBy = $message['deleted_by'];
$messageId = $message['id'];
// Check if `deleted_by` is empty or does not contain the `userId`
if (empty($deletedBy)) {
// If `deleted_by` is empty, set it to `userId`
$updatedDeletedBy = $userId;
} elseif (strpos($deletedBy, (string)$userId) === false) {
// If `userId` is not in `deleted_by`, append it
$updatedDeletedBy = $deletedBy . ',' . $userId;
} else {
// If `userId` is already in `deleted_by`, no need to update
$updatedDeletedBy = $deletedBy;
}
// Only update if the value was modified
if ($updatedDeletedBy !== $deletedBy) {
$updateSql = "UPDATE chat_messages SET deleted_by = ? WHERE id = ?";
$updateStmt = $em->getConnection()->prepare($updateSql);
$updateStmt->execute([$updatedDeletedBy, $messageId]);
}
}
// Return response after updating all messages
return new JsonResponse(['status' => 1, 'message' => 'Chat deleted']);
}
/**
* @Route("/admin/message/message_groupdetails", name="message_groupdetails")
*/
public function message_groupdetails(Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
$userId = $user->getId();
$convId = $request->get('conv_id');
$sql = "select * from conversation where id = ?";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$convId]);
$convList = $ap->fetchAssociative();
if ($convList['type'] == 1) {
if ($convList['from_user_id'] == $userId && $convList['clinic_id'] > 0) {
$this->addClinicMembersInGroup($convList);
}
$convUsers = explode(',', $convList['user_ids']);
$convUserData = [];
$placeholders = implode(',', array_fill(0, count($convUsers), '?'));
$ap = $em->getConnection()->prepare("SELECT user.id,user.first_name,user.last_name,user.username,user.profile_img,user.is_online,media.url FROM user left join media on media.id=user.media_id WHERE user.deleted=0 and user.id IN ($placeholders)");
$ap->execute($convUsers);
$users = $ap->fetchAll();
foreach ($users as $key => $u) {
$users[$key]['name'] = $u['first_name'] . ' ' . $u['last_name'];
$users[$key]['image'] = ($u['profile_img'] != '') ? $u['profile_img'] : ( $u['url'] != ''?$u['url']:'/images/Clinic/solid_gray.png');
$users[$key]['role'] = ($convList['from_user_id'] == $u['id']) ? 1 : 0;
$users[$key]['slug'] = $u['username'];
$users[$key]['online'] = ($u['is_online'] == 1) ? true : false;
}
return $this->render('message/group_chat_details.html.twig', [
'convList' => $convList,
'convUserData' => $users,
'userId' => $userId,
'user' => $user
]);
} else {
$oppoNantId = ($convList['from_user_id'] == $userId) ? $convList['to_user_id'] : $convList['from_user_id'];
$ap = $em->getConnection()->prepare("SELECT concat(u.first_name,' ',u.last_name) as fullname,c.name,u.role,u.profile_img,u.id,u.email,concat(u.country_code,'',u.phone) as phone,c.description,u.is_online as online,media.url
FROM user AS u
left join media on media.id=u.media_id
LEFT JOIN clinics AS c
ON (u.organisation_id IS NOT NULL AND c.organisation_id = u.organisation_id)
OR (u.organisation_id IS NULL AND c.id = u.clinic_id)
WHERE u.id = ?");
$ap->execute([$oppoNantId]);
$u = $ap->fetchAssociative();
$u['profile_img'] = ($u['profile_img'] != '') ? $u['profile_img'] : ( $u['url'] != ''?$u['url']:'/images/Clinic/solid_gray.png');
$ap = $em->getConnection()->prepare("SELECT id,title,g_image,clinic_id FROM `conversation` where FIND_IN_SET(?,user_ids) and FIND_IN_SET(?,user_ids) and type=1 order by updated_at desc;
");
$ap->execute([$oppoNantId, $userId]);
$groups = $ap->fetchAll();
return $this->render('message/chat_details.html.twig', [
'convList' => $convList,
'user' => $u,
'groups' => $groups
]);
}
}
/**
* @Route("/admin/message/groupupdatemodal", name="groupupdatemodal")
*/
public function groupupdatemodal(Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
$userId = $user->getId();
$convId = $request->get('conv_id');
$sql = "select * from conversation where id = ?";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$convId]);
$convList = $ap->fetchAssociative();
$convUsers = explode(',', $convList['user_ids']);
$userIds = [];
$sql = "select user_ids from conversation where FIND_IN_SET(?,user_ids)";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$userId]);
$convLists = $ap->fetchAll();
foreach ($convLists as $conv) {
foreach (explode(',', $conv['user_ids']) as $uid) {
if ($uid && $uid != $userId && !in_array($uid, $userIds)) {
$userIds[] = $uid;
}
}
}
$userList = [];
if ($userIds) {
$placeholders = implode(',', array_fill(0, count($userIds), '?'));
$sql = "select id,email,concat(first_name,' ',last_name) as name ,profile_img from user where deleted=0 and id in($placeholders)";
$ap = $em->getConnection()->prepare($sql);
$ap->execute($userIds);
$userList = $ap->fetchAll();
}
return $this->render('message/group_update.html.twig', [
'convList' => $convList,
'convLists' => $convLists,
'userId' => $userId,
'convUsers' => $convUsers,
'userList' => $userList
]);
}
/**
* @Route("/admin/message/groupupdateusers", name="groupupdateusers")
*/
public function groupupdateusers(Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$convId = $request->get('conv_id');
$userIds = $request->get('user_ids');
$sql = "select * from conversation where id = ?";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$convId]);
$convList = $ap->fetchAssociative();
if (empty($convList)) {
return new JsonResponse(['status' => 0, 'message' => 'Group not found']);
}
$updateUserIds = explode(',', $convList['user_ids']);
if (empty($userIds)) {
return new JsonResponse(['status' => 0, 'message' => 'Please select users']);
}
$updateUserIds = array_merge($userIds, explode(',', $convList['user_ids']));
$time = time();
$userIDs = implode(',', $updateUserIds);
try {
$sql = "UPDATE `conversation` SET `user_ids` = ?,updated_at=? WHERE `id`=?";
$appointment = $em->getConnection()->prepare($sql);
$appointment->execute([$userIDs, $time, $convId]);
} catch (\Exception $e) {
return new JsonResponse(['status' => 0, 'message' => $e->getMessage()]);
}
return new JsonResponse(['status' => 1, 'message' => 'Group updated']);
}
/**
* @Route("/admin/message/deletegroupuser", name="deletegroupuser")
*/
public function deletegroupuser(Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
$userId = $user->getId();
$user_id = $request->get('user_id');
$convId = $request->get('groupconvId');
$sql = "select * from conversation where id = ?";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$convId]);
$convList = $ap->fetchAssociative();
if (empty($convList)) {
return new JsonResponse(['status' => 0, 'message' => 'Group not found']);
}
$updateUserIds = explode(',', $convList['user_ids']);
if (($key = array_search($user_id, $updateUserIds)) !== false) {
unset($updateUserIds[$key]);
}
$time = time();
$userIDs = implode(',', $updateUserIds);
try {
$sql = "UPDATE `conversation` SET `user_ids` = ?,updated_at=? WHERE `id`=?";
$appointment = $em->getConnection()->prepare($sql);
$appointment->execute([$userIDs, $time, $convId]);
} catch (\Exception $e) {
return new JsonResponse(['status' => 0, 'message' => $e->getMessage()]);
}
return new JsonResponse(['status' => 1, 'message' => 'Group user removed']);
}
/**
* @Route("/admin/message/gimage_update", name="gimage_update")
*/
public function gimage_update(Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
$userId = $user->getId();
$convId = $request->get('conv_id');
$sql = "select * from conversation where id = ?";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$convId]);
$convList = $ap->fetchAssociative();
if (empty($convList)) {
return 'Group not found';
}
return $this->render('message/gimage_update.html.twig', [
'convList' => $convList,
'user' => $userId,
]);
}
/**
* @Route("/admin/message/createadvertise", name="createadvertise")
*/
public function createadvertise(Request $request): Response
{
$user = $this->getUser();
$userId = $user->getId();
if ($user->getRole() != 'ROLE_CONSENTZ_ADMIN') {
return 'You do not have permission to perform this action.';
}
$convId = $request->get('conv_id');
$em = $this->getDoctrine()->getManager();
$sql = "select a.*,concat(u.first_name,' ',u.last_name) as name,u.profile_img,u.username from advertisements as a left join user as u on u.id=a.user_id where a.chat_id = ? order by a.id desc";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$convId]);
$advertisements = $ap->fetchAll();
foreach ($advertisements as $key => $advertisement) {
$advertisements[$key]['date'] = date('d M, Y h:i A', $advertisement['created_at']);
}
return $this->render('message/create_advertise.html.twig', [
'convId' => $convId,
'advertisements' => $advertisements
]);
}
/**
* @Route("/admin/message/createadvertisepost", name="createadvertisepost")
*/
public function createadvertisepost(Request $request): Response
{
$convId = $request->get('conv_id');
$em = $this->getDoctrine()->getManager();
$sql = "select * from conversation where id = ?";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$convId]);
$convList = $ap->fetchAssociative();
if (!$convList) {
return new JsonResponse(['status' => '0', 'message' => 'Conversation not found']);
}
$content = $request->get('content');
$title = $request->get('title');
$user = $this->getUser();
$userId = $user->getId();
try {
$type = 0;
$mediaUrl = '';
if ($request->files->get('media')) {
$fileExtension = $request->files->get('media')->getClientOriginalExtension();
$allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'mp4', 'mov', 'avi', 'wmv'];
if (!in_array($fileExtension, $allowedExtensions)) {
return new JsonResponse(['status' => '0', 'message' => 'File not valid']);
}
$file = $request->files->get('media');
$size = $file->getSize();
if ($size > 150 * 1024 * 1024) {
return $this->json(['status' => 0, 'message' => 'File size is not more than 150 MB'], Response::HTTP_BAD_REQUEST);
}
$fileMimeType = $file->getClientMimeType();
if (strpos($fileMimeType, 'image/') === 0) {
$type = 2;
} else if (strpos($fileMimeType, 'video/') === 0) {
$type = 1;
}
$extension = $file->getClientOriginalExtension();
$uniqueFilename = md5(uniqid()) . time() . '.' . $extension;
$filePath = 'uploads/advertise/';
if (!is_dir($this->getParameter('kernel.project_dir') . '/public/uploads/advertise/')) {
mkdir($this->getParameter('kernel.project_dir') . '/public/uploads/advertise/');
}
$entityManager = $this->getDoctrine()->getManager();
$media = new Media();
$media->setFile($file);
$media->setNameFile(Media::getPrefixName($media->getFile()->getClientOriginalName()));
$media->setS3key($filePath . $uniqueFilename);
$this->s3Manager->upload($media);
if ($media->getUrl() != '') {
$mediaUrl = $media->getUrl();
$entityManager->flush();
} else {
$s = $file->move($filePath, $uniqueFilename);
$baseUrl = $_ENV['APP_URl'];
$mediaUrl = $baseUrl . $filePath . $uniqueFilename;
}
}
$time = time();
$sql = "INSERT INTO advertisements (chat_id, media, title, user_id, type, description,receiver_user_ids,read_user_ids, created_at)VALUES (?,?,?,?,?,?,?,?,?)";
$advertise = $em->getConnection()->prepare($sql);
$advertise->execute([$convId, $mediaUrl, $title, $userId, $type, $content, $convList['user_ids'], $userId, $time]);
$lastId = $em->getConnection()->lastInsertId();
$return = ['status' => 1, 'data' => ['media' => $mediaUrl, 'type' => $type, 'description' => $content, 'title' => $title, 'popup_id' => $lastId]];
return new JsonResponse($return);
} catch (\Exception $e) {
return new JsonResponse(['status' => '0', 'message' => $e->getMessage()]);
}
}
/**
* @Route("/admin/message/updategroup", name="updategroup")
*/
public function updategroup(Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
$userId = $user->getId();
$title = trim($request->get('title'));
$convId = $request->get('id');
$croppedImg = $request->get('croppedImage');
$sql = "select * from conversation where id = ?";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$convId]);
$convList = $ap->fetchAssociative();
if (empty($convList)) {
return new JsonResponse(['status' => 0, 'message' => 'Group not found']);
}
try {
if (isset($croppedImg) && $croppedImg && $croppedImg != 'data:,') {
$imgData = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $croppedImg));
$parts = explode(';', $croppedImg);
$mimePart = explode(':', $parts[0]);
$imageType = $mimePart[1];
$extension = explode('/', $imageType)[1];
$uniqueFilename = md5(uniqid()) . time() . '.' . $extension;
$directory = $this->getParameter('kernel.project_dir') . '/public/uploads/chat/';
if (!is_dir($directory)) {
mkdir($directory);
}
$fileSaved = file_put_contents($directory . $uniqueFilename, $imgData);
$uploadPath = $directory . $uniqueFilename;
$targetFile = $this->changeFilePermission($uploadPath);
$file = new UploadedFile($targetFile, $uniqueFilename, 'image/png');
$entityManager = $this->getDoctrine()->getManager();
$media = new Media();
$media->setFile($file);
$media->setNameFile(Media::getPrefixName($media->getFile()->getClientOriginalName()));
$media->setS3key('groups/' . $uniqueFilename);
$this->s3Manager->upload($media);
$fileUpload = $media->getUrl();
$entityManager->flush();
if ($fileUpload == null) {
$fileUpload = $_ENV['APP_URl'] . 'uploads/chat/' . $uniqueFilename;
} else {
if (isset($uniqueFilename) && $uniqueFilename) {
if (file_exists($this->getParameter('kernel.project_dir') . '/public/uploads/chat/' . $uniqueFilename)) {
unlink($this->getParameter('kernel.project_dir') . '/public/uploads/chat/' . $uniqueFilename);
}
}
}
} else {
$fileUpload = $convList['g_image'];
}
if (!$title) {
$title = $convList['title'];
}
$sql = "UPDATE `conversation` SET `title` = ?,g_image=? WHERE `id`=?";
$appointment = $em->getConnection()->prepare($sql);
$appointment->execute([$title, $fileUpload, $convId]);
return new JsonResponse(['status' => 1, 'message' => 'Group Updated']);
} catch (\Exception $e) {
return new JsonResponse(['status' => 0, 'message' => $e->getMessage()]);
}
}
private function changeFilePermission($file)
{
if (!$this->filesystem->exists($file)) {
return false;
}
try {
$this->filesystem->chmod($file, 0777);
} catch (\Exception $e) {
$this->logger->error(
'error change mod for file - ' . $file,
[
'message' => $e->getMessage(),
]
);
return false;
}
return $file;
}
/**
* @Route("/admin/message/start_call", name="startCall")
*/
public function startCall(Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
$userId = $user->getId();
$convId = $request->get('conv_id');
$type = $request->get('type');
$toUserId = $request->get('to_user_id');
$sql = "select * from conversation where id = ? and FIND_IN_SET(?,user_ids)";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$convId,$userId]);
$conversation = $ap->fetchAssociative();
if (!$conversation) {
return new JsonResponse(['status' => 0, 'message' => 'Conversation Not Found']);
}
$sql = "select * from user where last_call_time > ? and (id=? or id=?)";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([time()-20,$toUserId,$userId]);
$call = $ap->fetchAssociative();
if(isset($call) && $call){
return new JsonResponse(['status' => 2, 'data' => $call,'userId'=>$userId]);
}
$toUserId = ($toUserId > 0) ? $toUserId : 0;
$message = '';
$type = $request->get('type');
$call_id = bin2hex(random_bytes(10)) . time();
$data = [
'call_id' => $call_id,
'type' => ($type == 'audio') ? 0 : 1,
'status' => 'CALL_START'
];
$data = isset($data) && $data ? json_encode($data) : '';
$time = time();
try {
$messageData = [
'conversation_id' => $convId,
'from_user_id' => $userId,
'read_user_ids' => $userId,
'to_user_id' => @$toUserId,
'message' => $message,
'image' => ($user->getProfileImg() != '') ? $user->getProfileImg() : ($user->getMedia()?$user->getMedia()->getUrl(): '/images/Clinic/solid_gray.png'),
'type' => 2,
'data' => $data,
'created_at' => $time
];
$t = 2;
$sql = "INSERT INTO chat_messages (conversation_id, from_user_id, read_user_ids, to_user_id, message, type, data, created_at,call_id)
VALUES (?,?,?,?,?,?,?,?,?)";
$messageInsert = $em->getConnection()->prepare($sql);
$messageInsert->execute([$convId, $userId, $userId, @$toUserId, $message, $t, $data, $time, $call_id]);
$lastId = $em->getConnection()->lastInsertId();
$sql = "UPDATE `conversation` SET `last_chat_id` = ?,`updated_at`=? WHERE `id`=?";
$appointment = $em->getConnection()->prepare($sql);
$appointment->execute([$lastId, $time, $convId]);
$messageData['chat_id'] = $lastId;
$message_opponant = $this->setData($messageData, $toUserId);
$messageData['receive_status'] = '';
$message = $this->setData($messageData, $userId);
$callSocket = [
'type' => "CALL_START",
'data' => [
'user_id' => $userId,
'name' => $user->getFullName(),
'call_id' => $call_id,
'user_image' => ($user->getProfileImg() != '') ? $user->getProfileImg() : ($user->getMedia()?$user->getMedia()->getUrl(): '/images/Clinic/solid_gray.png')
]
];
return new JsonResponse(['status' => 1, 'data' => $message, 'call_socket' => $callSocket, 'chat_opponant' => $message_opponant, 'conv_user_ids' => $conversation['user_ids'], 'url' => $this->generateUrl('roomstart') . '?call_id=' . $call_id]);
} catch (\Exception $e) {
return new JsonResponse(['status' => 0, 'message' => $e->getMessage()]);
}
}
/**
* @Route("/admin/room/start", name="roomstart")
*/
public function roomstart(Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
$userId = $user->getId();
$sql = "select chat_messages.*,conversation.type as ctype,conversation.user_ids,conversation.title,conversation.g_image from chat_messages left join conversation on conversation.id=chat_messages.conversation_id where chat_messages.call_id = ? and FIND_IN_SET(?,conversation.user_ids)";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$_GET['call_id'], $userId]);
$message = $ap->fetchAssociative();
if (!$message) {
return new RedirectResponse($this->generateUrl('message_index'));
}
$conversationIds = explode(',', $message['user_ids']);
if (($key = array_search($userId, $conversationIds)) !== false) {
unset($conversationIds[$key]);
}
if ($message['ctype'] == 1) {
$oppo = [
'type' => 1,
'name' => $message['title'],
'image' => ($message['g_image'] != '') ? $message['g_image'] : '/images/Clinic/solid_gray.png',
'conversationIds' => implode(',', $conversationIds)
];
} else {
$opponantId = ($message['from_user_id'] == $userId) ? $message['to_user_id'] : $message['from_user_id'];
$sql = "select user.*,media.url from user left join media on media.id=user.media_id where user.id = ?";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$opponantId]);
$oppoN = $ap->fetchAssociative();
$oppo = [
'user_id' => $oppoN['id'],
'type' => 0,
'name' => $oppoN['first_name'] . ' ' . $oppoN['last_name'],
'image' => ($oppoN['profile_img'] != '') ? $oppoN['profile_img'] : (($oppoN['url'] != '')?$oppoN['url']:'/images/Clinic/solid_gray.png'),
'conversationIds' => $oppoN['id']
];
}
$userData = [
'id' => $userId,
'name' => $user->getFullName(),
'image' => ($user->getProfileImg() != '') ? $user->getProfileImg() : ($user->getMedia()?$user->getMedia()->getUrl(): '/images/Clinic/solid_gray.png')
];
return $this->render('room/start.html.twig', [
'user' => $user,
'opponant' => $oppo,
'message' => $message,
'userData' => $userData,
'conversationIds' => implode(',', $conversationIds)
]);
}
/**
* @Route("/admin/room/call", name="roomcall")
*/
public function roomcall(Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
$userId = $user->getId();
$sql = "select chat_messages.*,conversation.type as ctype,conversation.user_ids,conversation.title,conversation.g_image from chat_messages left join conversation on conversation.id=chat_messages.conversation_id where chat_messages.call_id = ? and FIND_IN_SET(?,conversation.user_ids)";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$_GET['call_id'], $userId]);
$message = $ap->fetchAssociative();
if (!$message) {
return new RedirectResponse($this->generateUrl('message_index'));
}
$conversationIds = explode(',', $message['user_ids']);
if (($key = array_search($userId, $conversationIds)) !== false) {
unset($conversationIds[$key]);
}
if ($message['ctype'] == 1) {
$oppo = [
'type' => 1,
'name' => $message['title'],
'image' => ($message['g_image'] != '')?$message['g_image']: '/images/Clinic/solid_gray.png' ,
'conversationIds' => implode(',', $conversationIds),
'user_id' => implode(',', $conversationIds)
];
} else {
$opponantId = ($message['from_user_id'] == $userId) ? $message['to_user_id'] : $message['from_user_id'];
$sql = "select user.*,media.url from user left join media on media.id=user.media_id where user.id = ?";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$opponantId]);
$oppoN = $ap->fetchAssociative();
$oppo = [
'user_id' => $oppoN['id'],
'type' => 0,
'name' => $oppoN['first_name'] . ' ' . $oppoN['last_name'],
'image' => ($oppoN['profile_img'] != '') ? $oppoN['profile_img'] : (($oppoN['url'] != '')?$oppoN['url']:'/images/Clinic/solid_gray.png'),
'conversationIds' => $oppoN['id']
];
}
$userInfo = [
'id' => $userId,
'displayName' => $user->getFullName(),
'name' => $user->getFullName(),
'image' => ($user->getProfileImg() != '') ? $user->getProfileImg() : ($user->getMedia()?$user->getMedia()->getUrl(): '/images/Clinic/solid_gray.png')
];
$event = $em->getRepository(Meeting::class)->findOneBy(['call_id' => $_GET['call_id']]);
if($event){
$eventId = $event->getId();
$clinicUsers = $this->getDoctrine()->getRepository(ClinicUser::class)->findBy([
'id' => explode(',',$event->getClinicUsers())
]);
$practitionersName = '';
foreach ($clinicUsers as $key => $clinicUser){
$practitionersName = $practitionersName.$clinicUser->getFullName().(count($clinicUsers)- 1 == $key?'':', ');
}
$rr = $this->serializer->normalize($event, 'json', ['find_event' => true]);
$clinic = $this->getDoctrine()->getRepository(Clinic::class)->find($event->getClinicId());
if (!$clinic) {
return $this->json('Event not found', Response::HTTP_BAD_REQUEST);
}
$rr['clinicTimezone'] = @array_search($clinic->getTimezone(), Clinic::CLINIC_TIMEZONES) ;
$rr['practitionerName'] = $practitionersName;
$dateST = new \DateTime();
$rr['date'] = $event->getStart()->format('l, jS F');
$rr['time'] = $event->getStart()->format('h:i A').'-'.$event->getEnd()->format('h:i A');
$rr['practitionerName'] = $practitionersName;
$rr['meetingUrl'] = $this->generateUrl('meeting',['meeting'=>$eventId],\Symfony\Component\Routing\Generator\UrlGeneratorInterface::ABSOLUTE_URL);
$meetingContent = $this->renderView('meeting/meeting_call_content.html.twig', [
'data' => $rr
]);
}
return $this->render('room/call.html.twig', [
'user' => $user,
'opponant' => $oppo,
'message' => $message,
'userInfo' => $userInfo,
'roomName' => 'Consentz #'.@$_GET['call_id'],
'conversationIds' => implode(',', $conversationIds),
'meeting' => $event?['meetingContent'=>$meetingContent,'meetingUrl'=>$rr['meetingUrl']]:'',
'meetingId' => $event?$event->getId():0,
]);
}
/**
* @Route("/admin/files/temp/upload", name="uploadNewFilesTemp")
*/
public function uploadNewFilesTemp(Request $request)
{
$fileExtension = $request->files->get('upload')->getClientOriginalExtension();
$allowedExtensions = ['jpg', 'png', 'svg', 'webp', 'jpeg'];
if (!in_array($fileExtension, $allowedExtensions)) {
return $this->json(['uploaded' => false, 'error' => ['message' => 'File must be in jpg/png/webp']], Response::HTTP_BAD_REQUEST);
}
if ($request->files->has('upload')) {
$file = $request->files->get('upload');
$size = $file->getSize();
if ($size > 20 * 1024 * 1024) {
return $this->json(['uploaded' => false, 'error' => ['message' => 'File size is not more than 20 MB']], Response::HTTP_BAD_REQUEST);
}
$fileMimeType = $file->getClientMimeType();
$originalName = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$uniqueFilename = md5(uniqid()) . time() . '.' . $extension;
$media = new Media();
$media->setFile($file);
$media->setNameFile(Media::getPrefixName($media->getFile()->getClientOriginalName()));
$media->setS3key('temp/' . $uniqueFilename);
$this->s3Manager->upload($media);
if ($media->getUrl() != null) {
$mediaUrl = $media->getUrl();
} else {
$filePath = 'uploads/advertise/';
// dd($filePath);
$s = $file->move($filePath, $uniqueFilename);
$baseUrl = $_ENV['APP_URl'];
$mediaUrl = $baseUrl . $filePath . $uniqueFilename;
}
return $this->json(['uploaded' => true, 'url' => $mediaUrl, 'fileName' => $originalName, 'fileSize' => $size, 'fileType' => $fileMimeType]);
}
return $this->json(['uploaded' => false, 'error' => ['message' => 'No file uploaded']], Response::HTTP_BAD_REQUEST);
}
/**
* @Route("/chat/presence", name="chatpresence")
*/
public function chatpresence(Request $request)
{
try {
$em = $this->getDoctrine()->getManager();
$id = $request->get('room');
$type = $request->get('type');
$this->logger->error('Sockect : User' . $id . ' type:' . $type);
$sql = "UPDATE `user` SET `is_online` = ? WHERE `id`=?";
$appointment = $em->getConnection()->prepare($sql);
$appointment->execute([$type, $id]);
} catch (\Exception $e) {
$this->logger->error('Sockect :' . $e->getMessage());
echo $e->getMessage();
exit;
}
echo 'OK';
exit;
}
/**
* @Route("/admin/chat/updateUserCall", name="updateUserCall")
*/
public function updateUserCall(Request $request){
$user = $this->getUser();
$entityManager = $this->getDoctrine()->getManager();
$user->setLastCallTime(time());
$entityManager->persist($user);
$entityManager->flush();
return new JsonResponse(['status' => 1, 'message' => 'ok']);
}
/**
* @Route("/chat/statuscron", name="statuscron")
*/
public function statuscron(Request $request)
{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://' . $_ENV['SOCKET_URL'] . '/rooms',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => json_encode(['api_key'=>$_ENV['SOCKET_SECRET_KEY']]),
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
$users = json_decode($response);
$onlineUsers = [];
foreach ($users as $u) {
// $u = (int)$u;
preg_match('/\d+/', $u, $matches);
// The number will be in $matches[0]
$u = $matches[0] ?? 0;
if ($u > 0) {
$onlineUsers[] = $u;
}
}
$em = $this->getDoctrine()->getManager();
if (count($onlineUsers) > 0) {
$placeholders = implode(',', array_fill(0, count($onlineUsers), '?'));
$sql = "UPDATE `user` SET `is_online` = ? WHERE `is_online`=? ";
$appointment = $em->getConnection()->prepare($sql);
$appointment->execute([0, 1]);
$sql = "UPDATE `user` SET `is_online` = ? WHERE `is_online`=? and `id` IN ($placeholders)";
$appointment = $em->getConnection()->prepare($sql);
$appointment->execute(array_merge([1, 0], $onlineUsers));
} else {
$sql = "UPDATE `user` SET `is_online` = ? WHERE `is_online`=?";
$appointment = $em->getConnection()->prepare($sql);
$appointment->execute([0, 1]);
}
return new JsonResponse(['status' => $response, 'message' => 'Success']);
}
/**
* @Route("/patient/sync-clinic", name="patientsconversation")
*/
public function patientsconversation(Request $request)
{
$clinic = $request->get('id');
$em = $this->getDoctrine()->getManager();
if (!$clinic) {
$clinics = $this->getDoctrine()->getRepository(Clinic::class)
->findAll();
foreach ($clinics as $clinic) {
$this->addPatientToConversations($em, $clinic->getId());
}
}else{
$this->addPatientToConversations($em, $clinic);
}
echo 'OK';
exit;
}
public function addPatientToConversations($em, $clinicId)
{
$limit = 1000;
$offset = 0;
do {
$sql = "SELECT id FROM user
WHERE clinic_id = ? AND role = ? AND deleted = ?
AND id NOT IN (
SELECT user_id FROM patient_conversation
WHERE type = 0 AND clinic_id = ?
)
LIMIT $limit OFFSET $offset";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute([$clinicId, 'ROLE_PATIENT', 0, $clinicId]);
$patients = $stmt->fetchAllAssociative();
$values = [];
foreach ($patients as $pts) {
$userId = $pts['id'];
$time = time();
$values[] = "(0, $userId, $userId, 1, $time, $time, $clinicId)";
}
if (!empty($values)) {
$sql = "INSERT INTO patient_conversation
(type, user_id, user_ids, status, created_at, updated_at, clinic_id)
VALUES " . implode(', ', $values);
$insertStmt = $em->getConnection()->prepare($sql);
$insertStmt->execute();
}
$offset += $limit;
} while (count($patients) === $limit);
return new Response('Okay');
}
private function addClinicMembersInGroup($convList)
{
try {
$clinic = $this->getDoctrine()->getRepository(Clinic::class)
->find($convList['clinic_id']);
$organizationId = $clinic->getOrganisation()->getId();
$em = $this->getDoctrine()->getManager();
$roles = ['ROLE_CLINIC_ADMIN', 'ROLE_PRACTITIONER', 'ROLE_SUPER_CLINIC_ADMIN'];
$rolesPlaceholder = implode(',', array_fill(0, count($roles), '?'));
$sql = "SELECT role,id,username FROM user WHERE deleted= ? AND ((role IN ($rolesPlaceholder) AND clinic_id = ?) OR organisation_id = ?) order by id desc";
$ap = $em->getConnection()->prepare($sql);
$params = array_merge([0], $roles);
$params[] = $convList['clinic_id'];
$params[] = $organizationId;
$ap->execute($params);
$users = $ap->fetchAll();
$fromuserId = $convList['from_user_id'];
$clinic = $this->getDoctrine()->getRepository(Clinic::class)
->find($convList['clinic_id']);
$sql = "SELECT role,id FROM user WHERE deleted= ? and organisation_id=?";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([0, $clinic->getOrganisationId()]);
$adminData = $ap->fetchAll();
if (count($adminData) > 0) {
$users = array_merge($users, $adminData);
}
$userIds = [];
foreach ($users as $us) {
if ($us['id'] != $fromuserId) {
$userIds[] = $us['id'];
}
}
$sql = "SELECT role,id,username FROM user WHERE role =? and deleted= ? order by id desc";
$ap = $em->getConnection()->prepare($sql);
$ap->execute(['ROLE_CONSENTZ_ADMIN', 0]);
$admins = $ap->fetchAll();
foreach ($admins as $admin) {
$userIds[] = $admin['id'];
}
if (count($userIds) > 0) {
$userIds = implode(',', $userIds) . ',' . $fromuserId;
$sql = "UPDATE `conversation` SET `user_ids` = ? WHERE `id`=?";
$appointment = $em->getConnection()->prepare($sql);
$appointment->execute([$userIds, $convList['id']]);
}
} catch (\Exception $e) {
dd($e->getMessage());
}
return ['status' => 1];
}
private function setData($chat, $userId)
{
$time = ($chat['created_at'] > (time() - 86400)) ? date('h:i A', $chat['created_at']) : date('Y-m-d h:i A', $chat['created_at']);
$message_class = $chat['from_user_id'] == $userId ? 'sender' : 'receiver';
if($chat['from_user_id'] == $userId){
if(isset($chat['receive_status']) && $chat['receive_status'] =='read'){
$messageStatus ='read';
$messageIcon ='✓✓';
}else if(isset($chat['receive_status']) && $chat['receive_status'] =='delivered'){
$messageStatus ='delivered';
$messageIcon ='✓';
}else{
$messageStatus ='sent';
$messageIcon ='✓';
}
}else{
$messageStatus ='';
$messageIcon ='';
}
return [
'chat_id' => $chat['chat_id'],
'name' => isset($chat['name']) ? $chat['name'] : '',
'image' => (isset($chat['image']) && $chat['image'] != '') ? $chat['image'] :(@$chat['media_url'] != ''?@$chat['media_url']:'/images/Clinic/solid_gray.png'),
'conv_id' => $chat['conversation_id'],
'from_user_id' => $chat['from_user_id'],
'created_at' => $chat['created_at'],
'created_time' => $time,
'date' => date('d-m-Y', $chat['created_at']),
'time' => date('h:i A', $chat['created_at']),
'message' => $this->messageHtml($chat, $userId),
'message_text' => $this->messageText($chat),
'message_class' => $message_class,
'receive_class'=>$messageStatus,
'receive_icon'=>$messageIcon,
'type' => $chat['type']
];
}
private function messageHtml($chat, $userId)
{
$msg = $chat['message'] ? $chat['message'] : '';
if($msg != ''){
if (strpos($msg, 'https://') !== false || strpos($msg, 'http://') !== false) {
$msg = '<a href="'.strip_tags($msg).'" target="_blank">'.$msg.'</a>';
}
}
if ($chat['type'] == 1) {
$msg = '';
$chatId = $chat['chat_id'];
$data = json_decode($chat['data'], true);
if ($data) {
if (strpos($data['type'], 'image') !== false) {
$msg .= '<img src="' . $data['media_url'] . '">';
} else if (strpos($data['type'], 'audio') !== false) {
$msg .= '<audio controls preload="metadata" id="chataudio_' . $chatId . '" src="' . $data['media_url'] . '" ></audio>';
$msg .= '<script>
setTimeout(() => {
const audio = document.getElementById("chataudio_' . $chatId . '");
if (audio) {
audio.addEventListener("loadedmetadata", () => {
audio.currentTime = 0.1;
});
audio.load();
}
}, 100);
</script>';
} else if (strpos($data['type'], 'video') !== false) {
$msg .= '<video controls width="300" height="200" src="' . $data['media_url'] . '" ></video>';
} else {
$msg .= '<span style="padding:30px;"><i class="fa fa-file" style="font-size:100px;"></i></span><br>';
}
}
$msg .= '<a download href="' . $data['media_url'] . '" target="_blank"><i class="fa fa-download"></i> ' . $this->shortenFilename($data['name'], 15) . '</a>';
} else if ($chat['type'] == 2) {
$msg = '';
$data = json_decode($chat['data'], true);
$callId = "'" . @$data['call_id'] . "'";
$fromId = @$chat['from_user_id'];
if ($data) {
// $msg .= '<button type="button" class="btn tbn-primary" onclick="chatApp.joinCall(' . $callId . ',
// ' . $fromId . ')"><img src="/images/telephone-call.png"></button>';
$msg .= '<button type="button" class="btn tbn-primary" style="cursor: auto;"><img src="/images/telephone-call.png"></button>';
}
}
return $msg;
}
private function shortenFilename($filename, $maxLength = 15)
{
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$basename = pathinfo($filename, PATHINFO_FILENAME);
if (strlen($basename) > $maxLength) {
$firstPart = substr($basename, 0, ceil($maxLength / 2));
$secondPart = substr($basename, -floor($maxLength / 2));
$basename = $firstPart . '...' . $secondPart;
}
return $basename . '.' . $ext;
}
private function startNewConversation($opponantId)
{
try {
if ($opponantId < 1) {
return ['status' => 0, 'message' => 'Invalid recipient.'];
}
$em = $this->getDoctrine()->getManager();
$sql = "select * from user where id=? and role != ? and deleted= ?";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$opponantId, 'ROLE_PATIENT', 0]);
$oppo = $ap->fetchAssociative();
if (!$oppo || @$oppo['role'] == 'ROLE_PATIENT') {
return ['status' => 0, 'message' => 'Invalid recipient.'];
}
$user = $this->getUser();
$userId = $user->getId();
if ($opponantId == $userId) {
return ['status' => 0, 'message' => "You cannot send a message to yourself."];
}
$sql = "select * from conversation where (from_user_id=? and to_user_id=?) or (from_user_id=? and to_user_id=?)";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$opponantId, $userId, $userId, $opponantId]);
$conversation = $ap->fetchAssociative();
$type = 0;
$time = time();
$status = 1;
if (!$conversation) {
$sql = "INSERT INTO conversation (type, from_user_id, to_user_id, user_ids,status, created_at, updated_at)
VALUES (?,?,?,?,?,?,?)";
$messageInsert = $em->getConnection()->prepare($sql);
$messageInsert->execute([$type, $userId, $opponantId, $userId . ',' . $opponantId, $status, $time, $time]);
$lastId = $em->getConnection()->lastInsertId();
$convId = $lastId;
} else {
$deletedBy = $conversation['deleted_by'];
if ($deletedBy) {
$deletedByArray = explode(',', $deletedBy);
$deletedByArray = array_filter(array_map('trim', $deletedByArray));
$deletedByArray = array_filter($deletedByArray, function ($id) use ($userId) {
return $id != $userId;
});
$updatedDeletedBy = implode(',', $deletedByArray);
} else {
$updatedDeletedBy = '';
}
$sql = "UPDATE `conversation` SET `updated_at`=?,`deleted_by`=? WHERE `id`=?";
$appointment = $em->getConnection()->prepare($sql);
$appointment->execute([time(), $updatedDeletedBy, $conversation['id']]);
$convId = $conversation['id'];
}
return ['status' => 1, 'convId' => $convId];
} catch (\Exception $e) {
return ['status' => 0, 'message' => $e->getMessage()];
}
}
private function messageText($chat)
{
$msg = $chat['message'] ? $chat['message'] : '';
if ($chat['type'] == 1) {
$msg = '[File]';
} else if ($chat['type'] == 2) {
$msg = 'Call';
}
return $msg;
}
}