<?php namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;
use Auth;
use Session;
use Redirect;
use Config;
use DB;
use URL;
use App\User;
use App\Invitations;
use App\InvitationUsers;
use Datatables;
use App\Profile;

class InvitationController extends Controller {

	/*
	|--------------------------------------------------------------------------
	| Invitaiton Controller
	|--------------------------------------------------------------------------
	|
	|
	*/

	/**
	 * Invitation 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();
                  //echo '<pre>'; print_r($input); exit;
		$sender_id = Auth::user()->id;
		if(isset($input['to'])):
			/*Save Message*/
				$attachment_path = '/uploads/invitation_attachments/'; 

				$compose['sender_profile_id'] = $sender_id;
				$compose['receiver_profile_id'] = 0;
				$compose['title'] = $input['subject'];
				$compose['msg_content'] = $input['message'];
				$compose['inv_title'] = $input['title'];
				$compose['company_name'] = $input['company_name'];
				$compose['company_url'] = $input['url'];
				
				$file_name = '';
				$org_name = '';
				if($request->file('attachments'))
				{
					$org_name = $request->file('attachments')->getClientOriginalName();
					$file = $request->file('attachments');
					$storage_path ='uploads/invitation_attachments';
					$file_name = $sender_id.time().".".strtolower($file->getClientOriginalExtension());
					$file->move($storage_path,$file_name);
				}
					
				$compose['attachment'] = $file_name;
				$compose['attachment_name'] = $org_name;

				$save = Invitations::create($compose);
			/* End Save Message*/
			/* Save Message Users*/
				foreach($input['to'] as $key=>$value):
					$result = User::where('id','=',$value)->get();
				/*echo "<pre>";
				print_r($result);
				exit;*/
					$inbox = InvitationUsers::create_record($result[0]['id'],$save->id,'I','NS','N','N'); //Inbox in sent folder
				endforeach;
					$sent = InvitationUsers::create_record($save->sender_profile_id,$save->id,'S','NS','N','N'); // save in sent folder
			/* End save Messag Users*/
			return redirect(URL::previous())->with('succ_msg',"Invitation Sent Successfully");

		else :
			//return redirect(URL::previous())->with('error_msg',"Invalid To address");
			return view('invitation.create_invitation');			
		endif;
	}

	/**
	 * Show the Invitation Inbox current user.
	 *
	 * @return Response
	 */
	public function index()
	{
		return view('invitation.index');
	}

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

