<?php namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;
use Auth;
use Session;
use Config;
use Redirect;
use DB;
use URL;
use App\User;
use App\Messages;
use App\MessageUsers;
use Datatables;
use App\Profile;
use Illuminate\Support\Facades\Input;

class MessageController extends Controller {

	/*
	|--------------------------------------------------------------------------
	| Profile Controller
	|--------------------------------------------------------------------------
	|
	|
	*/

	/**
	 * Profile controller instance.
	 *
	 * @return void
	 */
	public function __construct()
	{
		$this->middleware('auth');
                if(!Session::get('auth_selected_profile')) {
                                return Redirect::to('profile/step1')->with('succ_msg', 'Please Create atleast one profile')->send(); 
                             }
		
	}

	public function compose(Request $request)
	{
		$input= $request->all();
                $id="";
                $count="";
		//$result = Profile::where('name','=',$input['to'])->get();
//		$result = Profile::where('id','=',$input['sel_to_prof_id'])->get();
		$result = User::where('id','=',$input['sel_to_prof_id'])->get();
		if(isset($result[0])):
		
//			$compose['sender_profile_id'] = Session::get('auth_selected_profile');
			$compose['sender_profile_id'] = Auth::user()->id;
			$compose['receiver_profile_id'] = $result[0]->id;
			$compose['title'] = $input['subject'];
			$compose['msg_content'] = $input['message'];
                        
                        if(isset($input['update']))
                        {    
                             if($input['msg_id']!="")
                             {  
                                $new_id= Messages::find($input['msg_id']);
                                if($compose['sender_profile_id']==$compose['receiver_profile_id']){$compose['receiver_profile_id']=$new_id['receiver_profile_id'];}
                                $id=$input['msg_id'];
                                Messages::where('id',$id)->update(['title' => $compose['title'],'msg_content'=>$compose['msg_content']]);
                                $count=MessageUsers::where('message_id',$id)->count();
                             }
                        }
                        else
                        {  
                        $save = Messages::create($compose);
                        }
                        if($id==""){$id=$save->id;}else{$id=$id;} 
                        if($count<4)
                        {
			$inbox = MessageUsers::create_record($compose['receiver_profile_id'],$id,'R','I','N','N'); // save in inbox folder
			$sent = MessageUsers::create_record($compose['sender_profile_id'],$id,'R','S','N','N'); // save in sent folder
                        }
                        else
                        {
                          MessageUsers::where('profile_id',$compose['receiver_profile_id'])->where('message_id',$id)->where('folder','I')->update(['is_readed' => 'N']);  
                        }
                        

			return redirect(URL::previous())->with('succ_msg',"Message Sent Successfully");
		else :
			return redirect(URL::previous())->with('error_msg',"Invalid To address");
		endif;
	}

	/**
	 * Show the Message Inbox current user.
	 *
	 * @return Response
	 */
	public function inbox()
	{
		return view('message.inbox')->with(['error_msg'=>Session::get('error_msg')]);
	}

	public function sent()
	{
		return view('message.sent')->with(['error_msg'=>Session::get('error_msg')]);
	}

	public function trash()
	{
		return view('message.trash')->with(['error_msg'=>Session::get('error_msg')]);
	}

	public function ajax_messages(Request $request)
	{
		$input = $request->all();	

//		$results = Messages::getmessage(Session::get('auth_selected_profile'),$input['msg_type']);

		$results = Messages::getmessage(Auth::user()->id,$input['msg_type']);

		return Datatables::of($results)

						->addColumn('checkbox', function($results) {
							return '<div class="search_input"><input type="checkbox" value="'.$results['id'].'" name="msg_check[]" class="select_msg_check" ><label></label></div><input type="hidden" value="'.$results['msg_id'].'" name="msg_id[]" class="select_msg_id" >';
						})
						->addColumn('sender', function($results) {
							$default_image = 'default-profile.png';

							/*Using Profile ID*/	
							/*if($results['folder']=='I')
								$prof_det = Profile::find($results['sender_profile_id']);	
							else
								$prof_det = Profile::find($results['receiver_profile_id']);	

							if($results['is_readed']=='N' && $results['folder']=='I')
								$sender = '<strong>'.$prof_det->name.'</strong>';
							else
								$sender =  $prof_det->name;	

							if($prof_det->profile_image)								
								$default_image = $prof_det->profile_image;

							return '<img src="'.url('uploads/profile_images/'.$default_image).'" class="img-circle" width="30px" height="30px"> &nbsp;'.ucwords($sender);*/

							/* End Using Profile ID*/	

							/*Using Profile ID*/	
							if($results['folder']=='I'){
								$user_det = User::find($results['sender_profile_id']);
								$prof_det = Profile::find($results['sender_profile_id']);	
								}	
							else{
								$user_det = User::find($results['receiver_profile_id']);
								$prof_det = Profile::find($results['receiver_profile_id']);		
                                }
							if($results['is_readed']=='N' && $results['folder']=='I')
								$sender = '<strong>'.$user_det->username.'</strong>';
							else
								$sender =  $user_det->username;	
							 
							 
							 if(isset($prof_det->profile_image ))	{							
							 							
								if(is_file('uploads/profile_images/'.$prof_det->profile_image))
									$default_image = $prof_det->profile_image;
								else
									$default_image = 'default-profile.png';
							 }

							return '<span class="inbox-thumb-avtar"><img src="'.url('uploads/profile_images/'.$default_image).'" class="img-circle"> </span><h5 class="avtar-name">'.ucwords($sender).'</h5>';

							/*
							if($prof_det->profile_image && isset(is_file('uploads/profile_images/'.$prof_det->profile_image)))
							  	
							 //{
							*/
							
							/* End Using Profile ID*/	


						})
						->editColumn('title',function($results){

							if($results['is_readed']=='N' && $results['folder']=='I')
								return '<strong>'.$results['title'].'</strong>';
							else
								return $results['title'];
						})
						->editColumn('created_at',function($results){

							if(date("Y-m-d")==date('Y-m-d', strtotime($results['created_at'])))
								$date= '<a href="javascript:void(0)" title="'.date('m/d/Y h:i a', strtotime($results['created_at'])).'">'.date('h:i a', strtotime($results['created_at'])).'</a>';
								else
								$date= '<a href="javascript:void(0)" title="'.date('m/d/Y h:i a', strtotime($results['created_at'])).'">'.date('M d', strtotime($results['created_at'])).'</a>';

							if($results['is_readed']=='N' && $results['folder']=='I')
							$data="<strong>".$date."</strong>";	
							else
							$data=$date;

							return $data;
						})
						->make(true);
	}

