<?php

namespace App\Http\Controllers\Admin;

use App\Events\ChatMessageEvent;
use App\Http\Controllers\Controller;
use App\Jobs\MailSend;
use Illuminate\Http\Request;
use App\Models\Ticket\Ticket;
use App\Models\Ticket\Category;
use App\Mail\AppMailer;
use App\Models\User;
use App\Models\Apptitle;
use App\Models\Footertext;
use App\Models\Seosetting;
use App\Models\Pages;
use DB;
use App\Models\Ticketnote;
use App\Models\EmailTemplate;
use App\Models\Ticket\Comment;
use Illuminate\Support\Facades\Mail;
use Torann\GeoIP\Facades\GeoIP;
use Jenssegers\Agent\Agent;
use App\Models\EmployeeActivity;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;

class AdminTicketController extends Controller
{

    public function notificationpage(){

        $title = Apptitle::first();
        $data['title'] = $title;

        $footertext = Footertext::first();
        $data['footertext'] = $footertext;

        $seopage = Seosetting::first();
        $data['seopage'] = $seopage;

        $notifications = auth()->user()->notifications()->paginate('10')->groupBy(function($date) {
            return \Carbon\Carbon::parse($date->created_at)->format('Y-m-d');
        });
        $data['notifications'] = $notifications;

        $arraystatus = array('mail');
        $filter =  auth()->user()->notifications()->whereIn('data->status', $arraystatus)->where(function($query){
            $query->where('data->title', 'Sed repellendus in eligendi quo.')
            ->orWhere('data->mailsubject', 'gjfgfgfgfgfghfgghfg');
        })->get();
        $filter1 =  auth()->user()->notifications()->where(function($query){
            $keyword = request()->get('data');
            $query->where('data->title','LIKE', "%{$keyword}%")
            ->orWhere('data->mailsubject','LIKE', "%{$keyword}%")
            ->orWhere('data->mailtext','LIKE', "%{$keyword}%");
        })->get();

        $filter2 =  auth()->user()->notifications()->whereIn('data->status', $arraystatus)->get();

        return view('admin.notificationpage')->with($data);

    }

    public function adminticketclosing(Request $request, $id)
    {
        $this->authorize('Ticket Edit');

        $id = decrypt($id);
        $ticket = Ticket::findOrFail($id);
        if($ticket->status == 'Closed'){
            return response()->json(['code'=>500, 'error'=>lang('Ticket status is already in Solved only.', 'alerts')], 500);
        }else{
            $ticket->status = 'Closed';
            $ticket->auto_close_ticket = null;
            $ticket->auto_replystatus = null;
            $ticket->auto_overdue_ticket = null;
            $ticket->overduestatus = null;
            $ticket->closedby_user = Auth::id();
            $ticket->ticketreopen = 'stopreopen';
            $ticket->update();

            $comment = Comment::create([
                'ticket_id' => $ticket->id,
                'user_id' => Auth::user()->id,
                'cust_id' => null,
                'comment' => 'Ticket status changed to Solved',
                'commenttype' => 'tickethistory',
            ]);

            $ticketinfo = view('admin.superadmindashboard.allticketsinfo', compact('ticket'))->render();
            $comment->ticketinfo = $ticketinfo;

            event(new ChatMessageEvent(null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,$ticket->id,$ticket->cust->id,$comment,'tickethistory',Auth::user()->name));

            $ticketData = [
                'ticket_username' => $ticket->cust->username,
                'ticket_id' => $ticket->ticket_id,
                'ticket_status' => $ticket->status,
                'ticket_category' => $ticket->category != null ? $ticket->category->name : 'Category not available',
                'item_name' => $ticket->item_name != null ? $ticket->item_name : 'Item Name not available',
            ];

            $geolocation = GeoIP::getLocation(request()->getClientIp());
            $agent = new Agent();
            $activity = new EmployeeActivity();
            $activity->user_id = Auth::user()->id;
            $activity->activity_type = 'Ticket status changed to Solved';
            $activity->ip_address = $geolocation->ip;
            $activity->browser = $agent->browser();
            $activity->device = $agent->device();
            $activity->save();

            try{
                $imap_username = setting('IMAP_USERNAME');

                $replySubject = 'Re: ' . $ticket->subject;
                $emailtemplate = EmailTemplate::where('code', 'send_mail_customer_when_status_changed')->first();
                $body = $emailtemplate->body;

                foreach ($ticketData as $key => $value) {
                    $body = str_replace('{{' . $key . '}}', $value, $body);
                    $body = str_replace('{{ ' . $key . ' }}', $value, $body);
                }

                try {

                    Mail::send([], [], function ($message) use ($ticket, $replySubject, $body, $imap_username) {
                        $message->to($ticket->cust->email)
                            ->from($imap_username)
                            ->subject($replySubject)
                            ->html($body);
                        $headers = $message->getHeaders();
                        $headers->addTextHeader('In-Reply-To', '<' . $ticket->MessageID . '>');
                        $headers->addTextHeader('References', '<' . $ticket->MessageID . '>');
                    });
                } catch (\Exception $e) {

                }

                $assigneuser = User::find($ticket->selfassignuser_id);
                if($assigneuser != null && $assigneuser->usetting->emailnotifyon == 1 && Auth::id() != $assigneuser->id){
                    dispatch((new MailSend($assigneuser->email, 'send_mail_admin_panel_users_when_status_changed', $ticketData)));
                }

                $users = User::get();
                foreach($users as $user){
                    if($user->can('All Tickets') && $user->usetting->emailnotifyon == 1 && $user->id != $ticket->selfassignuser_id  && Auth::id() != $user->id){
                        dispatch((new MailSend($user->email, 'send_mail_admin_panel_users_when_status_changed', $ticketData)));
                    }
                }
            } catch(\Exception $e){
                return response()->json(['success' => lang('Ticket status changed to solved successfully.', 'alerts')]);
            }

            return response()->json(['success'=>lang('Ticket status changed to solved successfully.', 'alerts')]);
        }
    }

