<?php

namespace App\Http\Controllers\api;
use App\Http\Controllers\Controller;
//use App\Models\Project\Support;
use App\Models\Admin\Support;
use App\Models\Admin\SupportChat;
use App\Models\Project\Alerts;
use App\Models\Project\Support_types;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Traits\ApiLanguageTrait;
use App\Traits\CommunicationTrait;
use App\Traits\SendResponse;
use Carbon\Carbon;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Str;
use Validator;

class SupportController extends Controller
{
	use SendResponse , CommunicationTrait, ApiLanguageTrait;
    public function index(Request $request)
    {
        $record['record'] = Support::where('user_id',$request->user_id)->with('support_type')->get();
        return $this->sendGeneralResponse(true,$this->__transEn('support_list'), $this->__transAr('support_list'),'Support list', $record, 200);
    }


    public function supportDetails(Request $request)
    {
        $record['record'] = Support::where('id',$request->support_id)->with('support_type','detail')->get();
        return $this->sendGeneralResponse(true, $this->__transEn('support_details'), $this->__transAr('support_details'), 'Support details', $record, 200);
    }

    public function add_support(Request $request)
    {
       try {
            // $validator = Validator::make($request->all(), [
            //     'type' => 'required',
            //     'message' => 'required',
            //     'files.*' => 'mimes:jpg,jpeg,png|max:2048',
            // ]);
            // if ($validator->fails()) :
            //     return $this->sendError($this->__transEn('validation_failed'), $this->__transAr('validation_failed'),$validator->errors(), 401, ' ');
            //     exit;
            // endif;

            $validateRequest =
            [
                'type' => 'required',
                'message' => 'required',
                'files.*' => 'mimes:jpg,jpeg,png|max:20048',
            ];
           $messages_en = [
            'type.required' => $this->__transEn('type_is_required') ,
            'message.required' => $this->__transEn('message_is_required') ,
            'files.*.required' => $this->__transEn('must_be_a_type_of_image') ,
            ];
            $messages_ar = [
            'type.required' => $this->__transAr('type_is_required') ,
            'message.required' => $this->__transAr('message_is_required') ,
            'files.*.required' => $this->__transAr('must_be_a_type_of_image') ,
            ];

            $validator_en = Validator::make($request->all(),$validateRequest,$messages_en );
            $validator_ar = Validator::make($request->all(),$validateRequest,$messages_ar );

            if ($validator_en->fails()) {
                $errors_en = implode("\n",$validator_en->messages()->all());
                $errors_ar = implode("\n",$validator_ar->messages()->all());
                return $this->sendError($errors_en,  $errors_ar, '',  200,'login');
              }


            $data = [
                'user_id' => $request->user_id,
                'type' => $request->type,
                'message' => $request->message,
                'status' => '1',
            ];

            if($request->has('files') && !empty($request->files)): 
                $attachments = [];
                foreach ($request->file('files') as $file) {
                    $name = 'project/support/' . $request->user_id .'/'. Str::random(30) .".". $file->getClientOriginalExtension();
                    $file->move(public_path('project/support/' . $request->user_id), $name);
                    $attachments[] = $name;
                }
                $data['attachments'] = $attachments;
            endif;
            $post = Support::create($data);
            // notifications
            $alert_entry = [
                'ref_id' => $post->id,
                'title' => 'Support send',
                'discription' => 'Support send Successfully',
                'alert_type' => 4, //support
                'created_at' => Carbon::now(),
            ];
            Alerts::insert($alert_entry);
            // $notify = [
            //     'uid' => $request->user_id,
            //     'title' => 'Support send',
            //     'message' => 'Support send Successfully',
            // ];
            // $this->SendAlertNotification($notify);
            return $this->sendGeneralResponse(true,$this->__transEn('successfully_send'), $this->__transAr('successfully_send'),'Send-Support', ['response' => "success"] , 200);
       } catch (\Throwable $th) {
           throw $th;
       }
    }