//		$results = Invitations::getInvitation(Session::get('auth_selected_profile'),$input['msg_type']);
		$msg_type ='';
		if(isset($input['msg_type']) && $input['msg_type'])
			$msg_type = $input['msg_type'];

		$results = Invitations::getInvitation(Auth::user()->id,$msg_type);
		$results->msg_type = $msg_type;
		return Datatables::of($results)

						->addColumn('action', function($results) {
							if($results['folder']=='I')
							{
								$no = '<button class="btn btn-primary mleft10 update_inv_status invite_del-btn" data-id="'.$results['id'].'" data-type="N">Delete</button>';
								if($results['permission_type']=='NS')
									return '<button class=" btn btn-primary update_inv_status invite-ok-btn" data-id="'.$results['id'].'" data-type="I">Interested</button>
											<button class="btn btn-primary mleft10 update_inv_status invite-ok-btn" data-id="'.$results['id'].'" data-type="M">Maybe</button>'.$no;
								else if($results['permission_type']!='N')
									return $no;										
								else
									return '';
							}
							else
							{
								return '';
							}	
						})
						->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']);	
							/*else
								$user_det = User::find($results['receiver_profile_id']);	*/

							if($results['is_readed']=='N')
								$sender = '<strong>'.$user_det->username.'</strong>';
							else
								$sender =  $user_det->username;	

							if($user_det->profile_image && is_file('uploads/profile_images/'.$user_det->profile_image)){								
								$default_image = $user_det->profile_image;}

							return '<img src="'.url('uploads/profile_images/'.$default_image).'" class="img-circle invite_pro_pic"><p class="invit_name">'.ucwords($sender).'</p>';

							/* End Using Profile ID*/	


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

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

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

							if($results['is_readed']=='N')
							$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 invitation_details($inv_id)
	{
		if(is_numeric($inv_id)):
			$inv_user_det = InvitationUsers::find($inv_id);
			if(isset($inv_user_det->id) && $inv_user_det->id && $inv_user_det->profile_id == Auth::user()->id):
				$inv_det = Invitations::find($inv_user_det->invitation_id);
				if(isset($inv_det->id) && $inv_det->id):
					
					//if($inv_user_det->folder=='I')
						$user_det = User::find($inv_det->sender_profile_id);	
					/*else
						$user_det = User::find($inv_det->receiver_profile_id);	
					*/
					$inv_det->user_det = $user_det->username;
					$inv_det->reply_user = $user_det->username;
					if($inv_det->receiver_profile_id)
					{
						$user_det_recv = User::find($inv_det->receiver_profile_id);	
						$inv_det->reply_user = $user_det_recv->username;
					}
					$inv_det->delete_id = $inv_user_det->id;

					$with_array = array();
					if($inv_user_det->permission_type == 'I' || $inv_det->sender_profile_id==Auth::user()->id):
						$inv_det->inv_reply = true;
						$with_array['intr_prof'] = InvitationUsers::permissionProfiles($inv_user_det->invitation_id,'I');
						$with_array['maybe_prof'] = InvitationUsers::permissionProfiles($inv_user_det->invitation_id,'M');
						$with_array['rej_prof'] = InvitationUsers::permissionProfiles($inv_user_det->invitation_id,'N');
					else : 
						$inv_det->inv_reply = false;
					endif;

					if($inv_user_det->is_readed=='N')
					{
						$inv_user_det->is_readed = 'Y';
						$inv_user_det->save();
					}	

/*echo "<pre>"; print_r($inv_det);
exit;*/

					return view('invitation.details')->with(array('msg_details'=>$inv_det,'inv_user_det'=>$with_array));						
				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 invitation_delete($inv_id,Request $request)
	{
		if(is_numeric($inv_id)):
			$inv_user_det = InvitationUsers::find($inv_id);
			if(isset($inv_user_det->id) && $inv_user_det->id && $inv_user_det->profile_id == Auth::user()->id):
				if($inv_user_det->folder == 'I')
					$redirect = 'inbox';
				else
					$redirect = 'sent';
				//$inv_user_det->folder = 'T';
				$inv_user_det->is_deleted = 'Y';
				$inv_user_det->save();
				return redirect('Invitation/'.$redirect)->with('succ_msg',"Selected Invitation Delete Successfully");
			else:
				return redirect(URL::previous())->with('error_msg',"Invalid Request");
			endif;
		elseif($inv_id=='sel_check'):
			$input = $request->all();
			$update_id = implode(',',$input['msg_check']);
			/*echo $update_id;*/
			$result = InvitationUsers::whereRaw("id IN ({$update_id})")->update(['is_deleted'=>'Y']);
			return redirect(URL::previous())->with('succ_msg',"Selected Invitations Delete Successfully");
		elseif($inv_id=='for_ever'):
			$input = $request->all();$Invitation_id=array();
			$delete_id = implode(',',$input['msg_check']);
			$results = InvitationUsers::select(['Invitation_id'])->whereRaw("id IN ({$delete_id})")->delete();
			/*foreach($results as $r)
			{
				$Invitation_id[] = $r['Invitation_id'];
			}
			//echo $Invitation_id;
			echo "<pre>";
			print_r($Invitation_id);
			echo implode(',',$Invitation_id);
			exit;*/
			return redirect(URL::previous())->with('succ_msg',"Selected Invitations Delete Successfully");
		else:
			return redirect(URL::previous())->with('error_msg',"Invalid Request");
		endif;
	}

	public function invitation_action_update($inv_id,$per_type)
	{
            if($per_type=='I')
            {
                $msg = "Your invitation Accepted successfully";
            }
            else  if($per_type=='M')
            {
                $msg = "Maybe interested your invitaion future";
            }
            else  if($per_type=='N')
            {
                $msg = "Your invitation has been not accepted";
            }
            else
            {
                $msg = "Your Invitation has been updated successfully";
            }
            //echo $msg; exit;
            if(is_numeric($inv_id)):
			$inv_user_det = InvitationUsers::find($inv_id);
			if(isset($inv_user_det->id) && $inv_user_det->id && $inv_user_det->profile_id == Auth::user()->id):
				
				if($per_type=='N')
					$inv_user_det->status = '0';	

				$inv_user_det->permission_type = $per_type;
				$inv_user_det->save();
				return redirect(URL::previous())->with('succ_msg',$msg);
			else:
				return redirect(URL::previous())->with('error_msg',"Invalid Request");
			endif;
		else:
			return redirect(URL::previous())->with('error_msg',"Invalid Request");
		endif;
	}

	public function invitation_reply(Request $request)
	{
		$input = $request->all();
		if($input['inv_id']):
			$inv_det = Invitations::find($input['inv_id']);
			if(isset($inv_det->id) && $inv_det->id):
				
				$inv_det->msg_content = $input['message'];
				$inv_det->receiver_profile_id = Auth::user()->id;
				//$inv_det->updated_at = date('Y-m-d h:i:s a');
				$inv_det->save();
				$inv_user_det = InvitationUsers::where('invitation_id','=',$inv_det->id)->update(['is_readed'=>'N']);
				/*echo $inv_user_det;
				exit;*/
//				return redirect(URL::previous())->with('succ_msg',"Invitation reply sent successfully");
				return redirect(url('invitations'))->with('succ_msg',"Invitation reply sent successfully");
			else:
				return redirect(URL::previous())->with('error_msg',"Invalid Request");
			endif;
		else:
			return redirect(URL::previous())->with('error_msg',"Invalid Request");
		endif;

	}

	public function download($driver, $filename)
	{
		return redirect(url('uploads/'.$driver.'/'.$filename));
	}	
}