    public function adminticketinprogressing(Request $request, $id)
    {
        $this->authorize('Ticket Edit');

        $id = decrypt($id);
        $ticket = Ticket::findOrFail($id);
        if($ticket->status == 'Inprogress'){
            return response()->json(['code'=>500, 'error'=>lang('Ticket status is already in Inprogress only.', 'alerts')], 500);
        }else{
            $ticket->status = 'Inprogress';
            $ticket->auto_close_ticket = null;
            $ticket->auto_replystatus = null;
            $ticket->auto_overdue_ticket = null;
            $ticket->overduestatus = null;
            $ticket->closedby_user = null;
            $ticket->update();

            $comment = Comment::create([
                'ticket_id' => $ticket->id,
                'user_id' => Auth::user()->id,
                'cust_id' => null,
                'comment' => 'Ticket status changed to Inprogress',
                'commenttype' => 'tickethistory',
            ]);

            $ticketinfo = view('admin.superadmindashboard.allticketsinfo', compact('ticket'))->render();
            $comment->ticketinfo = $ticketinfo;

            event(new ChatMessageEvent(null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,$ticket->id,$ticket->cust->id,$comment,'tickethistory',Auth::user()->name));

            $ticketData = [
                'ticket_username' => $ticket->cust->username,
                'ticket_id' => $ticket->ticket_id,
                'ticket_status' => $ticket->status,
                'ticket_category' => $ticket->category != null ? $ticket->category->name : 'Category not available',
                'item_name' => $ticket->item_name != null ? $ticket->item_name : 'Item Name not available',
            ];


            $geolocation = GeoIP::getLocation(request()->getClientIp());
            $agent = new Agent();
            $activity = new EmployeeActivity();
            $activity->user_id = Auth::user()->id;
            $activity->activity_type = 'Ticket status changed to Inprogress';
            $activity->ip_address = $geolocation->ip;
            $activity->browser = $agent->browser();
            $activity->device = $agent->device();
            $activity->save();

            try{
                $imap_username = setting('IMAP_USERNAME');

                $replySubject = 'Re: ' . $ticket->subject;
                $emailtemplate = EmailTemplate::where('code', 'send_mail_customer_when_status_changed')->first();
                $body = $emailtemplate->body;

                foreach ($ticketData as $key => $value) {
                    $body = str_replace('{{' . $key . '}}', $value, $body);
                    $body = str_replace('{{ ' . $key . ' }}', $value, $body);
                }

                try {

                    Mail::send([], [], function ($message) use ($ticket, $replySubject, $body, $imap_username) {
                        $message->to($ticket->cust->email)
                            ->from($imap_username)
                            ->subject($replySubject)
                            ->html($body);
                        $headers = $message->getHeaders();
                        $headers->addTextHeader('In-Reply-To', '<' . $ticket->MessageID . '>');
                        $headers->addTextHeader('References', '<' . $ticket->MessageID . '>');
                    });
                } catch (\Exception $e) {

                }

                $assigneuser = User::find($ticket->selfassignuser_id);
                if($assigneuser != null && $assigneuser->usetting->emailnotifyon == 1 && Auth::id() != $assigneuser->id){
                    dispatch((new MailSend($assigneuser->email, 'send_mail_admin_panel_users_when_status_changed', $ticketData)));
                }

                $users = User::get();
                foreach($users as $user){
                    if($user->can('All Tickets') && $user->usetting->emailnotifyon == 1 && $user->id != $ticket->selfassignuser_id  && Auth::id() != $user->id){
                        dispatch((new MailSend($user->email, 'send_mail_admin_panel_users_when_status_changed', $ticketData)));
                    }
                }
            } catch(\Exception $e){
                return response()->json(['success' => lang('Ticket status changed to Inprogress successfully.', 'alerts')]);
            }

            return response()->json(['success'=>lang('Ticket status changed to Inprogress successfully.', 'alerts')]);
        }
    }