    public function reply_support(Request $request)
    {
       try {
            // $validator = Validator::make($request->all(), [
            //     'message' => 'required',
            // ]);
            // if ($validator->fails()) :
            //     return $this->sendError($this->__transEn('validation_failed'), $this->__transAr('validation_failed'),$validator->errors(), 401, ' ');
            //     exit;
            // endif;

            $validateRequest =
            [
                'message' => 'required',
            ];
           $messages_en = [
            'message.required' => $this->__transEn('message_is_required') ,
            ];
            $messages_ar = [
            'message.required' => $this->__transAr('message_is_required') ,
            ];

            $validator_en = Validator::make($request->all(),$validateRequest,$messages_en );
            $validator_ar = Validator::make($request->all(),$validateRequest,$messages_ar );

            if ($validator_en->fails()) {
                $errors_en = implode("\n",$validator_en->messages()->all());
                $errors_ar = implode("\n",$validator_ar->messages()->all());
                return $this->sendError($errors_en,  $errors_ar, '',  200,'login');
              }
            $data = [
                'support_id' => $request->support_id,
                'message' => $request->message,
                'user_id' => $request->user_id,
                'type' => '2',
                'status' => '1',
            ];
        SupportChat::create($data);
            return $this->sendGeneralResponse(true,$this->__transEn('successfully_send'), $this->__transAr('successfully_send'),'Send-Support', ['response' => "success"] , 200);
       } catch (\Throwable $th) {
           throw $th;
       }
    }


    public function support_type()
    {
        $record['record'] = Support_types::where('status',1)->get();
        return $this->sendGeneralResponse(true, $this->__transEn('support_types'), $this->__transAr('support_types'),'Support types', $record, 200);
    }

    // public function index(Request $request)
    // {   
    // 	if($request->type == "app"){ $id = $request->uid; } else{ $id = Auth::user()->id; }
	//     $data = array();
	//     $data['img_path'] = "https://sarfapp.com/public/images/support/";
	// 	$data['support'] = DB::table('supports')
	// 	->join('support_messages', 'support_messages.support_id', '=', 'support.id')
	// 	->join('users', 'users.id', '=', 'support.user_id')
	// 	->select(
	// 		'support.*', 'support_messages.*', 'users.username',
	// 		DB::raw("
	// 			(SELECT type_name FROM support_types WHERE support_types.id = support.type_id) as support_type_en
	// 		"),
	// 		DB::raw("
	// 			(SELECT type_name_ar FROM support_types WHERE support_types.id = support.type_id) as support_type_ar
	// 		"),
	// 		DB::raw("
	// 			(SELECT support_files.file_name FROM support_files WHERE support_files.support_id = support.id)as files
	// 		"),  
	// 		DB::raw("
	// 			(SELECT reply_msg FROM support_replies WHERE support_replies.support_id = support.id) as reply_msg
	// 		"),
	// 	)
	// 	->where('support.user_id',$id)
	// 	->get();
    //     return $data;
    // }

    // public function support_types()
    // {
    // 	$data = array();
	// 	$data['support_types'] = Support_types::where('rstatus',1)->get();
	// 	$data['support_types_status'] = 1;
	// 	if (empty($data['support_types'])) {
	// 		$data['msg_en'] = $this->__transEn('support_type_not_found');
	// 		$data['msg_ar'] = $this->__transAr('support_type_not_found');
	// 		$data['support_types_status'] = 0;
	// 	}
    //     return $data;
    // }

    // public function add_api_support(Request $request){
	// 	if($request->apptype == "app"){ $id = $request->user_id; } else{ $id = Auth::user()->id; }
	// 	$data = array();
	//     if(empty($request->s_type)) {
	// 		$data['msg_en'] = $this->__transEn('please_select_type');
	// 		$data['msg_ar'] = $this->__transAr('please_select_type');
	// 	}
	// 	else if (empty($request->msg)) {
    //    		$data['msg_en'] = $this->__transEn('please_write_message');
    //    		$data['msg_ar'] = $this->__transAr('please_write_message');
    //   	} 
	//   	else {
	//   		$support_id = $message_id = 0;
	// 		$post = new Support;
	// 	  	$post->type_id = $request->s_type;
	// 	  	$post->message = strip_tags($request->msg);
	// 	  	$post->sdate = date('Y-m-d');
	// 	  	$post->stime = date('H:m:i');
	// 	  	$post->user_id = $id;
	// 	  	$msg = $post->save();
	// 	  	$support_id = $post->id;

