<?php namespace App\Http\Controllers;
use App\Profile; // Profile Model
use Auth; // Auth model
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Input;
use Session;
use App\Categories;
use App\Industry;
use App\Roles;
use App\Search;
use Config;
use Datatables;
use App\Countries;
use App\Connections;
use App\ConnectionUsers;
use Mail;
use App\User;
use URL;
use App\Currency;
use App\CurrencyUnits;
use App\Users_likes;
use App\Import_contacts;

class SearchController extends Controller {

	/*
	|--------------------------------------------------------------------------
	| Search Controller
	|--------------------------------------------------------------------------
	|
	|
	*/

	/**
	 * Search 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 index(Request $request)
	{
		//print_r($request->toArray()); exit;
                $search_type = array("everyone"=>"Everyone");	
		$input = $request->all(); $history_data = '';

		$parent_data = Categories::getListofCategories(Session::get('auth_selected_profile_type'));
                $currency_all = Currency::getAllCurrency();
                $currency_units = CurrencyUnits::getAllUnits();	
		$child_data = Categories::getListofCategoriesLikeArray(true);
		$industry_data = Industry::getList();
		$roles_data = Roles::getList();
		$countries = Countries::orderBy('name')->get();
                $prof_det = Profile::find(Session::get('auth_selected_profile'));
//		$search_history = Search::getListArrayByProfile(Session::get('auth_selected_profile'));
		$search_history = Search::where('profile_id','=',Session::get('auth_selected_profile'))->orderBy('name')->get();
		if(isset($input['history']) && is_numeric($input['history']))
		{
			$history_id = $input['history'];	
			$check_history = Search::find($history_id);
			if(count($check_history) && $check_history->id)
				$history_data = unserialize($check_history['search_terms']);
		}

		if($request->input('search'))
		{      
			
			//  dd($input);
                        $likes=array();
                        $res1['likes_id']=array();
                        $res2['like_user_id']=array();
			$limit = $default_limit = Config::get('constants.PROFILE_SEARCH_LIMIT'); 
			$offset = Config::get('constants.PROFILE_SEARCH_OFFSET');	
			$profile_type = Config::get('constants.PROFILE_SEARCH_DEFAULT_PROFILE_TYPE');
				//echo $profile_type; exit;
			/*echo "<pre>"; 
			print_r($input);
			exit;*/
			unset($input['_token']);
			if($input['search']=='search_save'):
				$data = $input;
				$search_save_name = $data['save_name'];
				$search_save_id = $data['save_id'];
				unset($data['save_id']);unset($data['save_name']);unset($data['search']);
				/* Serialize the searching data*/
				$serialize_data = serialize($data);
				/*searching data save*/
					if($search_save_id):
						$model = Search::find($search_save_id);	
						$model->search_terms = $serialize_data;
						$model->save();
					else:	
						$save_search['name']= $search_save_name;	
						$save_search['profile_id'] = Session::get('auth_selected_profile');
						$save_search['search_terms'] = $serialize_data;
						Search::create($save_search);
					endif;	
				/* searching data save*/
			endif;

			if(isset($input['limit']))
				$limit = $input['limit'];

			if(isset($input['offset']))
				$offset = $input['offset'];

			if(Session::get('auth_selected_profile_type'))
				$profile_type = Session::get('auth_selected_profile_type');	
                        
                        $search_results = Profile::search($input,$limit,$offset,$profile_type);
                        //echo $search_results->count();exit;
                        if(!empty($search_results)>0):
                        foreach($search_results as $like):
                            $likes[] = Users_likes::select('likes_id','like_user_id')->where("like_user_id",'=',Auth::user()->id)->where("likes_id",'=',$like->id)->where("likes_type",'=','P')->get()->toArray();  
                        endforeach;
                        endif;
                     //print_r($likes);
                            foreach($likes as $resval=>$val){     //  print_r($val[0]);                         
                               if(!empty($val[0]['likes_id'])){
                                $res1['likes_id'][] = $val[0]['likes_id'];
                                $res2['like_user_id'][] = $val[0]['like_user_id'];
                               }
                                
                            }
                        