    public function purchasedetailsverify(Request $request)
    {
        $ticket = Ticket::findOrFail($request->id);
        $ticket->usernameverify = 'verified';
        $ticket->update();

        return response()->json(['success'=>lang('The customer was verified successfully.', 'alerts')]);
    }


    public function wrongcustomer(Request $request)
    {
        $ticket = Ticket::findOrFail($request->id);
        $ticket->usernameverify = 'wrongcustomer';
        $ticket->update();

        return response()->json(['success'=>lang('The customer mentioned details are wrong.', 'alerts')]);
    }


    /**
     * Close the specified ticket.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */

    public function close(Request $request,$ticket_id, AppMailer $mailer)
    {
        $ticket = Ticket::where('ticket_id', $ticket_id)->firstOrFail();

        $ticket->status = $request->input('status');

        $ticket->update();

        $ticketOwner = $ticket->user;

        $mailer->sendTicketStatusNotification($ticketOwner, $ticket);

        return redirect()->back()->with("warning", lang('The ticket has been closed.', 'alerts'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $this->authorize('Ticket Delete');

        $id = decrypt($id);

        $ticket = Ticket::with('users','selfassign')->findOrFail($id);

        $comment = $ticket->comments()->get();


        if (count($comment) > 0) {
            $media = $ticket->getMedia('ticket');

            foreach ($media as $media) {

                    $media->delete();

            }
            $medias = $ticket->comments()->get();

            foreach ($medias as $mediass) {
                foreach($mediass->getMedia('comments') as $mediasss){

                    $mediasss->delete();
                }

            }
            $comment->each->delete();

            $newcomment = Comment::create([
                'ticket_id' => $ticket->id,
                'user_id' => Auth::user()->id,
                'cust_id' => null,
                'comment' => 'Ticket has been deleted',
                'commenttype' => 'tickethistory',
            ]);

            $newcomment->ticketdeletingaction = 'ticketdeletingaction';
            $newcomment->assigneduserprofile = $ticket->selfassign != null ? userprofileimage($ticket->selfassign) : null;
            $newcomment->ticketencryptedId = Crypt::encrypt($ticket->id);
            $newcomment->ticketfulldata = $ticket;

            event(new ChatMessageEvent(null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,$ticket->id,$ticket->cust->id,$newcomment,'tickethistory',Auth::user()->name));

            $ticket->delete();

            return response()->json(['success'=>lang('The ticket was successfully deleted.', 'alerts')]);
        }else{

            $media = $ticket->getMedia('ticket');

            foreach ($media as $media) {

                    $media->delete();

            }

            $newcomment = Comment::create([
                'ticket_id' => $ticket->id,
                'user_id' => Auth::user()->id,
                'cust_id' => null,
                'comment' => 'Ticket has been deleted',
                'commenttype' => 'tickethistory',
            ]);

            $newcomment->ticketdeletingaction = 'ticketdeletingaction';
            $newcomment->assigneduserprofile = $ticket->selfassign != null ? userprofileimage($ticket->selfassign) : null;
            $newcomment->ticketencryptedId = Crypt::encrypt($ticket->id);
            $newcomment->ticketfulldata = $ticket;

            event(new ChatMessageEvent(null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,$ticket->id,$ticket->cust->id,$newcomment,'tickethistory',Auth::user()->name));

            $ticket->delete();

            $geolocation = GeoIP::getLocation(request()->getClientIp());
            $agent = new Agent();
            $activity = new EmployeeActivity();
            $activity->user_id = Auth::user()->id;
            $activity->activity_type = 'Ticket Deleted';
            $activity->ip_address = $geolocation->ip;
            $activity->browser = $agent->browser();
            $activity->device = $agent->device();
            $activity->save();

            return response()->json(['success'=>lang('The ticket was successfully deleted.', 'alerts')]);

        }
    }


    public function ticketmassdestroy(Request $request){

        $student_id_arrays = $request->input('id');

        $student_id_array = array_map(function ($encryptedValue) {
            return decrypt($encryptedValue);
        }, $student_id_arrays);

        $tickets = Ticket::with('users','selfassign')->whereIn('id', $student_id_array)->get();


        foreach($tickets as $ticket){

            $comment = $ticket->comments()->get();


            if (count($comment) > 0) {
                $media = $ticket->getMedia('ticket');

                foreach ($media as $media) {

                        $media->delete();

                }
                $medias = $ticket->comments()->get();

                foreach ($medias as $mediass) {
                    foreach($mediass->getMedia('comments') as $mediasss){

                        $mediasss->delete();
                    }

                }
                $comment->each->delete();

                $newcomment = Comment::create([
                    'ticket_id' => $ticket->id,
                    'user_id' => Auth::user()->id,
                    'cust_id' => null,
                    'comment' => 'Ticket has been deleted',
                    'commenttype' => 'tickethistory',
                ]);

                $newcomment->ticketdeletingaction = 'ticketdeletingaction';
                $newcomment->assigneduserprofile = $ticket->selfassign != null ? userprofileimage($ticket->selfassign) : null;
                $newcomment->ticketencryptedId = Crypt::encrypt($ticket->id);
                $newcomment->ticketfulldata = $ticket;

                event(new ChatMessageEvent(null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,$ticket->id,$ticket->cust->id,$newcomment,'tickethistory',Auth::user()->name));

                $tickets->each->delete();
                return response()->json(['success'=> lang('The ticket was successfully deleted.', 'alerts')]);
            }else{

                $media = $ticket->getMedia('ticket');

                foreach ($media as $media) {

                        $media->delete();

                }

                $newcomment = Comment::create([
                    'ticket_id' => $ticket->id,
                    'user_id' => Auth::user()->id,
                    'cust_id' => null,
                    'comment' => 'Ticket has been deleted',
                    'commenttype' => 'tickethistory',
                ]);

                $newcomment->ticketdeletingaction = 'ticketdeletingaction';
                $newcomment->assigneduserprofile = $ticket->selfassign != null ? userprofileimage($ticket->selfassign) : null;
                $newcomment->ticketencryptedId = Crypt::encrypt($ticket->id);
                $newcomment->ticketfulldata = $ticket;

                event(new ChatMessageEvent(null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,$ticket->id,$ticket->cust->id,$newcomment,'tickethistory',Auth::user()->name));

                $tickets->each->delete();
            }
        }

        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Multiple Tickets Deleted';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        return response()->json(['success'=> lang('The ticket was successfully deleted.', 'alerts')]);

    }

    public function guestmedia(Request $request)
    {
        $path = public_path('uploads/guestticket/');

        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }

        $file = $request->file('file');

        $name = uniqid() . '_' . trim($file->getClientOriginalName());

        $file->move($path, $name);

        return response()->json([
            'name'          => $name,
            'original_name' => $file->getClientOriginalName(),
        ]);
    }

    public function note(Request $request){

        $ticketnote = Ticketnote::create([
            'ticket_id' => $request->input('ticket_id'),
            'user_id' => Auth::user()->id,
            'ticketnotes' => $request->input('ticketnote')
        ]);

        $ticket = Ticket::where('id', $request->input('ticket_id'))->firstOrFail();

        $comment = Comment::create([
            'ticket_id' => $ticket->id,
            'user_id' => Auth::user()->id,
            'cust_id' => null,
            'comment' => 'Ticket note created',
            'commenttype' => 'tickethistory',
        ]);

        $ticketinfo = view('admin.superadmindashboard.allticketsinfo', compact('ticket'))->render();
        $comment->ticketinfo = $ticketinfo;

        event(new ChatMessageEvent(null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,$ticket->id,$ticket->cust->id,$comment,'tickethistory',Auth::user()->name));

        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Ticket note created';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        try{
            $users = User::get();
            foreach($users as $user){
                if($user->can('All Tickets') && $user->usetting->emailnotifyon == 1 && $user->id != $ticket->selfassignuser_id  && Auth::id() != $user->id && setting('NOTE_CREATE_MAILS') == 'on'){
                    $createduser = User::findOrFail($ticketnote->user_id);
                    $ticketData = [
                        'ticket_id' => $ticket->ticket_id,
                        'note_username' => $createduser->name,
                        'ticket_note' => $ticketnote->ticketnotes,
                        'ticket_admin_url' => fetchticketviaautoviewurl($ticket,$user->id),
                        'ticket_category' => $ticket->category != null ? $ticket->category->name : 'Category not available',
                        'item_name' => $ticket->item_name != null ? $ticket->item_name : 'Item Name not available',
                    ];
                    dispatch((new MailSend($user->email, 'send_mail_to_admin_when_ticket_note_created', $ticketData)));
                }
            }
        }
        catch(\Exception $e){
            return response()->json(['success'=> lang('The note was successfully submitted.', 'alerts')]);
        }


        return response()->json(['success'=> lang('The note was successfully submitted.', 'alerts')]);
    }

