<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Models\Apptitle;
use App\Models\Footertext;
use App\Models\Seosetting;
use App\Models\Pages;
use App\Models\Ticket\Ticket;
use DB;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
use App\Models\Ticket\Comment;
use App\Events\ChatMessageEvent;
use App\Models\LiveChatCustomers;
use Illuminate\Support\Facades\Crypt;
use Torann\GeoIP\Facades\GeoIP;
use Jenssegers\Agent\Agent;
use App\Models\EmployeeActivity;
use Illuminate\Support\Facades\Auth;

class AdminTicketViewController extends Controller
{
    public function customerprevioustickets($cust_id)
    {
        $title = Apptitle::first();
        $data['title'] = $title;

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

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

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

        $cust_id = decrypt($cust_id);

        $users = LiveChatCustomers::find($cust_id);
        $data['users'] = $users;

        $total = Ticket::where('cust_id', $cust_id)->latest('updated_at')->get();
        $data['total'] = $total;

        $custsimillartickets = Ticket::with('ticketnote','category','cust','selfassign')->where('cust_id', $cust_id)->latest('updated_at')->get();
        $custsimillartickets = $custsimillartickets->each(function ($ticket) {
            $ticket->encrypted_id = Crypt::encrypt($ticket->id);
            $ticket->viewRouteUrl = fetchticketviewurl($ticket);
            return $ticket;
        });
        $data['custsimillartickets'] = $custsimillartickets;

        $active = Ticket::where('cust_id', $cust_id)->whereIn('status', ['New', 'Re-Open', 'Inprogress'])->get();
        $data['active'] = $active;

        $closed = Ticket::where('cust_id', $cust_id)->where('status', 'Closed')->get();
        $data['closed'] = $closed;

        $onhold = Ticket::where('cust_id', $cust_id)->where('status', 'On-Hold')->get();
        $data['onhold'] = $onhold;

        return view('admin.viewticket.customerprevioustickets')->with($data);
    }