			$user_id=Auth::user()->id;
                        
			$count_search_results = Profile::search($input,$limit,$offset,$profile_type,true);
			//echo $count_search_results; exit;
			$search_history = Search::where('profile_id','=',Session::get('auth_selected_profile'))->orderBy('name')->get();
		   return view('search.list')->with(['error_msg'=>Session::get('error_msg'),'countries'=>$countries,'search_history'=>$search_history,'search_data'=>$input,'default_limit'=>$default_limit,'total_records'=>$count_search_results,'search_result'=>$search_results,'res1'=>$res1,'res2'=>$res2,'user_id'=>$user_id]);
		}
		else		
	    return view('search.index')->with(['error_msg'=>Session::get('error_msg'),'countries'=>$countries,'search_history'=>$search_history,'history_data'=>$history_data,'search_type'=>$search_type,'parent_data'=>$parent_data,'child_data'=>$child_data,'industry_data'=>$industry_data,'roles_data'=>$roles_data,'currency_all'=>$currency_all,'currency_units'=>$currency_units, 'prof_det'=> $prof_det]);
	}
        public function connect_details($msg_id)
	{            
            $msg_connect_det = Connections::getMessagesInfo($msg_id,Session::get('auth_selected_profile'));
          //print_r($msg_connect_det->toArray()); 
            if($msg_connect_det->id)
            {
                 //echo Session::get('auth_selected_profile'); 
                 $rs = ConnectionUsers::where(array('connection_id'=>$msg_connect_det->id,'profile_id'=>Session::get('auth_selected_profile')))->first();
                 //print_r($rs->toArray());exit;
                 $rs->is_read = 'Yes';
                 $rs->update(); 
                 
                 /*$rs = ConnectionUsers::where(array('connection_id'=>$msg_connect_det->id,'profile_id'=>$msg_connect_det->receiver_profile_id))->first();
                 $rs->is_read = 'Yes';
                 $rs->update();*/
               
                if($msg_connect_det->folder == 'I')
                            $user = Profile::find($msg_connect_det->sender_profile_id);
                        else
                            $user = Profile::find($msg_connect_det->receiver_profile_id);
                        $msg_connect_det->name = $user->name;
                return view('connections.details')->with(array('msg_details'=>$msg_connect_det));	
     
            }
            else 
            { 
                return redirect(URL::previous())->with('error_msg',"Invalid Request");
            }
           
        }
        public function message(Request $request)
        {
		$input= $request->all();                
                //echo '<pre>'.print_r($input);exit;
               
                $result = Connections::where('id','=',$input['connection_id'])->first();
                //print_r($mentor_req); exit;
		if($result->count()>0):
                   $connect_updt = Connections::where('id', $input['connection_id'])->first();
                    $connect_updt->message = $input['message']; 
                    $update_id = '';
                    if(Session::get('auth_selected_profile') == $connect_updt->sender_profile_id)
                    {
                        $update_id = $connect_updt->receiver_profile_id;
                    }
                    else
                    {
                        $update_id = $connect_updt->sender_profile_id;
                    }
                    
                    
                    $rs1 = ConnectionUsers::where(array('connection_id'=>$connect_updt->id,'profile_id'=>$update_id))->first();
                    $rs1->is_read = 'No'; 
                    $rs1->update(); 

                    /*$rs2 = ConnectionUsers::where(array('connection_id'=>$connect_updt->id,'profile_id'=>$connect_updt->sender_profile_id))->first();
                    $rs2->is_read = 'Yes';
                    $rs2->update();*/
                    
                    $connect_updt->update();
                        
                
                   /*$rs = Connections::find($input['connection_id'])->first();
                    $rs->is_read = 'No';
                    $rs->update();*/
                    
		   if(isset($connect_updt)):
                       return redirect('connectionview')->with('succ_msg',"Connection Message Sent Successfully");
		    else :
			return redirect(URL::previous())->with('error_msg',"Invalid To address");
		  endif;
                else:
                       return redirect(URL::previous())->with('error_msg',"Invalid To address");
                endif;
	
        }

        public function msg_details(Request $request)
          { 
                  $data_id = Input::get('u_id');
                  if(is_numeric($data_id))
                  {
                      
                        
			$msg_mentor_det = Connections::getMessagesInfo($data_id,Session::get('auth_selected_profile'));
                        //echo"<pre>   "; print_r($msg_mentor_det); exit;
                   // return $msg_mentor_det->status;exit;
                        /*echo $msg_mentor_det->receiver_profile_id ;
                        exit;*/
                        if($msg_mentor_det->folder == 'I')
                            $user = Profile::find($msg_mentor_det->sender_profile_id);
                        else
                            $user = Profile::find($msg_mentor_det->receiver_profile_id);
                        
                        /*echo "<pre>";
                        print_r($user);
                        exit;*/
                        $msg_mentor_det->name = $user->name;
                        
                       //echo"<pre>   "; print_r($msg_mentor_det); exit;
                        if($msg_mentor_det->status=='Active'){
                            
                          //return $msg_mentor_det->status; exit;
                                return view('connections.send_message')->with(array('msg_details'=>$msg_mentor_det));	
                           
                      }
                      else
                      {
                          return redirect('connectionview/')->with('succ_msg','You donot have permission to access this message');
                      }
                 }
          }
	public function ajax(Request $request)
	{	
			
		$input = $request->all();
                $result = array();
                $likes=array();
                $res1['likes_id']=array();
                $res2['like_user_id']=array();
		$profile_type = Session::get('auth_selected_profile_type');	
		$search_results = Profile::search($input,$input['limit'],$input['offset'],$profile_type);
		$count_search_results = Profile::search($input,$input['limit'],$input['offset'],$profile_type,true);
                        //echo $search_results->count();exit;
                        if(!empty($search_results)>0):
                        foreach($search_results as $like):
                            $likes[] = Users_likes::select('likes_id','like_user_id')->where("like_user_id",'=',Auth::user()->id)->where("likes_id",'=',$like->id)->where("likes_type",'=','P')->get()->toArray();  
                        endforeach;
                        endif;
                     //print_r($likes);
                            foreach($likes as $resval=>$val){     //  print_r($val[0]);                         
                               if(!empty($val[0]['likes_id'])){
                                $res1['likes_id'][] = $val[0]['likes_id'];
                                $res2['like_user_id'][] = $val[0]['like_user_id'];
                               }
                                
                            }
                  $result['user_id']=Auth::user()->id;
		$result['data'] = $search_results;
                $result['res1'] = $res1;
                $result['res2'] = $res2;
		$result['total'] = $count_search_results;
		echo json_encode($result);
	}

	public function history()
	{

	    return view('search.history')->with(['error_msg'=>Session::get('error_msg')]);
	}

	public function ajax_history()
	{
		$results = Search::where('profile_id','=',Session::get('auth_selected_profile'))->select(['id','search_terms','created_at']);
		return Datatables::of($results)
						->addColumn('action', function($results) {
							return '<a href="javascript:void(0)" class="btn btn-primary search_history" data-search="'.$results['id'].'"><i class="fa fa-search"></i> Search</a>';
						})
						->editColumn('search_terms',function($results){
							if($results['search_terms']):
								$array_sea = unserialize($results['search_terms']);
								unset($array_sea['req_search_type']);
								$return_array = '';
								foreach($array_sea as $k => $value):
									if($return_array && $value)
										$return_array = $return_array." , <strong>".ucwords($k)."</strong> : ".$value;
									else if($value)
										$return_array = "<strong>".ucwords($k)."</strong> : ".$value;
								endforeach;	
								return str_replace('_', ' ', $return_array);
							else:
								return "";
							endif;
						})
						->editColumn('created_at',function($results){
//							return date("m/d/Y h:i:s a",strtotime($results['created_at']));
							return date("m/d/Y",strtotime($results['created_at']));
						})
						->make(true);
	}
	
	public function connection(Request $request)
        {
            $input = $request->all();
            $compose['sender_profile_id'] = Session::get('auth_selected_profile');
            $message = $input['connection_message'];
            $reciver_ids = explode(',',$input['ids']);            
            //print_r($reciver_ids);
            $error = '';
            for($i=0;$i<count($reciver_ids);$i++)
            {
                $results = '';
                $results =  Connections::select('connections.id','name','status')
                                         ->join('profiles', 'profiles.id', '=', 'receiver_profile_id')
                                        ->where('sender_profile_id','=',$compose['sender_profile_id'])
                                        ->where('receiver_profile_id','=',$reciver_ids[$i])
					->groupBy('receiver_profile_id')->get()->toArray(); 
                if(count($results)==0){
                    
                    $results = Connections::select('connections.id','name','status')
                                         ->join('profiles', 'profiles.id', '=', 'sender_profile_id')
                                        ->where('sender_profile_id','=',$reciver_ids[$i])
                                        ->where('receiver_profile_id','=',$compose['sender_profile_id'])
					->groupBy('sender_profile_id')->get()->toArray();
                
                }
                
               if(count($results)==0)
                {
                   
                   $return_data= Connections::create_record($compose['sender_profile_id'],$reciver_ids[$i],$message);
                   if(count($return_data)>0)
                   { 
                      ConnectionUsers::create_record($compose['sender_profile_id'],$return_data->id,'S');
                      ConnectionUsers::where('connection_id',$return_data->id)->where('profile_id',$compose['sender_profile_id'])->update(array('is_read' => 'Yes'));
                      ConnectionUsers::create_record($reciver_ids[$i],$return_data->id,'I');
                       
                   }
                       
                    
               }
                else {
                   
                    for($j=0;$j<count($results);$j++) {
                    $error.= $results[$j]['name']." Connection already exists <br/>"; 
                   
                    if($results[$j]['status']=='delete')
                        Connections::where('id',$results[$j]['id'])->update(array('status' => 'Pending'));
                    }
                }
            }
            if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') 
            {
              if(!$error)
                  echo "<p class='alert alert-success clearfix'> Connection Request Sent Successfully </p>";
              else
                   echo "<p class='alert alert-danger clearfix'>".$error." </p>";
            }
            else
            {
              if(!$error)
                return Redirect::to('search')->with('succ_msg', 'Connection Request Sent Successfully'); 
              else
                return Redirect::to('search')->with('error_msg', $error); 
            }            
            
           
        }
         public function ajax_connection(Request $request)
        {
            $input = $request->all();
            $compose['sender_profile_id'] = Session::get('auth_selected_profile');
            $message = $input['connection_message'];
            $reciver_id = $input['ids'];            
            //print_r($reciver_ids);
            $error = '';
            
                $results = '';
                $results =  Connections::select('connections.id','name','status')
                                         ->join('profiles', 'profiles.id', '=', 'receiver_profile_id')
                                        ->where('sender_profile_id','=',$compose['sender_profile_id'])
                                        ->where('receiver_profile_id','=',$reciver_id)
					->groupBy('receiver_profile_id')->first(); 
                if(count($results)==0){
                    
                    $results = Connections::select('connections.id','name','status')
                                         ->join('profiles', 'profiles.id', '=', 'sender_profile_id')
                                        ->where('sender_profile_id','=',$reciver_id)
                                        ->where('receiver_profile_id','=',$compose['sender_profile_id'])
					->groupBy('sender_profile_id')->first();
                
                }
                
               if(count($results)==0)
                {
                   
                   $return_data= Connections::create_record($compose['sender_profile_id'],$reciver_id,$message);
                   if(count($return_data)>0)
                   { 
                      ConnectionUsers::create_record($compose['sender_profile_id'],$return_data->id,'S');
                      ConnectionUsers::where('connection_id',$return_data->id)->where('profile_id',$compose['sender_profile_id'])->update(array('is_read' => 'Yes'));
                      ConnectionUsers::create_record($reciver_id,$return_data->id,'I');
                       
                   }
                       
                    
               }
                else {
                   
                   $error.= '<div class="alert alert-danger">
                     <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                       <span aria-hidden="true">&times;</span>
                     </button>'.$results['name']." Connection already exists".'</div>';
                   
                    if($results['status']=='delete'){
                        Connections::where('id',$results['id'])->update(array('status' => 'Pending'));
                    }
                    
                }
            
            if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') 
            {
              if(!$error)
              {
                  echo '<div class="alert alert-success"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>Connection Request Sent Successfully</div>';
              }
              else
              {
                 echo $error;
              }
                 
            }
            else
            {
              if(!$error)
              {
                echo '<div class="alert alert-success"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>Connection Request Sent Successfully</div>'; 
              }
              else
              {
                echo $error;
              }
            }            
            
           
        }
        
        public function connectionview()
	{ 
            //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'); 
            }
             
                $results = Connections::getrecords(Session::get('auth_selected_profile'));
                for($i=0;$i<count($results);$i++)
                {
                    if(empty($results[$i]['profile_image']))
                    {
                        $results[$i]['profile_image']='default-profile.png';
                    }
                }
                return view('connections.index')->with(['error_msg'=>Session::get('error_msg'),'results'=>$results]);
                
	}
        
        public function connectedlist(Request $request)
        {
            /*$input = $request->all();
            $input['msg_type'] = 'I';
		$results = Connections::getrecords(Session::get('auth_selected_profile'));
                $listview = array();
                foreach($results as $key=>$val){ $res[$key] = $val;  }
               // print_r($res); exit;
                $default_image = 'default-profile.png';
                for($i=0;$i<count($results);$i++)
                {
                   $prof_det = Profile::find($res[$i]['sender_profile_id']);
			$sender = '<strong>'.$prof_det->name.'</strong>';

			if($prof_det->profile_image)								
				$default_image = $prof_det->profile_image;
				$listview[].= '<img src="'.url('uploads/profile_images/'.$default_image).'" class="img-circle" width="30px" height="30px"> &nbsp;'.ucwords($sender);
              
                }
                return $listview;*/
            $results = Connections::getrecords(Session::get('auth_selected_profile'));
            for($i=0;$i<count($results);$i++)
            {
                if($results[$i]['profile_image']=='' && !is_file('uploads/profile_images/'.$results[$i]['profile_image']))
                {
                    $results[$i]['profile_image']='default-profile.png';
                }
            }
            //print_r($results); exit;
            echo json_encode($results);
        }
        
        public function statuschange(Request $request)
        {
            $input = $request->all();           
            $result = Connections::where(array('receiver_profile_id'=>Session::get('auth_selected_profile'),'sender_profile_id'=>$input['pid']))->first();
           
            if(count($result)==0){
                $result = Connections::where(array('sender_profile_id'=>Session::get('auth_selected_profile'),'receiver_profile_id'=> $input['pid']))->first();
            }
            if($result->status =='Active')
            {
                $result->status = 'Pending';
                $result->save();
            }
            else if($result->status =='Pending')
            {
                $result->status = 'Active';
                //$result->save();
                if($result->save())
                {                   
                    $sender_db = Profile::getprofileinfo($input['pid']);                    
                    $recever_db = Profile::getsenderinfo(Session::get('auth_selected_profile'));
                   
                     $message = $recever_db[0]['name']." \n Hass been accepted Your Connection Request!!";
                      Mail::send('emails.connection', ['name' => $sender_db[0]['name'],'name1' => $recever_db[0]['name']], function($message)
					        use($sender_db){
					            $message->to($sender_db[0]['email'], $sender_db[0]['name'])->subject('Connection Request Accepted');       		
					        });
                }
            }
            
            
            echo "Connection Request Accepted";
            //Session::put('succ_msg', 'Connection Request Accepted');
            
            
            
        }
        
        public function statusdelete(Request $request)
        {
            $input = $request->all();           
            $result = Connections::where(array('receiver_profile_id'=>Session::get('auth_selected_profile'),'sender_profile_id'=>$input['pid']))->first();
             if(count($result)==0){
                $result = Connections::where(array('sender_profile_id'=>Session::get('auth_selected_profile'),'receiver_profile_id'=> $input['pid']))->first();
            }
           // echo $result['id'];exit;
            if(count($result)){
                 $datausers = ConnectionUsers::where('connection_id',$result['id'])->delete();
                $result->delete();
            }           
            
			echo "Connection Request Deleted";
            
        }
		
		/*
		*  Find out how many pending connection are available 
		*/
        public function findconnections()
        {
            $results = Connections::findconnections(Session::get('auth_selected_profile'));
        }
		
        /*
	*  list out saved search list 
	*/
        public function savedsearch()
        {
            $results = Search::getSearchList(Session::get('auth_selected_profile'));
            return view('search.savedlist')->with(['error_msg'=>Session::get('error_msg'),'results'=>$results]);
        }
        /*
         * Delte Saved search result
         */
        public function deletesearch($sid)
        { 
            $results = Search::find(array('id'=>$sid))->first();
            if(count($results)>0)
                $results->delete();
           
            //$results = Search::getSearchList(Session::get('auth_selected_profile'));
            return Redirect::to('savedsearch')->with('succ_msg','Successfully deleted search result');
            // return view('search.savedlist')->with(['succ_msg'=>'Successfully deleted search result','results'=>$results]);
            
        }
        /*
         * view search Results
         */
        public function searchresult($sid)
        { //echo $sid; exit;
            //$result = Search::find(array('id'=>$sid))->first();
            if($sid){
             $likes=array();
             $res1['likes_id']=array();
             $res2['like_user_id']=array();
            $result = Search::select('id','name','profile_id','search_terms')->where('id','=',$sid)->get();
            $result_array = array();
		foreach($result as $res):
			$result_array[$res->id] = array('id'=>$res->id,'name'=>$res->name,'profile_id'=>$res->profile_id,'search_data'=>unserialize($res->search_terms));
		endforeach;	

                
                $search_type = array("everyone"=>"Everyone");
                
               // echo $result_array[$sid]['search_data'];
               // print_r($result_array); exit;
		$input = $result_array[$sid]['search_data']; $history_data = '';

		$parent_data = Categories::getListofCategories(Session::get('auth_selected_profile_type'));
		$child_data = Categories::getListofCategoriesLikeArray(true);
		$industry_data = Industry::getList();
		$roles_data = Roles::getList();
		$countries = Countries::orderBy('name')->get();
//		$search_history = Search::getListArrayByProfile(Session::get('auth_selected_profile'));
		$search_history = Search::where('profile_id','=',Session::get('auth_selected_profile'))->orderBy('name')->get();
		
			$limit = $default_limit = Config::get('constants.PROFILE_SEARCH_LIMIT'); 
			$offset = Config::get('constants.PROFILE_SEARCH_OFFSET');	
			$profile_type = Config::get('constants.PROFILE_SEARCH_DEFAULT_PROFILE_TYPE');	
			
			if($result_array[$sid]['search_data']):
				$data = $result_array[$sid]['search_data'];
				//$search_save_name = $data['save_name'];
				$search_save_id = $result_array[$sid]['id'];
				//unset($data['save_id']);unset($data['save_name']);unset($data['search']);
				/* Serialize the searching data*/
				$serialize_data = serialize($data);
				/*searching data save*/
					if($search_save_id):
						$model = Search::find($search_save_id);	
						$model->search_terms = $serialize_data;
						$model->save();
					else:	
						$save_search['name']= $search_save_name;	
						$save_search['profile_id'] = Session::get('auth_selected_profile');
						$save_search['search_terms'] = $serialize_data;
						Search::create($save_search);
					endif;	
				/* searching data save*/
			endif;

			if(isset($input['limit']))
				$limit = $input['limit'];

			if(isset($input['offset']))
				$offset = $input['offset'];

			if(Session::get('auth_selected_profile_type'))
				$profile_type = Session::get('auth_selected_profile_type');	

			$search_results = Profile::search($input,$limit,$offset,$profile_type);
                        if(!empty($search_results)>0):
                        foreach($search_results as $like):
                            $likes[] = Users_likes::select('likes_id','like_user_id')->where("like_user_id",'=',Auth::user()->id)->where("likes_id",'=',$like->id)->where("likes_type",'=','P')->get()->toArray();  
                        endforeach;
                        endif;
                     //print_r($likes);
                            foreach($likes as $resval=>$val){     //  print_r($val[0]);                         
                               if(!empty($val[0]['likes_id'])){
                                $res1['likes_id'][] = $val[0]['likes_id'];
                                $res2['like_user_id'][] = $val[0]['like_user_id'];
                               }
                                
                            }
                         $user_id=Auth::user()->id;
                         
			$count_search_results = Profile::search($input,$limit,$offset,Session::get('auth_selected_profile_type'),true);
			$search_history = Search::where('profile_id','=',Session::get('auth_selected_profile'))->orderBy('name')->get();
		    
                        return view('search.list')->with(['error_msg'=>Session::get('error_msg'),'countries'=>$countries,'search_history'=>$search_history,'search_data'=>$input,'default_limit'=>$default_limit,'total_records'=>$count_search_results,'search_result'=>$search_results,'res1'=>$res1,'res2'=>$res2,'user_id'=>$user_id]);
		
            } 
            
        }
        
        /* 
         * Import contacts
         */
        public function getContacts()
        { 
            $data = Import_contacts::select('id','importer','status','title','image')->get()->toArray();
            return View('emails.contacts')->with('data',$data);
        }
         public function searchContacts(Request $request)
        {
            $input = $request->all();
            $ids="";
            $search_result=array();
            $search_result['profiles']=array();
            $search_result['emails']=array();
            if(!empty($input['contact_list'])):
                 $string=$input['contact_list']; 
              foreach(preg_split('/\s/', $string) as $token)
              {
             $email = filter_var(filter_var($token, FILTER_SANITIZE_EMAIL));
                if ($email !== false) 
                    {
                        $user = User::where('email','=',$email)->first();
                        if(!empty($user['id']) && $user['id']!=Auth::user()->id)
                        {
                        $profile = Profile::where('user_id','=',$user['id'])->first();
                        $ids[]=$profile['id'];
                        $search_result['profiles'][]=$profile;
                        }
                        else
                        {
                           if($user['id']!=Auth::user()->id)
                            {
                            $search_result['emails'][]=$email;
                            }
                        }
                    }
              } 
              
             endif;
             //print_r($search_result);exit;
            $input=$ids;
            $flag=1;
            $default_limit = Config::get('constants.PROFILE_SEARCH_LIMIT'); 
            $countries = Countries::orderBy('name')->get();
            $count_search_results =  sizeof($ids);
            $search_history = Search::where('profile_id','=',Session::get('auth_selected_profile'))->orderBy('name')->get();
            return view('connections.invite_to_join')->with(['error_msg'=>Session::get('error_msg'),'countries'=>$countries,'search_history'=>$search_history,'search_data'=>$input,'default_limit'=>$default_limit,'total_records'=>$count_search_results,'search_result'=>$search_result,'flag'=>$flag]);
            
        }
        public function ajax_invite(Request $request)
        {
            $input = $request->all();
            $insert_email = Auth::user()->email;
            $insert_name = Auth::user()->name;
            $mail= Mail::send('emails.invite_join', ['name' => $insert_name,'email' => $insert_email], function($message)
					        use($input,$insert_email,$insert_name){
                                                    $message->from($insert_email, $insert_name);
					            $message->to($input['ids'])->subject('Invitation to Join Sanskar!');       		
					        });
             if($mail){echo '<div class="alert alert-success"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>Your Invitation Request Sent Successfully</div>';}
             else{echo '<div class="alert alert-danger">
                     <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                       <span aria-hidden="true">&times;</span>
                     </button>Your Invitation Request Fail</div>';}
        }
      
}