    public function noteshow($ticket_id)
    {
        $ticket = Ticket::where('ticket_id', $ticket_id)->firstOrFail();
        $comments = $ticket->comments;
        $category = $ticket->category;

        $title = Apptitle::first();
        $data['title'] = $title;

        $footertext = Footertext::first();
        $data['footertext'] = $footertext;

        $seopage = Seosetting::first();
        $data['seopage'] = $seopage;

        $post = Pages::all();
        $data['page'] = $post;


        return view('admin.viewticket.note', compact('ticket','category', 'comments', 'title','footertext'))->with($data);
    }

    public function notedestroy($id)
    {
        $ticketnotedelete = Ticketnote::find($id);

        $ticket = Ticket::where('id', $ticketnotedelete->ticket_id)->firstOrFail();

        $ticketnotedelete->delete();

        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Ticket note Deleted';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        return response()->json(['success'=> lang('The note was successfully deleted.', 'alerts')]);


    }

    public function sublist(Request $request){

        $parent_id = $request->cat_id;
        $subcategories = [];

        return response()->json([
            'subcategories' => $subcategories
        ]);

    }


    public function changepriority(Request $req){

        $this->validate($req, [
            'priority_user_id' => 'required',
        ]);

        $priority = Ticket::find($req->priority_id);
        $priority->priority = $req->priority_user_id;
        $priority->update();

        $priorityname = $priority->priority;

        $comment = Comment::create([
            'ticket_id' => $priority->id,
            'user_id' => Auth::user()->id,
            'cust_id' => null,
            'comment' => 'Ticket priority changed',
            'commenttype' => 'tickethistory',
        ]);

        $ticket = $priority;
        $ticketinfo = view('admin.superadmindashboard.allticketsinfo', compact('ticket'))->render();
        $comment->ticketinfo = $ticketinfo;

        event(new ChatMessageEvent(null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,$priority->id,$priority->cust->id,$comment,'tickethistory',Auth::user()->name));

        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Ticket priority changed';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        return response()->json(['priority' => $priorityname,'success' => lang('Updated successfully', 'alerts')], 200);
    }