	public function check_username(Request $request)	
	{
		$input = $request->all();
		//$result = Profile::where('name','=',$input['to'])->get(); /*Profile Name*/
		$result = User::where('username','=',$input['to'])->get(); /* Username*/
		if(isset($result[0]))
			$return = "true";
		else
			$return = "false";

		echo json_encode(array('valid' => $return,));
	}

	public function typeahead(Request $request)
	{
		$whereRaw = "'T'";	
		if(Auth::user()->selected_profile=='O')
			$whereRaw = "'O','T'";

		$input = $request->all();$query = $input['user_name'];
		$result = User::select(['username as value','id'])
					->where('username','like',"%{$query}%")
					->where('id','<>',Auth::user()->id)
					->whereRaw("selected_profile in ({$whereRaw})")
					->get();
		/*echo "<pre>";
		print_r($result);
		exit;*/
		echo json_encode($result);
	}

	public function message_details($msg_id)
	{
		if(is_numeric($msg_id)):
			$msg_user_det = MessageUsers::find($msg_id);
			if(isset($msg_user_det->id) && $msg_user_det->id && $msg_user_det->profile_id == Auth::user()->id):
				$msg_det = Messages::find($msg_user_det->message_id);
				if(isset($msg_det->id) && $msg_det->id):
					
					if($msg_user_det->folder=='I')
						$user_det = User::find($msg_det->sender_profile_id);	
					else
						$user_det = User::find($msg_det->receiver_profile_id);	

					$msg_det->user_det = $user_det->username;
					$msg_det->delete_id = $msg_user_det->id;

					if($msg_user_det->folder == 'I')
						$msg_det->folder = 'inbox';
					else if($msg_user_det->folder == 'S') 
						$msg_det->folder = 'sent';
					else
						$msg_det->folder = 'trash';
					if($msg_user_det->is_readed=='N')
					{
						$msg_user_det->is_readed = 'Y';
						$msg_user_det->save();
					}	

					return view('message.details')->with(array('msg_details'=>$msg_det));						
				else:
					return redirect(URL::previous())->with('error_msg',"Invalid Request");
				endif;
			else:
				return redirect(URL::previous())->with('error_msg',"Invalid Request");
			endif;
		else:
			return redirect(URL::previous())->with('error_msg',"Invalid Request");
		endif;
	}

	public function message_delete($msg_id,Request $request)
	{
           //echo $msg_id;exit;
		if(is_numeric($msg_id)):
			$msg_user_det = MessageUsers::find($msg_id);
			if(isset($msg_user_det->id) && $msg_user_det->id && $msg_user_det->profile_id == Auth::user()->id):
				if($msg_user_det->folder == 'I')
					$redirect = 'inbox';
				else
					$redirect = 'sent';
				//$msg_user_det->folder = 'T';
				$msg_user_det->is_deleted = 'Y';
				$msg_user_det->save();
				return redirect('message/'.$redirect)->with('succ_msg',"Selected Message Delete Successfully");
			else:
				return redirect(URL::previous())->with('error_msg',"Invalid Request");
			endif;
		elseif($msg_id=='sel_check'):
                    
                    $find_checked = Input::get('msg_check');	//print_r($find_checked);exit;
                        if(count($find_checked)>0):
                         for($i=0;$i<count($find_checked);$i++)
                        {
                           $result = MessageUsers::where("id",'=',$find_checked[$i])->update(['is_deleted'=>'Y','is_readed'=>'Y']);
                        }
                        return redirect(URL::previous())->with('succ_msg',"Selected Messages Delete Successfully");
                        else:
                        return redirect(URL::previous())->with('error_msg',"Invalid Request");
                        endif;
		elseif($msg_id=='for_ever'):
			$input = $request->all();$message_id=array();
			$delete_id = implode(',',$input['msg_check']);
			$results = MessageUsers::select(['message_id'])->whereRaw("id IN ({$delete_id})")->delete();
			/*foreach($results as $r)
			{
				$message_id[] = $r['message_id'];
			}
			//echo $message_id;
			echo "<pre>";
			print_r($message_id);
			echo implode(',',$message_id);
			exit;*/
			return redirect(URL::previous())->with('succ_msg',"Selected Messages Delete Successfully");
		else:
			return redirect(URL::previous())->with('error_msg',"Invalid Request");
		endif;
	}

}
