Viewing file: ChatController.php (20.55 KB) -rw-r--r-- Select action/file-type: (+) | (+) | (+) | Code (+) | Session (+) | (+) | SDB (+) | (+) | (+) | (+) | (+) | (+) |
<?php
namespace App\Http\Controllers\Customer;
use App\Http\Controllers\Controller;
use App\Models\Contact;
use App\Models\Exception;
use App\Models\Label;
use App\Models\MessageLog;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class ChatController extends Controller
{
public function index()
{
$data['numbers'] = auth('customer')->user()->numbers()->get();
$data['chat_responses'] = auth('customer')->user()->chat_responses()->where('status', 'active')->get();
$data['labels'] = auth('customer')->user()->labels()->where('status', 'active')->get();
return view('customer.chat.index', $data);
}
public function get_numbers(Request $request)
{
$page_no = $request->page;
if (!$page_no) abort(404);
$no_of_data = 10;
$offset = ($page_no * $no_of_data) - $no_of_data;
$search = $request->search;
$allNumbers = auth()->user()->message_logs()->select('from AS to', 'body', DB::raw('MAX(updated_at) as created_at'))->where('type', 'inbox')->groupBy('from');
if ($request->type == 'old') {
$allNumbers = $allNumbers->orderBy('created_at', 'asc');
} else {
$allNumbers = $allNumbers->orderByDesc('created_at');
}
if ($search) {
$contacts = Contact::where('number', 'like', '%' . $search . '%')->orWhere('first_name', 'like', '%' . $search . '%')->orWhere('last_name', 'like', '%' . $search . '%')->pluck('number');
$allNumbers = $allNumbers->whereIn('from', $contacts)->where('type', 'inbox');
}
if ($request->date) {
$dates = explode('-', $request->date);
$fromDate = isset($dates) && isset($dates["0"]) ? str_replace(' ', '', $dates["0"]) : now();
$toDate = isset($dates) && isset($dates["1"]) ? str_replace(' ', '', $dates["1"]) : now();
$fromDate = new \DateTime($fromDate);
$toDate = new \DateTime($toDate);
if ($fromDate != $toDate) {
$allNumbers = $allNumbers->whereBetween('updated_at', [$fromDate, $toDate]);
}
}
if ($request->label_id) {
$label = Label::where('id', $request->label_id)->first();
if (!$label) {
return response()->json(['status' => 'failed', 'message' => 'Invalid Label']);
}
$contacts = auth('customer')->user()->contacts()->where('label_id', $label->id)->pluck('number')->unique();
$allNumbers = $allNumbers->whereIn('from', $contacts);
}
$allNumbers = $allNumbers->limit($no_of_data)->offset($offset)->get();
if ($request->type == 'old') {
$from_numbers = $allNumbers->sortBy('created_at')->pluck('to')->unique();
} else {
$from_numbers = $allNumbers->sortByDesc('created_at')->pluck('to')->unique();
}
$createdAt = [];
foreach ($allNumbers as $number) {
$diffInMinutes = now()->diffInMinutes($number->created_at);
$createdAt[$number->to] = $diffInMinutes > 60 ? $number->created_at->format('M,d,y h:i A') : $diffInMinutes . " min";
}
$allChats = auth('customer')->user()->message_logs()->whereIn('to', $from_numbers)
->orWhereIn('from', $from_numbers)
->orderBy('updated_at')
->get(['body', 'to', 'from', 'created_at', 'updated_at']);
$find_chat = [];
foreach ($allChats as $key => $chat) {
$find_chat[$chat->to] = $chat->body;
}
foreach ($allChats as $key => $chat) {
$find_chat[$chat->from] = $chat->body;
}
// Created At For New Message
$find_created_at=[];
foreach ($allChats as $key => $chat) {
$find_created_at[$chat->from] = $chat->created_at->format('y-m-d h:i:s');
}
$numbersArray = [];
foreach ($from_numbers as $number) {
$numbersArray[] = '+' . str_replace('+', '', $number);
}
$findContacts = auth('customer')->user()->contacts()->whereIn('number', $from_numbers)->orWhereIn('number', $numbersArray)->orderBy('created_at')->get(['id','number','first_name','last_name']);
$findContact = [];
foreach ($findContacts as $contact) {
$findContact[$contact->number] = [
'label' => '',
'color' => '',
'full_name' => $contact->full_name ?? '',
'id' => $contact->id ?? ''
];
}
$unreadsCount=MessageLog::select('from',DB::raw('count(*) as total'))->whereIn('from', $from_numbers)->where('is_read', 'no')->groupBy('from')->pluck('total','from')->toArray();
$data = [];
foreach ($from_numbers as $key => $from_number) {
$data[$key]['full_name'] = isset($findContact[$from_number]) && isset($findContact[$from_number]['full_name']) ? $findContact[$from_number]['full_name'] : '';
$data[$key]['id'] = isset($findContact[$from_number]) && isset($findContact[$from_number]['id']) ? $findContact[$from_number]['id'] : '';
$data[$key]['number'] = $from_number;
$data[$key]['created_at'] = isset($createdAt) && isset($createdAt[$from_number]) ? $createdAt[$from_number] : '';
$data[$key]['label'] = isset($findContact[$from_number]) && isset($findContact[$from_number]['label']) ? $findContact[$from_number]['label'] : '';
$data[$key]['color'] = isset($findContact[$from_number]) && isset($findContact[$from_number]['color']) ? $findContact[$from_number]['color'] : '';
$data[$key]['body'] = isset($find_chat[$from_number]) ? $find_chat[$from_number] : '';
$data[$key]['unread']= $unreadsCount[$from_number] ?? 0;
$data[$key]['createdAt'] = isset($find_created_at[$from_number])?$find_created_at[$from_number] : '';
}
// $data=collect($data)->sortByDesc('createdAt')->values();
$labels = collect([]);
if ($from_numbers->isNotEmpty()) {
return response()->json(['status' => 'success', 'data' => ['numbers' => $data, 'labels' => $labels, 'page' => $page_no + 1]]);
} else {
return response()->json(['status' => 'success', 'data' => ['numbers' => [], 'page' => 'end']]);
}
}
public function getNewChat(Request $request){
try {
$timeD = new Carbon($request->time);
$time = $timeD->format('y-m-d h:i:s');
$totalNew = MessageLog::where('customer_id', auth('customer')->user()->id)->where('type', 'inbox')->where('is_read', 'no')->get();
$counter=0;
foreach ($totalNew as $count){
$msgTime=$count->created_at->format('y-m-d h:i:s');
$msgTime=strtotime($msgTime);
$time=strtotime($time);
// dd($request->time, $time);
if ($msgTime > $time){
$counter++;
}
}
return response()->json(['status' => 'success', 'data' => count($totalNew)]);
} catch (\Exception $ex) {
return response()->json(['status' => 'failed', 'message'=>$ex->getMessage()]);
}
}
public function label_update(Request $request)
{
$request->validate([
'number' => 'required',
'label' => 'required'
]);
$contact = Contact::where_number($request->number)->first();
if (!$contact) {
return response()->json(['status' => 'failed']);
}
$label = auth('customer')->user()->labels()->where('id', $request->label)->where('status', 'active')->first();
if (!$label) {
return response()->json(['status' => 'failed', 'message' => 'This is not a valid label']);
}
$contact->label_id = $label->id;
$contact->update();
return response()->json(['status' => 'success', 'message' => 'Label successfully updated']);
}
public function get_data(Request $request)
{
$no_of_data = 20;
$chats = auth('customer')->user()->message_logs()->where(function ($q) use ($request) {
$q->where('to', $request->number)->orWhere('to', str_replace('+', '', $request->number))->orWhere('to', "+" . str_replace('+', '', $request->number));
})->orWhere(function ($q) use ($request) {
$q->where('from', $request->number)->orWhere('from', str_replace('+', '', $request->number))->orWhere('from', "+" . str_replace('+', '', $request->number));
})->orderByDesc('updated_at')->limit($no_of_data)->get(['id','is_read','body', 'to', 'from', 'type', 'created_at', 'updated_at', 'status'])->toArray();
$messageLogIds=[];
foreach ($chats as $chat){
if($chat['is_read']=='no'){
$messageLogIds[]=$chat['id'];
}
}
if($messageLogIds){
auth('customer')->user()->message_logs()->whereIn('id',$messageLogIds)->update(['is_read'=>'yes']);
}
$contact_id = auth('customer')->user()->contacts()->select('id','first_name','last_name','label_id','address')->where('number', $request->number)->orWhere('number', str_replace('+', '', $request->number))->orWhere('number', "+" . str_replace('+', '', $request->number))->first();
if ($contact_id) {
$address = isset($contact_id->address) ? $contact_id->address : '';
$exception_cache=cache('exception_'.auth('customer')->id());
$isException='';
if($exception_cache){
$exceptions=json_decode($exception_cache);
if($exceptions && in_array($contact_id->id,$exceptions)){
$isException='true';
}
}else{
$exception_contacts=Exception::where('customer_id',auth('customer')->id())->pluck('contact_id')->toArray();
// dd($exception_contacts);
if($exception_contacts){
cache()->remember('exception_'.auth('customer')->id(), 10800, function () use ($exception_contacts) {
return json_encode($exception_contacts);
});
}
}
$label = auth('customer')->user()->labels()->select('id','color')->where('id', $contact_id->label_id)->where('status', 'active')->first();
return response()->json(['status' => 'success', 'data' => ['address' => $address, 'number' => $isException, 'id' => $contact_id->id, 'color' => $label->color ?? '', 'label' => $label->id ?? '', 'name' => $contact_id->full_name, 'messages' => $chats, 'page' => count($chats) < $no_of_data ? 'end' : 2]]);
}
return response()->json(['status' => 'success', 'data' => ['id' => null, 'label' => null, 'messages' => $chats, 'page' => count($chats) < $no_of_data ? 'end' : 2]]);
}
public function get_chats(Request $request)
{
$chats_no = $request->chats;
if (!$chats_no) abort(404);
$no_of_data = 20;
$offset = ($chats_no * $no_of_data) - $no_of_data;
$chats = auth('customer')->user()->message_logs()->where(function ($q) use ($request) {
$q->where('to', $request->number)->orWhere('to', str_replace('+', '', $request->number))->orWhere('to', "+" . str_replace('+', '', $request->number));
})->orWhere(function ($q) use ($request) {
$q->where('from', $request->number)->orWhere('from', str_replace('+', '', $request->number))->orWhere('from', "+" . str_replace('+', '', $request->number));
})->orderByDesc('updated_at')->offset($offset)->limit($no_of_data)->get(['body', 'to', 'from', 'type', 'created_at', 'updated_at'])->toArray();
if ($chats) {
return response()->json(['status' => 'success', 'data' => ['messages' => $chats, 'page' => count($chats) < $no_of_data ? 'end' : $chats_no + 1]]);
} else {
return response()->json(['status' => 'success', 'data' => ['messages' => [], 'page' => 'end']]);
}
}
public function exception(Request $request)
{
$label = auth('customer')->user()->labels()->where('title', 'new')->first();
if (!$label) {
$label = new Label();
$label->title = 'new';
$label->status = 'active';
$label->customer_id = auth('customer')->user()->id;
$label->color = 'red';
$label->save();
}
$contact = auth('customer')->user()->contacts()->where('number', $request->number)->orWhere('number', str_replace('+', '', $request->number))->orWhere('number', "+" . str_replace('+', '', $request->number))->first();
if (!$contact) {
$contact = new Contact();
$contact->customer_id = auth('customer')->user()->id;
$contact->number = $request->number;
$contact->label_id = $label->id;
$contact->save();
}
if ($request->type == 'add') {
$exception = new Exception();
$exception->contact_id = $contact->id;
$exception->number = $request->number;
$exception->customer_id = auth('customer')->user()->id;
$exception->save();
$exception_contacts=Exception::where('customer_id',auth('customer')->id())->pluck('contact_id')->toArray();
if($exception_contacts){
cache()->remember('exception_'.auth('customer')->id(), 10800, function () use ($exception_contacts) {
return json_encode($exception_contacts);
});
}
return response()->json(['status' => 'success', 'type' => $request->type]);
} elseif ($request->type == 'delete') {
$exception = Exception::where('number', $request->number)->orWhere('number', str_replace('+', '', $request->number))->where('customer_id', auth('customer')->user()->id)->first();
if ($exception) {
$exception->delete();
$exception_contacts=Exception::where('customer_id',auth('customer')->id())->pluck('contact_id')->toArray();
if($exception_contacts){
cache()->remember('exception_'.auth('customer')->id(), 10800, function () use ($exception_contacts) {
return json_encode($exception_contacts);
});
}
}
return response()->json(['status' => 'success', 'type' => $request->type]);
} elseif ($request->type == 'block') {
$exception = Exception::where('number', $request->number)->orWhere('number', str_replace('+', '', $request->number))->where('customer_id', auth('customer')->user()->id)->where('type', 'block')->first();
if (!$exception) {
$exception = new Exception();
}
$exception->contact_id = $contact->id;
$exception->number = $request->number;
$exception->type = 'block';
$exception->customer_id = auth('customer')->user()->id;
$exception->save();
if ($request->ajax()) {
return response()->json(['status' => 'success', 'type' => $request->type]);
}
return redirect()->back()->with(['msg' => 'Contact has been blocked']);
}
}
public function addNewContact(Request $request)
{
$label = auth('customer')->user()->labels()->where('id', $request->label)->where('status', 'active')->first();
if (!$label) {
return response()->json(['status' => 'failed', 'message' => 'This is not a valid label']);
}
$preContact = Contact::where_number($request->number)->first();
if ($preContact) {
$preContact->label_id = $label->id;
$preContact->save();
return response()->json(['status' => 'success', 'message' => 'Contact Successfully added']);
}
$contact = new Contact();
$contact->customer_id = auth('customer')->user()->id;
$contact->number = "+" . str_replace('+', '', $request->number);
$contact->label_id = $label->id;
$contact->save();
return response()->json(['status' => 'success', 'message' => 'Contact Successfully added']);
}
public function sendContactInfo(Request $request)
{
if (!$request->number || !$request->url) {
return response()->json(['status' => 'failed', 'message' => 'Invalid Request']);
}
$contact = Contact::select('first_name', 'last_name', 'number', 'email', 'label_id', 'city', 'state', 'zip_code', 'note', 'address', 'company')
->where_number($request->number)->first();
if (!$contact) {
return response()->json(['status' => 'failed', 'message' => 'Invalid number']);
}
$message_logs = MessageLog::select('to', 'from', 'body', 'type', 'status', 'created_at', 'updated_at')->where('to', $contact->number)->orWhere('from', $contact->number)->orderByDesc('updated_at')->get();
$contactData = [
'first_name' => $contact->first_name,
'last_name' => $contact->last_name,
'number' => $contact->number,
'email' => $contact->email,
'city' => $contact->city,
'state' => $contact->state,
'zip_code' => $contact->zip_code,
'address' => $contact->address,
'note' => $contact->note,
'company' => $contact->company,
'label' => null
];
if (isset($contact->label)) {
$contactData['label'] = [
'title' => $contact->label->title,
'color' => $contact->label->color,
];
}
$messageData = [];
foreach ($message_logs as $key => $message_log) {
$messageData[$key]['from'] = $message_log->from;
$messageData[$key]['to'] = $message_log->to;
$messageData[$key]['body'] = $message_log->body;
$messageData[$key]['type'] = $message_log->type;
$messageData[$key]['status'] = $message_log->status;
$messageData[$key]['created_at'] = $message_log->created_at->toDateTimeString();
$messageData[$key]['updated_at'] = $message_log->updated_at->toDateTimeString();
}
$data = [
'contact' => $contactData,
'messages' => $messageData,
];
$client = new \GuzzleHttp\Client(['verify' => false]);
if ($request->url_method == 'post') {
$client->post($request->url, [
'form_params' => $data
]);
} else {
$client->get($request->url, [
'query' => $data
]);
}
return response()->json(['status' => 'success']);
}
public function findUser(Request $request)
{
$page_no = $request->page;
if (!$page_no) abort(404);
$no_of_data = 20;
$offset = ($page_no * $no_of_data) - $no_of_data;
$contacts = auth('customer')->user()->contacts()->limit($no_of_data)->offset($offset)->select(['first_name', 'last_name', 'id', 'number']);
if ($request->name) {
$nameArray = explode(' ', $request->name);
foreach ($nameArray as $item) {
$contacts->where(function ($q) use ($item) {
$q->orWhere(DB::raw('CONCAT(`first_name`," ",`last_name`)'), 'like', '%' . $item . '%')
->orWhere('number', 'like', '%' . $item . '%');
});
}
}
$allContacts = [];
foreach ($contacts->get() as $contact) {
$allContacts[] = [
'name' => $contact->fullname ? ucwords($contact->fullname) : $contact->number,
'number' => $contact->number,
'id' => $contact->id,
];
}
return response()->json(['data' => $allContacts, 'status' => 'success']);
}
public function deleteFullConversation(Request $request)
{
$contact = auth('customer')->user()->contacts()->where('number', $request->number)->orWhere('number', str_replace('+', '', $request->number))->orWhere('number', "+" . str_replace('+', '', $request->number))->firstOrFail();
auth('customer')->user()->message_logs()->where('from', $contact->number)->orWhere('to', $contact->number)->delete();
return redirect()->back()->with('success', 'Conversation deleted successfully');
}
}
|