<?php namespace App\Http\Controllers;
use App\Profile; // Profile Model
use Auth; // Auth model
use Illuminate\Support\Facades\Redirect;
use Illuminate\Http\Request;
use App\Mentor;
use Session;
use Config;
use Datatables;
use App\Countries;
use App\Connections;
use Mail;
use App\Users;
use App\MentorUsers;
use URL;
class MentorController extends Controller {

	/*
	|--------------------------------------------------------------------------
	| M Controller
	|--------------------------------------------------------------------------
	|
	|
	*/

	/**
	 * Myprofile 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(); 
                             }
		
	}

	/**
	 * Show the application Step1 to the user.
	 *
	 * @return Response
	 */

	public function index()
	{
            //print_r($_POST); exit;
            $subjact = $_POST['mentor_sub'];
            $checkvalue = array();
            $checkvalue = explode(',',$_POST['checbox_val']);
            $sender_profile_id = Session::get('auth_selected_profile');
                        
            $error = '';
            for($i=0;$i<count($checkvalue);$i++)
            {
                $results = '';
                $create = array();
                $create['sender_profile_id'] = $sender_profile_id;
                $create['receiver_profile_id'] = $checkvalue[$i];
                $create['subject'] = $subjact;
                $results =  Mentor::select('profiles.id','name')
                                         ->join('profiles', 'profiles.id', '=', 'receiver_profile_id')
                                        ->where('sender_profile_id','=',$create['sender_profile_id'])
                                        ->where('receiver_profile_id','=',$checkvalue[$i])
                                        //->where('status','!=','1')                                       
					->groupBy('receiver_profile_id')->get()->toArray();
              
               if(count($results)==0)
               {
                   $results =  Mentor::select('profiles.id','name')
                                         ->join('profiles', 'profiles.id', '=', 'sender_profile_id')
                                        ->where('receiver_profile_id','=',$create['sender_profile_id'])
                                        ->where('sender_profile_id','=',$checkvalue[$i])
                                        //->where('status','!=','1')                                       
					->groupBy('receiver_profile_id')->get()->toArray();
               }
               // print_r($results);exit;
               if(count($results)==0){
                    $result = Mentor::create_record($create);
                    MentorUsers::create_record($create['receiver_profile_id'],$result->id);
                    MentorUsers::create_record($create['sender_profile_id'],$result->id);
                    MentorUsers::where('profile_id',$create['receiver_profile_id'])->update(['status'=>'0']);
                    MentorUsers::where('profile_id',$create['sender_profile_id'])->update(['is_readed'=>'Y']);
               }
                else {
                    //print_r($results[$i]['name']);exit;
                    for($j=0;$j<count($results);$j++) {
                    $error.= "".$results[$j]['name'].","; }
                }
            }
            if(!$error)
                return Redirect::to('search')->with('succ_msg', 'Mentor Request sent successfully');
            else {
                $error.=" Profiles Mentor Requests already exists ";
                return Redirect::to('search')->with('error_msg', $error);
            } 
                 
           
            
	}
        
        /** 
         * To display view result of mentor requests
         *  **/

