<?php


namespace App\Http\Controllers\API;


use Illuminate\Http\Request;
use App\Http\Controllers\API\BaseController as BaseController;
use App\Tickets;
use Validator;
use DB;
use Datatables;
use App\Http\Controllers\Helpers;

class TicketsController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

    }
    
    Public function livesearch(Request $request)
    {
        $term = $request->get('q');
        $app_name = trim($request->get('app_name'));
        $id =DB::table('categories')->where('name', $app_name)->first()->id;
        
        return DB::table('suggestions')
        ->where([['title', 'LIKE', '%'.$term.'%'],['category_id', '=', $id]])
        ->whereNull('deleted_at')
        ->limit(15)
        ->get();
    }
    Public function getappdetails(Request $request)
    {
        //return $request->app_url;
    $apps_check = DB::table('categories')->where('app_url', $request['app_url'])->whereNull('deleted_at')->first();

            if (is_null($apps_check)) {
                return $this->sendResponse($apps_check, 'suggestions retrieved successfully.');
            }
            else
            {
                return $this->sendResponse($apps_check, 'suggestions retrieved successfully.');
            }

        
    }
    

    public function suggestionlist(Request $request)
    {
        $seceretKey = env('SHOP_API_KEY');
        $headers = $this->apache_request_headers();
        if(isset($headers['Authorization'])){
            $api_key = $headers['Authorization'];
            if($api_key != $seceretKey)
            {
                return $this->sendError('Auth failed.');
            }
            else
            {
                $cat_id =DB::table('categories')->where('name', $request->shop_name)->first()->id;
                $table = DB::table('suggestions');
                $table->where("suggestions.category_id", "=", $cat_id);
                $table->whereNull('deleted_at');
                $table->orderBy('suggestions.id', 'desc');
                $table->limit(5);
                $table = $table->get();

                return $this->sendResponse($table->toArray(), 'suggestions retrieved successfully.');

            }
        }
        else
        {
            return $this->sendError('Authorization faild.');
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //dd($request->all());

        $seceretKey = env('SHOP_API_KEY');
        $headers = $this->apache_request_headers();
        if(isset($headers['Authorization'])){
            $api_key = $headers['Authorization'];
            if($api_key != $seceretKey)
            {
                return $this->sendError('Auth failed.');
            }
            else
            {
                // for shop Details Inserted
                $shops_check = DB::table('shops_master')->where('shop_id', $request['shop_id'])->whereNull('deleted_at')->first();
                if (is_null($shops_check)) {
                    DB::table('shops_master')->insert([
                        'app_id' => $request['category_id'],
                        'shop_id' => $request['shop_id'],
                        'shop_name' => $request['shop_name'],
                        'shop_secret' => $request['shop_secret'],
                        'shop_owner_name' => $request['shop_owner_name'],
                        'shop_owner_email' => $request['shop_email'],
                        'shop_domain' => $request['shop_url'],
                        'shop_shopify_domain' => $request['shop_domain'],
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at' => date('Y-m-d H:i:s')
                    ]);

                    $last_shop_id = DB::getPdo()->lastInsertId();
                }
                else
                {
                    $last_shop_id = $shops_check->id;
                }
                
                $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'],
                    'base_url' => $request['base_url'],
                    'subject' => $request['subject'],
                    'content' => $request['content'],
                    'ticketable_type' => $request['ticketable_type'],
                    'shop_id' => $last_shop_id,
                    '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')
                ]);

                //$ticket  = Tickets::create($request->all());

                $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.";

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


                        $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' => $last_insertd_id,
                    'user_id' => $last_user_id,
                    'comment_id' => 0,  
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s')
                ]);


                        $upload_success = $file->move($destinationPath, $img);
                    }
                }

                /* End File Attachments*/

                $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();

                $configurations_from = DB::table('configurations')->where("id", "=", 2)->get();
                

                $from = 'Support System <'.trim($configurations_from[0]->config_val).'>';
                $to =   trim($request['email']);
                $cc = 'Support System <jaydeep@simprosys.net>';
                $bcc = 'Support System <jaydeep@simprosys.net>';

                $base_url_user = $request['base_url'].'show.php';

                //$message_email ="Hello [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/>Our support representative will review your request and get back to you on mentioned email. (usually within 6 business hours).<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", "=", 1)->get();
                $message_subject = trim($ticketemailtemplates[0]->title);
                $message_email = trim($ticketemailtemplates[0]->content);
                    
                //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_user.'?id='.$last_insertd_id .'">View Ticket</a>'
                );
                $subject = Helpers::parseTemplate($message_subject,$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 = trim($configurations[0]->config_val);

                //$message_email_admin ="Hello Support,<br/><br/>New ticket has been created in [APP_NAME]. Here are the details. <br/><br/>Ticket ID : #[TICKET_ID].<br/>Priority : [PRIORITY].<br/>Customer Name : [USER_NAME].<br/>Customer Email : [USER_EMAIL].<br/>Category : [CATEGORY_NAME].<br/>Subject : [SUBJECT].<br/>Message : [MESSAGE].<br/><br/>Please visit below link to response do the ticket.<br/>[VIEW_TICKET_LINK]<br/><br/>Best regards,<br/>Simprosys Support System";
                
                $ticketemailtemplates_admin = DB::table('ticketemailtemplates')->where("id", "=", 3)->get();
                $message_admin_subject = trim($ticketemailtemplates_admin[0]->title);
                $message_email_admin = trim($ticketemailtemplates_admin[0]->content);
                
                $base_url = url('/tickets');
                //replace template var with value
                $token_array_admin = array(
                    'USER_NAME'  => $request['username'],
                    'USER_EMAIL'  => $request['email'],
                    'SUBJECT'  => $request['subject'],
                    'MESSAGE'  => $request['content'],
                    'APP_NAME'  => $tickets_data[0]->cname,
                    'CATEGORY_NAME'  => $tickets_data[0]->subname,
                    'PRIORITY'  => $tickets_data[0]->pname,
                    'TICKET_ID' => $last_insertd_id,
                    'VIEW_TICKET_LINK'=> '<a href="' .$base_url.'/'.$last_insertd_id .'">View Ticket</a>'
                );
                $subject = Helpers::parseTemplate($message_admin_subject,$token_array_admin);
                $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);


                return $this->sendResponse($last_insertd_id, $message);
            }
        }
        else
        {
            return $this->sendError('Authorization faild.');
        }

    }

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

    }

    public function getsubcatsession(Request $request)
    {
        $seceretKey = env('SHOP_API_KEY');
        $headers = $this->apache_request_headers();
        if(isset($headers['Authorization'])){
            $api_key = $headers['Authorization'];
            if($api_key != $seceretKey)
            {
                return $this->sendError('Auth failed.');
            }
            else
            {
                $shop_name = $request->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 $this->sendResponse($sub_category->toArray(), $cat_id);

            }
        }
        else
        {
            return $this->sendError('Authorization faild.');
        }
    }



    public function getpriority()
    {
        $priority = DB::table('priorities')->whereNull('deleted_at')->get();
        return $this->sendResponse($priority->toArray(), 'priority retrieved successfully.');

    }

    public function getcategory(){
        $category = DB::table('subcategories')
            ->join('categories', 'categories.id', '=', 'subcategories.category_id')
            ->select('categories.*')
            ->whereNull('subcategories.deleted_at')
            ->whereNull('categories.deleted_at')
            ->pluck("name","id");
        return $this->sendResponse($category->toArray(), 'category retrieved successfully.');
    }


    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request)
    {
        $seceretKey = env('SHOP_API_KEY');
        $headers = $this->apache_request_headers();
        if(isset($headers['Authorization'])){
            $api_key = $headers['Authorization'];
            if($api_key != $seceretKey)
            {
                return $this->sendError('Auth failed.');
            }
            else
            {
                $cat_id =DB::table('categories')->where('name', $request->shop_name)->first()->id;
                $table = DB::table('tickets');
                $table->join('priorities', 'tickets.priority_id', '=', 'priorities.id');
                $table->join('categories', 'tickets.category_id', '=', 'categories.id');
                $table->join('subcategories', 'tickets.sub_category_id', '=', 'subcategories.id');
                $table->join('statuses', 'tickets.status_id', '=', 'statuses.id');
                $table->select('tickets.*', 'priorities.name AS pname', 'categories.name AS cname', 'subcategories.name as subname', 'statuses.name as sname', 'statuses.color as scolor', 'priorities.color as pcolor');
                $table->whereNull('tickets.deleted_at');
                $table->where("tickets.domain_name", "=", $request->domain_name);
                $table->where("tickets.category_id", "=", $cat_id);
                $table->orderBy('tickets.id', 'desc');
                $table = $table->get();

                return $this->sendResponse($table->toArray(), 'Tickets retrieved successfully.');

            }
        }
        else
        {
            return $this->sendError('Authorization faild.');
        }
    }
    
    public function show_master($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'));
    }


    public function edit(Request $request)
    {
        $seceretKey = env('SHOP_API_KEY');
        $headers = $this->apache_request_headers();
        if(isset($headers['Authorization'])){
            $api_key = $headers['Authorization'];
            if($api_key != $seceretKey)
            {
                return $this->sendError('Auth failed.');
            }
            else
            {

                $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', 'subcategories.name as subname', 'statuses.name as sname', 'statuses.color as scolor', 'priorities.color as pcolor')
                    ->where("tickets.id", "=", $request->ticket_id)
                    ->orderBy('tickets.id', 'desc')
                    ->get();

                $comments = DB::table('comments')
                    ->join('users', 'comments.user_id', '=', 'users.id')
                    ->select('comments.*', 'users.name AS uname','users.email AS uemail')
                    ->where([['ticket_id', '=', $request->ticket_id], ['support_team_display', '=', '0'],])
                    ->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", "=", $request->ticket_id)->get();

                return $this->sendResponse($tickets->toArray(), $comments->toArray());

            }
        }
        else
        {
            return $this->sendError('Authorization faild.');
        }
    }
    
    public function usertickets_images(Request $request)
    {
        $seceretKey = env('SHOP_API_KEY');
        $headers = $this->apache_request_headers();
        if(isset($headers['Authorization'])){
            $api_key = $headers['Authorization'];
            if($api_key != $seceretKey)
            {
                return $this->sendError('Auth failed.');
            }
            else
            {
                $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", "=", $request->ticket_id)->get();

                return $this->sendResponse($tickets_attachements->toArray(), 'The Ticket has been completed!.');

            }
        }
        else
        {
            return $this->sendError('Authorization faild.');
        }
    }
    

    public function updatemark(Request $request)
    {
         $affected = DB::table('tickets')->where('id', '=', $request['ticket_id'])->update(array('status_id' => 2));


        $tickets = \App\Tickets::find($request['ticket_id']);
            $tickets_id = $tickets['id'];
            $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 #'.$tickets_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' => $tickets_id,
                'VIEW_TICKET_LINK'=> '<a href="' .$base_url.'?id='.$tickets_id .'">View Ticket</a>'
            );
            $message_email = Helpers::buildTemplate($message_email,'user');
            $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);
        return $this->sendResponse($request['ticket_id'], 'The Ticket has been completed!.');
    }


    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Product $product)
    {

    }

    public function ticketcomments(Request $request)
    {
        
        $seceretKey = env('SHOP_API_KEY');
        $headers = $this->apache_request_headers();
        if(isset($headers['Authorization'])){
            $api_key = $headers['Authorization'];
            if($api_key != $seceretKey)
            {
                return $this->sendError('Auth failed.');
            }
            else
            {
                //dd($request->all());
                  // dd($last_comments->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();


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


                        $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*/
                    
                    
                    $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>';
                    
                    $base_url = url('/tickets');
                    $last_comments = DB::table('comments')->where('ticket_id', '=', $request['ticket_id'])->where('commentable_type', '=', 1)->latest('id')->first();
                    if ($last_comments === null) {
                        $last_comments_content = "No comments";
                    }
                    else{
                        $last_comments_content = $last_comments->content;
                    }
                    if($request['commentable_type'] == 0){
                    
                    $configurations = DB::table('configurations')->where("id", "=", 1)->get();
                    $to = 'Support System'.trim($configurations[0]->config_val);
                    
                    
                   // $message_email = "Hello Support,<br/><br/>There is update posted by customer.<br/><br/>Ticket ID : #[TICKET_ID].<br/>Comment : [COMMENT_DESCRIPTION]<br/>Last Comment from Support : [LAST_COMMENT]<br/><br/>Please visit below link to response do the ticket.<br/>[VIEW_TICKET_LINK]<br/><br/>Best regards,<br/>Simprosys Support System";
                    
                    $ticketemailtemplates = DB::table('ticketemailtemplates')->where("id", "=", 4)->get();
                    $message_subject = trim($ticketemailtemplates[0]->title);
                    $message_email = trim($ticketemailtemplates[0]->content);
                    
                    $token_array_user = array(
                    'USER_NAME'  => $tickets->username,
                    'COMMENT_DESCRIPTION' => $request['content'],
                    'TICKET_ID' => $last_insertd_id,
                    'LAST_COMMENT' => $last_comments_content,
                    'VIEW_TICKET_LINK'=> '<a href="' .$base_url.'/'.$last_insertd_id .'">View Ticket</a>'
                    );
                    
                    $subject = Helpers::parseTemplate($message_subject,$token_array_user);
                    
                    $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);
                    }
                    

                     $tickets_attachements_images = 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();

                    $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_images]);
            }
        }
        else
        {
            return $this->sendError('Authorization faild.');
        }
        //return redirect()->route('tickets.show',$request['ticket_id'])->with('success','Comment has been added successfully.');
        //return response()->json(['comment'=>$comments]);
    }

    public function updatemultipleimages(Request $request)
    {
        dd($request->all());
        $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;
        }
    }

    public function apache_request_headers() {
        $headers = array();
        foreach($_SERVER as $key => $value) {
            if(substr($key, 0, 5) == 'HTTP_') {
                $headers[str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))))] = $value;
            }
        }
        return $headers;
    }
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Product $product)
    {

    }
}