<?php namespace App\Http\Controllers;
use Auth; // Auth model
use Response;
use Storage;
use Illuminate\Http\Request;
use App\Actions;
use Datatables;
use Session;
use Redirect;
use App\user;
use App\Profile; // Profile Model
use App\Messages;
use URL;
use App\Inquiry;
use App\MessageUsers;
use Mail;
use App\Invitations;


class InquirController extends Controller {

	/*
	|--------------------------------------------------------------------------
	| Share Controller
	|--------------------------------------------------------------------------
	|
	|
	*/

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

	/**
	 * Share public files.
	 *
	 * @return Response
	 */
        public function index()
        {
            return view('inquiries.index');
        }
        public function request(Request $request)
	{       
            /* Private type keys with name */
		$private_type = array(  'B'=>'Basic Information','L'=>'location','EXP'=>'Experience','EDU'=>'Education','S'=>'Skills','In'=>'Influence',
								'Int'=>'Interests','A'=>'About us','W'=>'Why us','Cont'=>'Contact information','P'=>'Products / services',
								'AW'=>'Awards');
		/* Private type keys*/
		$private_type_keys = array('B','L','EXP','EDU','S','In','Int','A','W','Cont','P','AW');

		$input = $request->all(); 
                
		if($input['profileList'])
		{
			if(isset($input['enquiry'])) 
			{
				$company      =    $input['company'];
                                $type_inq     =    $input['type_inq'];
                                $desc_inquiry =    $input['desc_inquiry'];
                                
				
				$insert_data=array();
				foreach ($input['profileList'] as $key => $value) 
                                {
					$insert_data = array(
							'receiver_profile_id' => $value,
							'sender_profile_id' => Auth::user()->id,
							'title' =>$type_inq,
							'msg_content' => $desc_inquiry,
                                                        'message_type'=> 'INQ',
                                                        'created_at' => date('Y-m-d h:i:s')
						             );
                                        
                                     $insert_inquiry = Messages::create($insert_data);
                                     $last_id[]=$insert_inquiry->id;
                                     
                                     $send_name = Profile::where('user_id', Auth::user()->id)->first();
                                     $rec_name = Profile::where('user_id', $value)->first();
                                     $rec_email = User::where('id', $value)->first();
                                     
                                     Mail::send('emails.inquiry', ['name' => $rec_name['name'],'firstname'=>$send_name['name'],'data' => $insert_data,'company'=>$company], function($message)
					        use($rec_email){
					            $message->to($rec_email['email'], $rec_email['name'])->subject('Inquiry Form Details');       		
					        });
                                     
                                     
                                     $insert_sen[] = array(
							'profile_id' => Auth::user()->id,
							'message_id' => $insert_inquiry->id,
							'folder' => 'S',
                                                        'created_at' => date('Y-m-d h:i:s')
						        );
                                     
                                     $insert_rec[] = array(
							'profile_id' => $value,
							'message_id' => $insert_inquiry->id,
							'folder' => 'I',
                                                        'created_at' => date('Y-m-d h:i:s')
						        );
                                      
				}
                                //return $insert_rec;exit;
                                $msg_sen= MessageUsers::insert($insert_sen);
                                $msg_rec= MessageUsers::insert($insert_rec);
                                
                                $var="";
                                for($i=0;$i<count($last_id);$i++):
                                    if(!empty($var)) $var=$var.','.$last_id[$i];else $var=$last_id[$i]; 
                                endfor;
                                if(!empty($var)):
                              
                                $insert_data = array(
							
						        'sender_profile_id' => Auth::user()->id,
							'company' => $company,
                                                        'msg_ids'=> $var
						     );
                                $insert_inquiry = Inquiry::create($insert_data);
                                else:
                                    return redirect(URL::previous())->with('error_msg',"Invalid To address");
                                endif;
				return redirect(Url('/search/'))->with('succ_msg',"Your profile has been successfully Inquiried");
			}	

			$profiles = Profile::whereRaw("id IN (".implode(',',$input['profileList']).")")->get();
			$comp_name = User::where('id', Auth::user()->id)->first();
		     return view('inquiries.inquire_list')->with(['share_inquire'=>$profiles,'private_type'=>$private_type,'comp_name'=>$comp_name]);
		}
		else
		{
			return redirect(URL::previous())->with('error_msg',"Invalid To address");
		}
	}
        public function ajax_inquiries(Request $request)
	{
		$input = $request->all();	

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

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

//						->addColumn('action', function($results) {
//							
//								$no = '<button class="btn-primary mleft10 update_inv_status" data-id="'.$results['id'].'" data-type="N">Delete</button>';
//								
//								return $no;
//								
//								
//						})
						->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 = Profile::where('user_id', $results['receiver_profile_id'])->first();	
							/*else
								$user_det = User::find($results['receiver_profile_id']);	*/

							if($results['is_readed']=='N')
								$sender = '<strong>'.$user_det->name.'</strong>';
							else
								$sender =$user_det->name;	
							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){
                                                      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>';

							return $date;
						})
						->make(true);
	}
       public function inquiry_details($inv_id)
	{
		if(is_numeric($inv_id)):
			$inv_user_det = Messages::find($inv_id);
			if(isset($inv_user_det->id) && $inv_user_det->id && $inv_user_det->sender_profile_id == Auth::user()->id):
				 $inv_det = Inquiry::checkMessage($inv_user_det->id);
                       
				if(isset($inv_det->id)):
					
						$user_det = Profile::where('user_id', $inv_user_det->receiver_profile_id)->first();	
					
					return view('inquiries.details')->with(array('inq_details'=>$inv_det,'user_det'=>$user_det,'msg_details'=>$inv_user_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;
	}

	
}