	// 	  	$post = new Support_messages;
	// 	  	$post->support_id = $support_id;
	// 	  	$post->message = strip_tags($request->msg);
	// 	  	$post->msg_date = date('Y-m-d');
	// 	  	$post->msg_time = date('H:m:i');
	// 	  	$post->sender = $request->sender;
	// 	  	$post->attachements = $request->attachements;
	// 	  	$msg = $post->save();

	// 	  	$message_id = $post->id;

	// 	  	if ($request->attachements == 1) {
	// 	  		if(!$request->hasFile('file_photo')) {
	// 		        $data['msg_en'] = $this->__transEn('upload_file_not_found');
	// 				$data['msg_ar'] = $this->__transAr('upload_file_not_found');
	// 				$data['status'] = 0;
	// 		    }
	// 		    $data2 = array();
	// 		    $allowedfileExtension=['pdf','docx','jpg','png'];
	// 		    $files = $request->file('file_photo');
	// 		    foreach ($files as $file) {   
	// 		        $extension = $file->getClientOriginalExtension();
	// 		        $check = in_array($extension,$allowedfileExtension);
	// 		        if($check) {
	// 		            foreach($request->file_photo as $mediaFiles) {
	// 		                $path = $mediaFiles->store('public/images/support/');
	// 		                $name = $mediaFiles->getClientOriginalName();
	// 		                //store image file into directory and db
	// 		                array_push($data2, $name);
	// 		            }
	// 		        } else {
	// 		            $data['msg_en'] = $this->__transEn('invalid_file_format');
	// 					$data['msg_ar'] = $this->__transAr('invalid_file_format');
	// 					$data['status'] = 0;
	// 		        }
	// 		    }
	// 		    $post = new Support_files;
	// 		  	$post->file_name = json_encode($data2);
	// 		  	$post->support_id = $support_id;
	// 		  	$post->message_id = $message_id;
	// 		  	$msg = $post->save();
	// 	  	}
	// 		if ($msg) {
	// 			$data['msg_en'] = 'Send successfully';
	// 			$data['msg_ar'] = 'Send successfully';
	// 			$data['status'] = 1;
	//         } else {
	// 			$data['msg_en'] = 'Not Send';
	// 			$data['msg_ar'] = 'Not Send';
	// 			$data['status'] = 0;
	//         }	 
	// 	}
	//  	return $data; 
	// }

	// //add budget type
	// public function add(Request $request){
	// 	if($request->type == "app"){ $id = $request->uid; } else{ $id = Auth::user()->id; }
	// 	$data = array();
	//     if(empty($request->type)) {
	// 		$data['msg_en'] = array('text' => $this->__transEn('please_select_type'), 'cls' => 'warning');
	// 		$data['msg_ar'] = array('text' => $this->__transAr('please_select_type'), 'cls' => 'warning');
	// 	}
	// 	else if (empty($request->msg)) {
    //    		$data['msg_en'] = array('text' => $this->__transEn('please_write_message'), 'cls' => 'warning');
    //    		$data['msg_ar'] = array('text' => $this->__transAr('please_write_message'), 'cls' => 'warning');
    //   	} 
	//   	else {
	//   		$support_id = $message_id = $attach = 0;
	//   		$new_name = "";
	//   		$validation = Validator::make($request->all(), [
	//             'attach' => 'image|mimes:jpeg,png,jpg,gif,svg|max:5048'
	//         ]);
	//         if ($validation->passes()) {
	//             $photo = $request->file('attach');
	//             if ($photo) {
	//                 $new_name = rand() . '.' . $photo->getClientOriginalExtension();
	//                 $photo->move(base_path('public/images/support/'), $new_name);
	//                 $attach = 1;
	//             }
	// 			$post = new Support;
	// 		  	$post->type_id = $request->s_type;
	// 		  	$post->message = strip_tags($request->msg);
	// 		  	$post->sdate = date('Y-m-d');
	// 		  	$post->stime = date('H:m:i');
	// 		  	$post->user_id = $id;
	// 		  	$msg = $post->save();
	// 		  	$support_id = $post->id;