    public function alltickets()
    {


        $title = Apptitle::first();
        $data['title'] = $title;

        $footertext = Footertext::first();
        $data['footertext'] = $footertext;

        $seopage = Seosetting::first();
        $data['seopage'] = $seopage;

        $post = Pages::all();
        $data['page'] = $post;

        $totalData = Ticket::with('comments', 'cust')->get();

        $completeData = $totalData->filter(function ($data) {
            $data['encryptId'] = encrypt($data->id);
            return $data;
        });
        $data['completeData'] = $completeData;

        $tickettypeshow = 'notmentioned';
        $tickettype = 'notmentioned';
        if(request()->query('ticketdata') == 'unassignedtickets'){
            $this->authorize('Unassigned Tickets');
            $tickettypeshow = 'Unassigned Tickets';
            $tickettype = 'unassignedticketslocalstore';
            $alltickets = Ticket::whereNull('myassignuser_id')->whereNull('selfassignuser_id')->latest('updated_at')->where('status', '!=' ,'Closed')->get();
        }elseif(request()->query('ticketdata') == 'mytickets'){
            $this->authorize('My Tickets');
            $tickettypeshow = 'My Tickets';
            $tickettype = 'myticketslocalstore';
            $alltickets = Ticket::where('selfassignuser_id', auth()->id())->where('status', '!=' ,'Closed')->where('status', '!=' ,'Suspend')->latest('updated_at')->get();
        }elseif(request()->query('ticketdata') == 'myclosedtickets'){
            $this->authorize('Solved');
            $tickettypeshow = 'My Closed Tickets';
            $tickettype = 'myclosedticketslocalstore';
            $alltickets = Ticket::where('closedby_user', auth()->id())->latest('updated_at')->get();
        }elseif(request()->query('ticketdata') == 'tickettrashed'){
            $this->authorize('Trashed');
            $tickettypeshow = 'Trashed Tickets';
            $tickettype = 'trashedticketslocalstore';
            $alltickets = Ticket::onlyTrashed()->latest('updated_at')->get();
        }else{
            if(request()->query('ticketdata') == 'alltickets'){
                $this->authorize('All Tickets');
                $tickettypeshow = 'All Tickets';
                $tickettype = 'allticketslocalstore';
                $alltickets = Ticket::latest('updated_at')->get();
            }else{
                $alltickets = [];
            }
        }
        $data['ticketnotifyid'] = request()->query('ticketid') != null ? request()->query('ticketid') : null;
        $data['tickettypeshow'] = $tickettypeshow;
        $data['tickettype'] = $tickettype;
        $data['alltickets'] = $alltickets;

        foreach ($alltickets as $allticket) {
            $livechatdata = Comment::where('ticket_id', $allticket->id)->get();
            $unreadIndexNumber = 0;
            foreach ($livechatdata as $message) {
                if ($message->cust_id !== null && $message->status != "seen") {
                    $unreadIndexNumber = $unreadIndexNumber + 1;
                }
            }
            $allticket->unreadIndexNumber = $unreadIndexNumber;
            $allticket->lastMessage = $livechatdata->isNotEmpty() ? $livechatdata->last() : null;
        }

        $ticketnote = DB::table('ticketnotes')->pluck('ticketnotes.ticket_id')->toArray();
        $data['ticketnote'] = $ticketnote;

        $categories = Category::whereIn('display', ['ticket', 'both'])->where('status', '1')->get();
        $data['categories'] = $categories;

        $userdatas = User::where('status', 1)->get();
        $data['userdatas'] = $userdatas;

        $user = User::where('id','!=',Auth::id())->where('status',1)->get();
        $data['user'] = $user;

        return view('admin.superadmindashboard.alltickets')->with($data);
    }
}