        public function mentorview()
        {
            //echo Session::get('auth_selected_profile');exit;
            if(!Session::get('auth_selected_profile')) {
               return Redirect::to('profile/step1')->with('succ_msg', 'Please Create atleast one profile'); 
            }  $res_act='';
               $res_inact='';
                $res_inact = Mentor::getrecordsInactive(Session::get('auth_selected_profile'));
                $res_act = Mentor::getrecordsActive(Session::get('auth_selected_profile'));
                 
                 //echo '<pre>';print_r($res_act);exit;
                for($i=0;$i<count($res_act);$i++)
                {
                    if($res_act[$i]['profile_image']=='')
                    {
                        $res_act[$i]['profile_image']='default-profile.png';
                    }
                }
                  for($i=0;$i<count($res_inact);$i++)
                {
                    if($res_inact[$i]['profile_image']=='')
                    {
                        $res_inact[$i]['profile_image']='default-profile.png';
                    }
                }
                return view('mentor.index')->with(['error_msg'=>Session::get('error_msg'),'res_act'=>$res_act,'res_inact'=>$res_inact]);
        }
        public function inboxajax()
        {
            $res_all = '';
            $res_all = Mentor::getrecords(Session::get('auth_selected_profile'));
            for($i=0;$i<count($res_all);$i++)
            {
                if($res_all[$i]['profile_image']=='')
                {
                    $res_all[$i]['profile_image']='default-profile.png';
                }
            }

            return view('mentor.inboxajax')->with(['error_msg'=>Session::get('error_msg'),'res_all'=>$res_all]);
        }
        public function mentorstatus($status,$sid)
        {
            $status_new = '';
            $subject = '';
            $result = Mentor::where(array('receiver_profile_id'=>Session::get('auth_selected_profile'),'sender_profile_id'=> $sid))->first();
            if(count($result)==0){
                $result = Mentor::where(array('sender_profile_id'=>Session::get('auth_selected_profile'),'receiver_profile_id'=> $sid))->first();
            }
            if($status == 'yes'){
                    $subject = "Mentor/Mentee Request has been Accepted";
                     $status_info = "Accepted";
                    $status_new = 1;
                   MentorUsers::where(array('profile_id' => Session::get('auth_selected_profile'),'mentor_id' => $result->id))->update(['status'=>'1']);
                   MentorUsers::where(array('profile_id' => $sid,'mentor_id' => $result->id))->update(['status'=>'0']);
            }
            else if($status == 'no'){
                   //echo 44; exit;
                    $subject = "Mentor/Mentee Request has been Declined";
                    $status_info = "Declined";
                    $status_new = 2;
            }
            else if($status == 'delete'){
                    $subject = "Mentor/Mentee Request has been Deleted";
                    $status_info = "Deleted";
                    $status_new = 3;
            }
            else
                    $status_new = 0;
               
           $result->status = $status_new;
           
           $mentor_req = MentorUsers::where(array('profile_id' => Session::get('auth_selected_profile'),'status'=>'1','mentor_id' => $result->id))->first();
           $mentor_del = MentorUsers::where(array('profile_id' => $sid,'status'=>'0','mentor_id' => $result->id))->first();
                         
                        if($mentor_req)
                        { 
                            $mentor_req->is_readed = 'Y';
                            $mentor_req->save();
                        }
         $mentor_req = MentorUsers::where(array('profile_id' => Session::get('auth_selected_profile'),'mentor_id' => $result->id))->first();
         $mentor_del = MentorUsers::where(array('profile_id' => $sid,'mentor_id' => $result->id))->first();   
                if($status_new==3 || $status_new==2){
                    $result->delete();
                    $mentor_req->delete();
                    $mentor_del->delete();
                }
                else
                {  
                    $result->save();
                }   
                
                        
                    $sender_db = Profile::getprofileinfo($sid);                    
                    $recever_db = Profile::getsenderinfo(Session::get('auth_selected_profile'));                   
                     $message = $recever_db[0]['name']." \n Hass been accepted Your Mentor Request!!";
                      $subjectinfo = $subject;
                      Mail::send('emails.mentor', ['name' => $sender_db[0]['name'],'name1' => $recever_db[0]['name'],'status' => $status_info], function($message)
					        use($sender_db){
					            $message->to($sender_db[0]['email'], $sender_db[0]['name'])->subject('Mentor/ Mentee Connection Request');       		
					        });
                    
                
                return Redirect::to('mentorview')->with('succ_msg',$subject);
                 
        }
        