	// 		  	$post = new Support_messages;
	// 		  	$post->support_id = $support_id;
	// 		  	$post->message = strip_tags($request->msg);
	// 		  	$post->msg_date = date('Y-m-d');
	// 		  	$post->msg_time = date('H:m:i');
	// 		  	$post->sender = 1;
	// 		  	$post->attachements = $attach;
	// 		  	$msg = $post->save();

	// 		  	$message_id = $post->id;

	// 		  	if ($attach == 1) {
	// 		  		$post = new Support_files;
	// 			  	$post->file_name = $new_name;
	// 			  	$post->support_id = $support_id;
	// 			  	$post->message_id = $message_id;
	// 			  	$msg = $post->save();
	// 		  	}
	// 			if ($msg) {
	// 				$data['msg_en'] = array('text' => $this->__transEn('send_success'), 'cls' => 'success');
	// 				$data['msg_ar'] = array('text' => $this->__transAr('send_success'), 'cls' => 'success');
	// 				$data['status'] = 1;
	// 	        } else {
	// 				$data['msg_en'] = array('text' => $this->__transEn('not_send'), 'cls' => 'error');
	// 				$data['msg_ar'] = array('text' => $this->__transAr('not_send'), 'cls' => 'error');
	// 				$data['status'] = 0;
	// 	        }
	// 	    } else {
	//             throw ValidationException::withMessages([
	//                 'attach' =>[$validation->errors()->all()]
	//             ]);
	//         }	 
	// 	}
	//  	return $data; 
	// }

	// //update profile info
	// /*public function update(Request $request){
    //     $data = array();
    //     if(empty($request->budget_name)) {
	// 		$data['msg_en'] = array('text' => 'Name is required', 'cls' => 'warning');
	// 		$data['msg_ar'] = array('text' => 'Name is required', 'cls' => 'warning');
	// 	}
	// 	else if (empty($request->budget_amount)) {
    //    		$data['msg_en'] = array('text' => 'Amount is required', 'cls' => 'warning');
    //    		$data['msg_ar'] = array('text' => 'Amount is required', 'cls' => 'warning');
    //   	} 
	//   	else {
	// 	  	$post = Support::find($request->id);
	// 	  	$post->budget_name = strip_tags($request->budget_name);
	// 	  	$post->budget_amount = intval($request->budget_amount);
	// 	  	$msg = $post->save();
	// 	  	if ($msg) {
	// 			$data['msg_en'] = array('text' => 'Updated successfully', 'cls' => 'success');
	// 			$data['msg_ar'] = array('text' => 'Updated successfully', 'cls' => 'success');
	// 			$data['status'] = 1;
	// 	  	}else{
	// 	  		$data['msg_en'] = array('text' => 'Updation Fail', 'cls' => 'error');
	// 	  		$data['msg_ar'] = array('text' => 'Updation Fail', 'cls' => 'error');
	// 	  		$data['status'] = 0;
	// 	  	}
	// 	}
	// 	return $data;
	// }*/

	// //destroy info
	// public function destroy(Request $request){
	// 	$data=array();
	// 	if (isset(Support::find($request->id)->id)) {
	// 		$msg = Support::find($request->id)->delete();
	// 	  	$msg2 = Support_messages::where('support_id', $request->id)->delete();
	// 	  	$msg3 = Support_files::where('support_id', $request->id)->delete();
	// 	  	if ($msg || $msg2 || $msg3) {
	// 			$data['msg_en'] = array('text' => $this->__transEn('delete_success'), 'cls' => 'success');
	// 			$data['msg_ar'] = array('text' => $this->__transAr('delete_success'), 'cls' => 'success');
	// 			$data['status'] = 1;
	// 	  	}else{
	// 	  		$data['msg_en'] = array('text' => $this->__transEn('delete_fail'), 'cls' => 'error');
	// 	  		$data['msg_ar'] = array('text' => $this->__transAr('delete_fail'), 'cls' => 'error');
	// 	  		$data['status'] = 0;
	// 	  	}
	// 	}else{
	// 		$data['msg_en'] = array('text' => $this->__transEn('id_not_found'), 'cls' => 'warn');
	// 	  	$data['msg_ar'] = array('text' => $this->__transAr('id_not_found'), 'cls' => 'warn');
	// 	  	$data['status'] = 0;
	//   	}
	//   	return $data;
	// }
}