    public function selfassignticketview()
    {
        $title = Apptitle::first();
        $data['title'] = $title;

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

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

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

        $selfassignedtickets = Ticket::where('selfassignuser_id', auth()->id())->where('status', '!=' ,'Closed')->where('status', '!=' ,'Suspend')->latest('updated_at')->get();
        $perPage = request()->input('per_page', 10);
        $currentPage = request()->input('page', 1);
        $finalResult = $selfassignedtickets->forPage($currentPage, $perPage)->values();

        $data['ticketdata'] = new \Illuminate\Pagination\LengthAwarePaginator(
            $finalResult,
            $selfassignedtickets->count(),
            $perPage,
            $currentPage,
            ['path' => request()->url(), 'query' => request()->query()]
        );
        $data['perPage'] = $perPage;

        if(request()->ajax()){
            return response()->json([
                'rendereddata'=>view('admin.superadmindashboard.tabledatainclude', ['ticketdata' => $data['ticketdata'], 'perPage' => $perPage])->render(),
            ]);
        }

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


        $selfassignedticketsnew = Ticket::where('selfassignuser_id', auth()->id())->where('status', 'New')->count();
        $data['selfassignedticketsnew'] = $selfassignedticketsnew;

        $selfassignedticketsinprogress = Ticket::where('selfassignuser_id', auth()->id())->where('status', 'Inprogress')->count();
        $data['selfassignedticketsinprogress'] = $selfassignedticketsinprogress;

        $selfassignedticketsonhold = Ticket::where('selfassignuser_id', auth()->id())->where('status', 'On-Hold')->count();
        $data['selfassignedticketsonhold'] = $selfassignedticketsonhold;

        $selfassignedticketsreopen = Ticket::where('selfassignuser_id', auth()->id())->where('status', 'Re-Open')->count();
        $data['selfassignedticketsreopen'] = $selfassignedticketsreopen;

        $selfassignedticketsoverdue = Ticket::where('selfassignuser_id', auth()->id())->where('overduestatus', 'Overdue')->count();
        $data['selfassignedticketsoverdue'] = $selfassignedticketsoverdue;

        $selfassignedticketsclosed = Ticket::where('selfassignuser_id', auth()->id())->where('status', 'Closed')->count();
        $data['selfassignedticketsclosed'] = $selfassignedticketsclosed;

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

    public function tickettrashedrestore(Request $request, $id)
    {
        $id = decrypt($id);
        $tickettrashedrestore = Ticket::with('users','selfassign')->onlyTrashed()->findOrFail($id);
        $commenttrashedrestore = $tickettrashedrestore->comments()->onlyTrashed()->get();

        if (count($commenttrashedrestore) > 0) {


            $commenttrashedrestore->each->restore();

            $media = Media::onlyTrashed()->where('model_id', $tickettrashedrestore->id)->where('model_type', get_class($tickettrashedrestore))->where('collection_name', 'ticket')->get();

            foreach ($media as $media) {
                $media->restore();
            }

            foreach ($commenttrashedrestore as $comment) {
                foreach(Media::onlyTrashed()->where('model_id', $comment->id)->where('model_type', get_class($comment))
                ->where('collection_name', 'comments')->get() as $media){
                    $media->restore();
                }

            }

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

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

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

            $tickettrashedrestore->restore();

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

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

            $media = Media::onlyTrashed()->where('model_id', $tickettrashedrestore->id)->where('model_type', get_class($tickettrashedrestore))->where('collection_name', 'ticket')->get();

            foreach ($media as $media) {
                $media->restore();
            }

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

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

            event(new ChatMessageEvent(null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,$tickettrashedrestore->id,$tickettrashedrestore->cust->id,$newcomment,'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 restored';
            $activity->ip_address = $geolocation->ip;
            $activity->browser = $agent->browser();
            $activity->device = $agent->device();
            $activity->save();

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

        }
    }

    public function tickettrasheddestroy($id)
    {
        $id = decrypt($id);
        $tickettrasheddelete = Ticket::onlyTrashed()->findOrFail($id);
        $commenttrasheddelete = $tickettrasheddelete->comments()->onlyTrashed()->get();


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

            foreach ($media as $medias) {

                    $medias->forceDelete();

            }
            $medias = $tickettrasheddelete->comments()->onlyTrashed()->get();

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

                    $mediasss->forceDelete();
                }

            }
            $commenttrasheddelete->each->forceDelete();

            $newcomment = [
                'ticket_id' => $tickettrasheddelete->id,
                'user_id' => Auth::user()->id,
                'ticketpermdeletingaction' => 'ticketpermdeletingaction',
            ];

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

            $tickettrasheddelete->forceDelete();

            $geolocation = GeoIP::getLocation(request()->getClientIp());
            $agent = new Agent();
            $activity = new EmployeeActivity();
            $activity->user_id = Auth::user()->id;
            $activity->activity_type = 'Ticket Permanently 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')]);
        }else{

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

            foreach ($media as $medias) {

                    $medias->forceDelete();

            }

            $newcomment = [
                'ticket_id' => $tickettrasheddelete->id,
                'user_id' => Auth::user()->id,
                'ticketpermdeletingaction' => 'ticketpermdeletingaction',
            ];

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

            $tickettrasheddelete->forceDelete();

            $geolocation = GeoIP::getLocation(request()->getClientIp());
            $agent = new Agent();
            $activity = new EmployeeActivity();
            $activity->user_id = Auth::user()->id;
            $activity->activity_type = 'Ticket permanently 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 tickettrashedview($id)
    {
        $id = decrypt($id);
        $tickettrashedview = Ticket::onlyTrashed()->findOrFail($id);
        $data['tickettrashedview'] = $tickettrashedview;

        $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.assignedtickets.trashedticketview')->with($data);
    }


    public function alltrashedticketrestore(Request $request)
    {

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

        $id_array = array_map(function ($encryptedValue) {
            return decrypt($encryptedValue);
        }, $id_arrays);

        $sendmails = Ticket::with('users','selfassign')->onlyTrashed()->whereIn('id', $id_array)->get();

        foreach($sendmails as $tickettrashedrestoreall){
            $commenttrashedrestorealls = $tickettrashedrestoreall->comments()->onlyTrashed()->get();
            foreach($commenttrashedrestorealls as $commenttrashedrestoreall){
                    $commenttrashedrestoreall->restore();
                    foreach(Media::onlyTrashed()->where('model_id', $commenttrashedrestoreall->id)->where('model_type', get_class($commenttrashedrestoreall))
                    ->where('collection_name', 'comments')->get() as $media){
                        $media->restore();
                    }
            }
            $media = Media::onlyTrashed()->where('model_id', $tickettrashedrestoreall->id)->where('model_type', get_class($tickettrashedrestoreall))->where('collection_name', 'ticket')->get();

            foreach ($media as $media) {
                $media->restore();
            }
            $tickettrashedrestoreall->restore();

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

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

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

        }

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

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

    }

    public function alltrashedticketdelete(Request $request)
    {
        $id_arrays = $request->input('id');

        $id_array = array_map(function ($encryptedValue) {
            return decrypt($encryptedValue);
        }, $id_arrays);

        $sendmails = Ticket::onlyTrashed()->whereIn('id', $id_array)->get();

        foreach($sendmails as $tickettrasheddeleteeall){

            $commenttrasheddeleteall = $tickettrasheddeleteeall->comments()->onlyTrashed()->get();


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

                foreach ($media as $medias) {

                        $medias->forceDelete();

                }

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

                        $mediasss->forceDelete();
                    }

                    $mediass->forceDelete();
                }

                $newcomment = [
                    'ticket_id' => $tickettrasheddeleteeall->id,
                    'user_id' => Auth::user()->id,
                    'ticketpermdeletingaction' => 'ticketpermdeletingaction',
                ];

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

                $sendmails->each->forceDelete();

                $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')]);
            }else{

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

                foreach ($media as $medias) {

                    $medias->forceDelete();

                }

                $sendmails->each->forceDelete();

                $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')]);

            }

        }
    }

}