        public function compose(Request $request)
	{ 
		$input= $request->all();
                $mentor_req = MentorUsers::where(array('profile_id' => $input['sel_to_prof_id'],'mentor_id' => $input['mentor_id']))->first();
                         
                        if($mentor_req && $input['sel_to_prof_id']!=Session::get('auth_selected_profile'))
                        { 
                            $mentor_req->is_readed = 'N';
                            $mentor_req->save();
                        }
              
		$result = Mentor::where('id','=',$input['mentor_id'])->first();
		if(isset($result)):
			
			$result->msg_content = $input['message'];
                        $result->save();
                
                        $res = MentorUsers::where(array('profile_id'=>$input['sel_from_prof_id'],'mentor_id'=>$input['mentor_id']))->first();
                        //$resnew = MentorUsers::where(array('profile_id'=>Session::get('auth_selected_profile'),'mentor_id'=>$input['mentor_id']))->first();
                      
                        if(count($res)==0){
                            $res_info = MentorUsers::create_record($input['sel_from_prof_id'],$input['mentor_id']);
                            //$res_info = MentorUsers::create_record(Session::get('auth_selected_profile'),$input['mentor_id']);
                        }
                        else
                        { if($input['sel_from_prof_id']!=Session::get('auth_selected_profile'))
                           {
                           $res->is_readed = 'N' ;
                           $res->save();
                           }
                        }
                        /*
                        if(count($resnew)==0){
                            //$res_info = MentorUsers::create_record($input['sel_to_prof_id'],$input['mentor_id']);
                            $res_info = MentorUsers::create_record(Session::get('auth_selected_profile'),$input['mentor_id']);
                        }
                        else
                        {
                           $resnew->is_readed = 'N' ;
                           $resnew->save();
                        }
                
                        $result->save();*/
                       
			return redirect('mentorview')->with('succ_msg',"Mentor Message Sent Successfully");
		else :
			return redirect(URL::previous())->with('error_msg',"Invalid To address");
		endif;
	}
        
        public function mentor_delete($msg_id)
	{  
		if(is_numeric($msg_id)):
			$msg_mentor_det = Mentor::where('id',$msg_id)->first();
                
			if(isset($msg_mentor_det->id)):
				$msg_mentor_det->delete();
                        
                                $mentor_req = MentorUsers::where(array('profile_id' => Session::get('auth_selected_profile'),'mentor_id' => $msg_id))->first();
                        
                                if($mentor_req)
                                { 
                                    //$mentor_req->is_readed = 'Y';
                                    $mentor_req->delete();
                                }
				return redirect('mentorview/')->with('succ_msg',"Selected Message Delete Successfully");
			else:
				return redirect('mentorview/')->with('error_msg',"Invalid Request");
			endif;
		endif;
	}
        
        public function mentor_details($msg_id)
	{ 
		if(is_numeric($msg_id)){
                        
                        
			$msg_mentor_det = Mentor::getfindresult($msg_id,Session::get('auth_selected_profile'));
                    
                       //print_r($msg_mentor_det); exit;
                       //echo receiver_profile_id Session::get('auth_selected_profile'); 
                        if($msg_mentor_det->status==1){
                            
                            $mentor_res = Mentor::where(array('id' => $msg_id))->first();
                            //print_r($mentor_res); exit;
                            //echo $mentor_res->receiver_profile_id; exit;
                            if($mentor_res->receiver_profile_id==Session::get('auth_selected_profile'))
                            {//echo $mentor_res->receiver_profile_id;exit;
                                $mentor_req = MentorUsers::where(array('profile_id' => $mentor_res->receiver_profile_id,'mentor_id' => $msg_id))->first();
                                //echo '<pre>'.print_r($mentor_req);exit;
                                if(count($mentor_req))
                                { 
                                    $mentor_req->is_readed = 'Y';
                                    $mentor_req->status = '1';
                                    $mentor_req->save();


                                }
                            }
                            if($mentor_res->sender_profile_id==Session::get('auth_selected_profile'))
                            {//echo $mentor_res->sender_profile_id;exit;
                                $mentor_req_new = MentorUsers::where(array('profile_id' => $mentor_res->sender_profile_id,'mentor_id' => $msg_id))->first();
                                 //echo '<pre>'.print_r($mentor_req_new);exit;
                                 if(count($mentor_req_new))
                                {
                                    $mentor_req_new->is_readed = 'Y';
                                    $mentor_req_new->status = '1';
                                    $mentor_req_new->save();
                                }
                            }
                                
                           
                        //  print_r($mentor_res->receiver_profile_id); exit;
                            // echo count($mentor_req).'r';
                            //  echo count($mentor_req_new).'s';exit;
                             //echo $msg_mentor_det->id;exit;
                            
                            
                           
                            
                            if(isset($msg_mentor_det->id)){

                                return view('mentor.details')->with(array('msg_details'=>$msg_mentor_det));	
                            }                        	
                            else { 
                                return redirect(URL::previous())->with('error_msg',"Invalid Request");
                            }
                      }
                      else
                      {
                          return redirect('mentorview/')->with('succ_msg','You donot have permission to access this message');
                      }
                }
         }
}
