<?php

namespace App\Http\Controllers;

use App\Tickets;
use App\Ticket_attachments;
use DB;
use Datatables;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Mail\SendMailable;
use Auth;
use File;

class TicketsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function __construct()
    {
        $this->middleware('auth');
        //$this->middleware('auth', ['except' => ['create','usertickets','store','index','show','update','updatepriorities','userindex','getSubcategory','edit','useractivetickets','usercompletetickets','ticketcomments','destroy']]);
    }

    public function index(Request $request)
    {   
        $flagstatus = $request->input('status');
        
        if(is_null($flagstatus))
        {
            $flagstatus = 5;
        }
        
        $category = DB::table('categories')->whereNull('deleted_at')->pluck("name","id");
        $statuses = DB::table('statuses')->whereNull('deleted_at')->pluck("name","id");
        $status = 1;
        return view('tickets.index',compact('category','status','statuses','flagstatus'));
    }

    public function complete()
    {
        $category = DB::table('categories')->whereNull('deleted_at')->pluck("name","id");
        $statuses = DB::table('statuses')->whereNull('deleted_at')->pluck("name","id");
        $status = 2;
        $flagstatus = 5;
        return view('tickets.index',compact('category','status','statuses','flagstatus'));
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function useractivetickets()
    {

        $category = DB::table('categories')->whereNull('deleted_at')->pluck("name","id");
        $status = 1;
        return view('tickets.usertickets',compact('category','status'));

    }
    public function usercompletetickets()
    {
        $category = DB::table('categories')->whereNull('deleted_at')->pluck("name","id");
        $status = 2;
        return view('tickets.usertickets',compact('category','status'));
    }

    public function create()
    {
		$category = DB::table('subcategories')
		->join('categories', 'categories.id', '=', 'subcategories.category_id')
		->select('categories.*')
		->whereNull('subcategories.deleted_at')
		->whereNull('categories.deleted_at')
		->pluck("name","id");
		
		$shop_name = env('SHOP_NAME');
        $priority = DB::table('priorities')->whereNull('deleted_at')->get();
        $statuses = DB::table('statuses')->whereNull('deleted_at')->where('default_set', 1)->get();
		
        if($shop_name != '')
        {
            $cat_id = DB::table('categories')->select('id')->where('name','LIKE',"%{$shop_name}%")->get();
            $cat_id = $cat_id[0]->id;
            $sub_category = DB::table("subcategories")->whereNull('deleted_at')->where("category_id",$cat_id)->pluck("name","id");

            return view('tickets.create',compact('category','priority', 'statuses','sub_category','cat_id'));
        }
        else
        {
            return view('tickets.create',compact('category','priority', 'statuses'));
        }
    }

    public function getSubcategory($id) 
    {
        $sub_category = DB::table("subcategories")->whereNull('deleted_at')->where("category_id",$id)->pluck("name","id");
        return json_encode($sub_category);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
     
    public function store(Request $request)
    {
		request()->validate([
		'subject' => 'required',
		'content' => 'required',
		'priority_id' => 'required|not_in:0',
		'category_id' => 'required|not_in:0',
		'sub_category_id' => 'required|not_in:0',
		'g-recaptcha-response' => ['required'],
		], [
		'priority_id.required' => 'priority is required',
		'category_id.required' => 'category is required',
		'g-recaptcha-response.required' => 'ReCaptcha required!',

		]);

        $user = DB::table('users')->where('email', $request['email'])->whereNull('deleted_at')->first();
		
		if (is_null($user)) {
			DB::table('users')->insert([
				'email' => $request['email'],
				'name' => $request['username'],
				'created_at' => date('Y-m-d H:i:s'),
				'updated_at' => date('Y-m-d H:i:s')
			]);

			$last_user_id = DB::getPdo()->lastInsertId();
		}
		else
		{
			$last_user_id = $user->id;
		}
		
        $ticket = DB::table('tickets')->insert([
            'email' => $request['email'],
            'user_id' => $last_user_id,
            'username' => $request['username'],
            'domain_name' => $request['domain_name'],
            'subject' => $request['subject'],
            'content' => $request['content'],
            'ticketable_type' => $request['ticketable_type'],
            'ticketable_id' => $request['ticketable_id'],
            'priority_id' => $request['priority_id'],
            'category_id' => $request['category_id'],
            'sub_category_id' => $request['sub_category_id'],
            'status_id' => $request['status_id'],
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ]);

        $last_insertd_id = DB::getPdo()->lastInsertId();
        $message = "Your ticket #".$last_insertd_id." has been created. One of our representative will get in touch with you soon.";

        $tickets_data = DB::table('tickets')
            ->join('priorities', 'tickets.priority_id', '=', 'priorities.id')
            ->join('categories', 'tickets.category_id', '=', 'categories.id')
            ->join('subcategories', 'tickets.sub_category_id', '=', 'subcategories.id')
            ->select('tickets.*', 'priorities.name AS pname', 'categories.name AS cname', 'subcategories.name as subname')
            ->where("tickets.id", "=", $last_insertd_id)
            ->orderBy('tickets.id', 'desc')
            ->get();

        $from = 'Simprosys Infomedia <support@simprosys.com>';
        $to = 'Support System <'.trim($request->input('email')).'>';
        $cc = 'Support System <jaydeep@simprosys.net>';
        $bcc = 'Support System <jaydeep@simprosys.net>';
        $base_url = url('/tickets');

        $message_email ="Dear [USER_NAME],<br/><br/>We would like to acknowledge that we've received your request and a ticket has been created with the Ticket ID- #[TICKET_ID]. <br/>A support representative will be reviewing your request and will send you a personal response. (usually within 24 hours).<br/><br/>To view the status of the ticket or add comments, please visit<br/>[VIEW_TICKET_LINK]<br/><br/>Thank you for your patience.<br/>Yours sincerly<br/>Support Ticketing System";

        //replace template var with value
        $token_array = array(
                'USER_NAME'  => $request['username'],
                'TICKET_ID' => $last_insertd_id,
                'APP_NAME'  => $tickets_data[0]->cname,
                'VIEW_TICKET_LINK'=> '<a href="' .$base_url.'/'.$last_insertd_id .'">View Ticket</a>'
            );

        $subject = Helpers::parseTemplate('[#TICKET_ID] Request received for [APP_NAME]',$token_array);
        $message_email = Helpers::buildTemplate($message_email,'user');
        $emailContent = Helpers::parseTemplate($message_email,$token_array);
        $data = array('from' => $from, 'to' => $to, 'cc' => $cc, 'cc' => $cc, 'bcc' => $bcc, 'subject' => $subject, 'message' => $emailContent);
		
        Helpers::mail($data);

        //Admin part

        $configurations = DB::table('configurations')->where("id", "=", 1)->get();
        $to = 'Support System'.trim($configurations[0]->config_val);
        $message_email_admin ="Hello support,<br/><br/>New ticket created with the Ticket ID-  #[TICKET_ID]. <br/><br/>Name : [USER_NAME].<br/>Email : [USER_EMAIL].<br/>App name : [APP_NAME].<br/>Category : [CATEGORY_NAME].<br/>Priority : [PRIORITY_NAME].<br/><br/>To view The full ticket or respond to the ticket, please visit<br/>[VIEW_TICKET_LINK]<br/><br/>Best regrads<br/>Support Ticketing System";

        //replace template var with value
        $token_array_admin = array(
            'USER_NAME'  => $request['username'],
            'USER_EMAIL'  => $request['email'],
            'APP_NAME'  => $tickets_data[0]->cname,
            'CATEGORY_NAME'  => $tickets_data[0]->subname,
            'PRIORITY_NAME'  => $tickets_data[0]->pname,
            'TICKET_ID' => $last_insertd_id,
            'VIEW_TICKET_LINK'=> '<a href="' .$base_url.'/'.$last_insertd_id .'">View Ticket</a>'
        );
		
        $message_email_admin = Helpers::buildTemplate($message_email_admin,'admin');
        $emailContent = Helpers::parseTemplate($message_email_admin,$token_array_admin);
        $data = array('from' => $from, 'to' => $to, 'cc' => $cc, 'cc' => $cc, 'bcc' => $bcc, 'subject' => $subject, 'message' => $emailContent);
		
        Helpers::mail($data);

        if(Auth::guest())
        {
            return redirect('useractivetickets')->with('success',$message);
        }
        else {
            return redirect('tickets')->with('success',$message);
        }
    } 
     
    /**
     * Display the specified resource.
     *
     * @param  \App\Tickets  $tickets
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {

		$tickets = DB::table('tickets')->join('priorities', 'tickets.priority_id', '=', 'priorities.id')
		->join('categories', 'tickets.category_id', '=', 'categories.id')
		->join('subcategories', 'tickets.sub_category_id', '=', 'subcategories.id')
		->join('statuses', 'tickets.status_id', '=', 'statuses.id')
		->select('tickets.*', 'priorities.name AS pname', 'categories.name AS cname', 'categories.shortname AS shortname', 'subcategories.name as subname', 'statuses.name as sname', 'statuses.color as scolor', 'priorities.color as pcolor')
		->where("tickets.id", "=", $id)
		->orderBy('tickets.id', 'desc')
		->get();
			
        $statuses = DB::table('statuses')->whereNull('deleted_at')->get();
        $time_durations = DB::table('time_durations')->get();
        $priority = DB::table('priorities')->whereNull('deleted_at')->get();
        
        $shopdetails = DB::table('shops_master')->where('id', $tickets[0]->shop_id)->whereNull('deleted_at')->get();
    
        $cannedresponses = DB::table('cannedresponses')
        ->select('title','content')
        ->where("category_id", "like", "%".$tickets[0]->category_id."%")
        ->whereNull('deleted_at')
        ->orderBy('title', 'asc')
        ->get()
        ->map(function ($item) {   
            $item->content = str_replace("\r\n", '', $item->content);
            return $item;
        });
        
        $token_cannedresponses_template = array(
            'NAME'  => $tickets[0]->username,
            'EMAIL'  => $tickets[0]->email,
            'TICKET_NUMBER'  => $id,
            'TICKET_SUBJECT'  => $tickets[0]->subject,
            'TICKET_DATE'  => $tickets[0]->created_at,
            'TICKET_STATUS' => $tickets[0]->sname,
        );

        
        $results = array();
        foreach ($cannedresponses as $result)
        {
            $message_email = Helpers::buildTemplate($result->content,'user');
            $cannedresponses_message = Helpers::parseTemplate($message_email,$token_cannedresponses_template);
            $results[] =  ['title' => $result->title,'content' => $cannedresponses_message];
        }
        
       $getjsondata = json_encode($results);
       $cannedresponses = collect(json_decode($getjsondata, true));
        
        if(Auth::guest())
        {
                $comments = DB::table('comments')
                ->join('users', 'comments.user_id', '=', 'users.id')
                ->select('comments.*', 'users.name AS uname')
                ->where([['ticket_id', '=', $id], ['support_team_display', '=', '0'],])->orderBy('comments.id', 'asc')->get();
        }
        else{
                $comments = DB::table('comments')
                ->join('users', 'comments.user_id', '=', 'users.id')
                ->select('comments.*', 'users.name AS uname','users.email AS uemail')
                ->where("comments.ticket_id", "=", $id)->orderBy('comments.id', 'asc')->get();
        }
		
		 $tickets_attachements = DB::table('ticket_attachments')
        ->select('ticket_attachments.file_name','ticket_attachments.id','ticket_attachments.comment_id','ticket_attachments.file_ext')
        ->where("ticket_attachments.ticket_id", "=", $id)->get();
		
		  $tickets_notifications = DB::table('notifications')
        ->join('users', 'notifications.user_id', '=', 'users.id')
        ->join('statuses', 'notifications.status_id', '=', 'statuses.id')
        ->leftjoin('time_durations', 'notifications.time_durations_id', '=', 'time_durations.id')
        ->select('notifications.*', 'users.name AS uname','users.email AS uemail','statuses.name AS status_name','time_durations.name as duration_name')
        ->where("notifications.ticket_id", "=", $id)->get();
		
        return view('tickets.show',compact('tickets','id', 'comments', 'statuses', 'priority', 'cannedresponses', 'shopdetails', 'tickets_attachements','time_durations','tickets_notifications'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Tickets  $tickets
     * @return \Illuminate\Http\Response
     */
    public function edit(Request $req,$id)
    {
        $tickets = \App\Tickets::find($id);
        $tickets->status_id=$req->status_id;
        $tickets->save();

        if ($req->status_id == 2) {

            $from = 'Simprosys Infomedia <support@simprosys.com>';
            $to = 'Support System'.trim($tickets->email);
            $cc = 'Support System <jaydeep@simprosys.net>';
            $bcc = 'Support System <jaydeep@simprosys.net>';
            $base_url = $tickets->base_url.'show.php';

            $subject = 'Ticket resolved and closed #'.$id;
            $message_email = "Dear [USER_NAME],<br/><br/>Please be aware that Ticket ID- #[TICKET_ID].has been resolved and closed. <br/>Please let the Client Support team know if you have any further questions or issues.<br/><br/>To view the status of the ticket or add comments, please visit<br/>[VIEW_TICKET_LINK]<br/><br/>Thank you for your patience<br/>Yours sincerly<br/>Support Ticketing System";

            //replace template var with value
            $token_array_resolved = array(
                'USER_NAME'  => $tickets->username,
                'TICKET_ID' => $id,
                'VIEW_TICKET_LINK'=> '<a href="' .$base_url.'?id='.$id .'">View Ticket</a>'
            );
            $message_email = Helpers::buildTemplate($message_email,'admin');
            $emailContent_resolved = Helpers::parseTemplate($message_email,$token_array_resolved);
            $data = array('from' => $from, 'to' => $to, 'cc' => $cc, 'cc' => $cc, 'bcc' => $bcc, 'subject' => $subject, 'message' => $emailContent_resolved);
			
            Helpers::mail($data);
        }
		
				if(Auth::guest())
				{
					if ($req->status_id == 2) {
						return redirect('usercompletetickets')->with('success','The Ticket has been completed!');
					}
					else
					{
						return redirect('useractivetickets')->with('success','The Ticket has been reopened!');
					}
				}
				else
				{
					if ($req->status_id == 2) {
						return redirect('complete')->with('success','The Ticket has been completed!');
					}
					else
					{
						return redirect('tickets')->with('success','The Ticket has been reopened!');
					}
				}
    }
    
    public function ticketcomments(Request $request)
    {
        //dd($request->all());

		request()->validate([
		'content' => 'required|string',
		], [
		'content.required' => 'Please enter the content',
		]);
   
        DB::table('comments')->insert([
            'content' => $request['content'],
            'ticket_id' => $request['ticket_id'],
            'user_id' => $request['user_id'],
            'support_team_display' => $request['support_team_display'],
            'commentable_type' => $request['commentable_type'],
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ]);

        $comment_id = DB::getPdo()->lastInsertId();


                /* File Attachments*/
                $time=time();
                $files = $request->file('file');
                $destinationPath =base_path()."/img/atteach/";
                if($request->hasFile('file')) {
                    $counter = 1;
                      foreach ($files as $file) {
                        $img=$file->getClientOriginalName();
                        if($img != 'blob'){ 
                        $file_ext = $file->getClientOriginalExtension();
                        $file_size = $file->getSize();

                        $title_img = str_slug($img, '-');
                        $img = $title_img . time() . '.' . $file->getClientOriginalExtension();
                        $path = $file->storeAs('photos', $img);

                        $all_files_name [] = ['img_name' => $img];

                        $ticket_attachments = DB::table('ticket_attachments')->insert([
                            'file_name' => $img,
                            'file_ext' => $file_ext,
                            'file_size' => $file_size,
                            'shop_id' => $request['category_id'],
                            'ticket_id' => $request['ticket_id'],
                            'user_id' => $request['user_id'],
                            'comment_id' => $comment_id,  
                            'created_at' => date('Y-m-d H:i:s'),
                            'updated_at' => date('Y-m-d H:i:s')
                        ]);


                        $upload_success = $file->move($destinationPath, $img);
                        if ($counter++ == 5) break;
                    }
                    }
                }

                /* End File Attachments*/


       // $affected = DB::table('tickets')->where('id', '=', $request['ticket_id'])->update(array('ticketable_type' => 1));
        $affected = DB::table('tickets')->where('id', '=', $request['ticket_id'])->update(array('ticketable_type' => 1,'updated_at' => date('Y-m-d H:i:s')));
        $last_insertd_id = $request['ticket_id'];
        $support_email = "jaydeep@simprosys.net";

        $tickets = \App\Tickets::find($request['ticket_id']);
        $from = 'Simprosys Infomedia <support@simprosys.com>';
        $cc = 'Support System <jaydeep@simprosys.net>';
        $bcc = 'Support System <jaydeep@simprosys.net>';


        $category = DB::table('categories')->where("id", "=", $tickets->category_id)->get();
        
        $tickets_attachements = DB::table('ticket_attachments')
        ->select('ticket_attachments.file_name','ticket_attachments.id','ticket_attachments.comment_id','ticket_attachments.file_ext')
        ->where("ticket_attachments.comment_id", "=", $comment_id)->get();
		
        if($request['commentable_type'] == 0){

            $base_url = url('/tickets');
            $configurations = DB::table('configurations')->where("id", "=", 1)->get();
            $to = 'Support System <'.trim($configurations[0]->config_val).'>';
            $message_email = "Hello Support,<br/><br/><b>Comment Description : </b> [COMMENT_DESCRIPTION]<br/><br/>To view The full ticket or respond to the ticket, please visit<br/>[VIEW_TICKET_LINK]<br/><br/>Best regrads<br/>[USER_NAME]";

            $token_array_user = array(
                'USER_NAME'  => $tickets->username,
                'COMMENT_DESCRIPTION' => $request['content'],
                'VIEW_TICKET_LINK'=> '<a href="' .$base_url.'/'.$last_insertd_id .'">View Ticket</a>'
            );
            $subject = '#[TICKET_ID] New comment has been posted by support team';
            $message_email = Helpers::buildTemplate($message_email,'admin');
            $emailContent = Helpers::parseTemplate($message_email,$token_array_user);
            $data = array('from' => $from, 'to' => $to, 'cc' => $cc, 'cc' => $cc, 'bcc' => $bcc, 'subject' => $subject, 'message' => $emailContent);
			
            Helpers::mail($data);
        }
		else{

            $base_url = $tickets->base_url.'show.php';
			
            if($request['support_team_display'] == 0)
            {
                $to = 'Support System <'.trim($tickets->email) .'>';
                //$message_email = "Hello [USER_NAME],<br/><br/>There is update posted by customer.<br/><br/>Ticket ID : #[TICKET_ID]</br>Comment :</b> [COMMENT_DESCRIPTION]<br/><br/>To view the status of the ticket or add comments, please visit<br/>[VIEW_TICKET_LINK]<br/><br/>To view or modify the ticket, please visit below link<br/>[VIEW_TICKET_LINK]<br/><br/>Thank you for your patience.<br/>Best regards,<br/>[APP_NAME]<br/>Simprosys Support Team";
                $ticketemailtemplates = DB::table('ticketemailtemplates')->where("id", "=", 2)->get();
                $message_subject = trim($ticketemailtemplates[0]->title);
                $message_email = trim($ticketemailtemplates[0]->content);
                
                $token_array_admin = array(
                    'USER_NAME'  => $tickets->username,
                    'TICKET_ID'  => $last_insertd_id,
                    'APP_NAME'  => $category[0]->name,
                    'COMMENT_DESCRIPTION' => $request['content'],
                    'VIEW_TICKET_LINK'=> '<a href="' .$base_url.'?id='.$last_insertd_id .'">View Ticket</a>'
                );
                $subject = Helpers::parseTemplate($message_subject,$token_array_admin);
                $message_email = Helpers::buildTemplate($message_email,'user');
                $emailContent_admin = Helpers::parseTemplate($message_email,$token_array_admin);
                $data = array('from' => $from, 'to' => $to, 'cc' => $cc, 'cc' => $cc, 'bcc' => $bcc, 'subject' => $subject, 'message' => $emailContent_admin);
				
                Helpers::mail($data);
            }
        }

		$comments = DB::table('comments')
		->join('users', 'comments.user_id', '=', 'users.id')
		->select('comments.*', 'users.name AS uname', 'users.email AS uemail')
		->where('comments.id', '=', $comment_id)->get();
		return response()->json(['comment'=>$comments,'tickets_attachements'=>$tickets_attachements]);
    }
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Tickets  $tickets
     * @return \Illuminate\Http\Response
     */
    public function update(Request $req)
    {
        //dd($req->all());
        $last_commnets = DB::table('comments')->where('ticket_id', $req->ticket_id)->latest()->first();
        //dd($last_commnets);
        if(is_null($last_commnets))
        {
            $last_cmnt_id = 0;
        }
        else
        {   
            $last_cmnt_id = $last_commnets->id;
        }
        if(is_null($req->time_durations))
        {
            $time_durations = 0;
        }
        else
        {   
            $time_durations = $req->time_durations;
        }


                $tickets = \App\Tickets::find($req['ticket_id']);
                $base_url = $tickets->base_url.'show.php';
            
                $category = DB::table('categories')->where("id", "=", $tickets->category_id)->get();
                $to = 'Support System <'.trim($tickets->email).'>';
                $from = 'Simprosys Infomedia <support@simprosys.com>';
                $cc = 'Support System <jaydeep@simprosys.net>';
                $bcc = 'Support System <jaydeep@simprosys.net>';
                $ticketemailtemplates = DB::table('ticketemailtemplates')->where("id", "=", 5)->get();
                $message_subject = trim($ticketemailtemplates[0]->title);
                $message_email = trim($ticketemailtemplates[0]->content);
                
                $token_array_admin = array(
                    'USER_NAME'  => $tickets->username,
                    'TICKET_ID'  => $req['ticket_id'],
                    'APP_NAME'  => $category[0]->name,
                    'STATUS_NAME' => $req['sname'],
                    'VIEW_TICKET_LINK'=> '<a href="' .$base_url.'?id='.$req['ticket_id'] .'">View Ticket</a>'
                );
                $subject = Helpers::parseTemplate($message_subject,$token_array_admin);
                $message_email = Helpers::buildTemplate($message_email,'user');
                $emailContent_admin = Helpers::parseTemplate($message_email,$token_array_admin);
                $data = array('from' => $from, 'to' => $to, 'cc' => $cc, 'cc' => $cc, 'bcc' => $bcc, 'subject' => $subject, 'message' => $emailContent_admin);
                
                //Helpers::mail($data);


            $time_durations = DB::table('time_durations')->select('hours')->where('id', $req->time_durations)->first();
               //dd($time_durations); 
            if(is_null($time_durations))
            {
                $duration_dates = date('Y-m-d H:i:s');
                $status = 1;
            }
            else
            {   
                $duration_dates = date('Y-m-d H:i:s', strtotime('+'.$time_durations->hours.' hours',strtotime(date('Y-m-d H:i:s'))));
                $status = 0;
            }
            DB::table('notifications')->insert([
            'ticket_id' => $req->ticket_id,
            'user_id' => Auth::id(),
            'status_id' => $req->status_id,
            'ip_address' => $req->ip(),
            'time_durations_id' => $req->time_durations,
            'duration_dates' => $duration_dates,
            'last_comments_id' => $last_cmnt_id,
            'status' => $status,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ]);
        $notifications_id = DB::getPdo()->lastInsertId();

        $affected = DB::table('tickets')->where('id', '=', $req->ticket_id)->update(array('status_id' => $req->status_id));
        $statuses = DB::table('statuses')->where('id', '=', $req->status_id)->get();


         $tickets_notifications = DB::table('notifications')
        ->join('users', 'notifications.user_id', '=', 'users.id')
        ->join('statuses', 'notifications.status_id', '=', 'statuses.id')
        ->leftjoin('time_durations', 'notifications.time_durations_id', '=', 'time_durations.id')
        ->select('notifications.*', 'users.name AS uname','users.email AS uemail','statuses.name AS status_name','time_durations.name as duration_name')
        ->where("notifications.id", "=", $notifications_id)->get();

        return response()->json(['color'=>$statuses,'notification'=>$tickets_notifications]);
    }

    public function updatepriorities(Request $req)
    {
        $affected = DB::table('tickets')->where('id', '=', $req->ticket_id)->update(array('priority_id' => $req->priority_id));
        $priority = DB::table('priorities')->where('id', '=', $req->priority_id)->get();
        return response()->json(['color'=>$priority]);

    }

    public function updatemultipleimages(Request $request)
    {
        $target_dir =base_path()."/img/atteach/";
        $request_status = 1;
        if(isset($request['request']))
        {
            $request_status = $request['request'];
        }

        // Upload file
        if($request_status == 1){ 
           
        $last_commnets = DB::table('comments')->latest()->first();
        $new_comments_id = $last_commnets->id + 1;
        $files = $request->file('file');
        $img=$files->getClientOriginalName();
        $file_ext = $files->getClientOriginalExtension();
        $file_size = $files->getSize();
        $tickets = \App\Tickets::find($request['ticket_id']);
        $ticket_attachments = DB::table('ticket_attachments')->insert([
                'file_name' => $img,
                'file_ext' => $file_ext,
                'file_size' => $file_size,
                'shop_id' => $tickets->category_id,
                'ticket_id' => $request['ticket_id'],
                'user_id' => Auth::id(),
                'comment_id' => $new_comments_id,  
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ]); 
            $attachements_id = DB::getPdo()->lastInsertId();
          //$target_file = $target_dir . basename($_FILES["file"]["name"]);
          $msg = ""; 
          if ($files->move($target_dir, $img)) {
            return $attachements_id;
            $msg = "Successfully uploaded"; 
          }else{    
            $msg = "Error while uploading"; 
          } 
          echo $msg;
        }


        // Remove file
        if($request_status == 2){ 
          $filename = $target_dir.$request['name']; 
          if(File::delete($filename))
          {
             $ticket_attachments = Ticket_attachments::find($request['atach_id']);            
            // $ticket_attachments->delete();
           
          }
          exit;
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Tickets  $tickets
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {

	    $tickets = \App\Tickets::find($id)->delete();
       // $tickets->delete();
        if(Auth::guest())
        {
            return redirect('useractivetickets')->with('success','Ticket has been deleted');
        }
        else
        {
            return redirect('tickets')->with('success','Ticket has been deleted');
        }


    }
}
