<?php namespace App\Http\Controllers;

use App\User;
use App\Assets;
use App\Users_likes;
use App\AssetsData;
use Validator;
use Session;
use Illuminate\Support\Facades\Input;
use Vimeo\Vimeo;
use Config;
use Illuminate\Http\Request;
use Redirect;
use Auth;
use App\Countries;
use App\Industry;
use App\Roles;
use App\JobSpecifications;
use App\Profile;
use App\MessageUsers;
use App\Messages;
use Mail;
use App\Countrys;
use App\States;
use Datatables;
use App\Recruitment;
use View;
use Illuminate\Support\Facades\URL;




class JobspecController extends Controller {

    private $current_profile_id;
	/*
	|--------------------------------------------------------------------------
	| User Controller
	|--------------------------------------------------------------------------
	|
	| This controller renders your application's users functionality
	| like signup, login, forgot password.
	|
	*/

	/**
	 * Create a new 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(); 
                             }
                        $this->current_profile_id = Session::get('auth_selected_profile');
                      
                        
                }

	/**
		 * Show the application login to the user.
		 *
		 * @return Response
		 */
		public function index()
		{    $jobs=JobSpecifications::where('profile_id', '=', $this->current_profile_id)->orderBy('id', 'desc')->get();
                        //$countries = Countries::orderBy('name')->get();
                       // $industry_data = Industry::getList();
                       // $roles_data = Roles::getList();
			//return View('Job.jobspec')->with(['countries'=>$countries,'industry_data'=>$industry_data,'roles_data'=>$roles_data]);
                     return View('Job.index')->with(['jobs'=>$jobs]);
                    
                }
                
                public function recruit()
                {
                    return View('recruit.recruitment');
                }
               public function ajax_recruit(Request $request)
                {
		$input = $request->all();	  

		$results = Recruitment::getrecruit(Auth::user()->id);
		
		return Datatables::of($results)

						->addColumn('action', function($results) {
							
								$no = '<button class="btn btn-primary mleft10 delete rectuit-delete-btn" data-id="'.$results['id'].'" data-type="N">Delete</button>';
								
									return $no;
						})
						->addColumn('sender', function($results) {
							$default_image = 'default-profile.png';							
							$user_det = Profile::where('user_id', $results['receiver_profile_id'])->first();
							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>';

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

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

							if($results['is_readed']=='N')
								return '<strong>'.$results['title'].'</strong>';
							else
								return $results['title'];
						})
						->editColumn('id',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 $results['id'];
						})
						->make(true);
	        }
                public function recruit_details($inv_id)
               { $contact_state="";$contact_country="";
                       if(is_numeric($inv_id)):
                               $rec_user_det = Recruitment::find($inv_id);
                               if(isset($rec_user_det->id) && $rec_user_det->id && $rec_user_det->sender_profile_id == Auth::user()->id):
                                        $job_det = JobSpecifications::where('id',$rec_user_det->job_id)->first();

                                       if(isset($job_det->id)):

                                                       $user_det = Profile::where('user_id', $rec_user_det->receiver_profile_id)->first();	
                                                       $industry_data = Industry::getList();
                                                       $roles_data = Roles::getList();
                                                        if(!empty($job_det->country)):
                                                        $country_name = Countrys::where('id', $job_det->country)->first();
                                                        endif;
                                                        if(!empty($job_det->state)):
                                                        $state_name = States::where('id', $job_det->state)->first();
                                                        endif;
                                                        if(!empty($job_det->contact_state)):
                                                        $contact_state = States::where('id', $job_det->contact_state)->first();
                                                        endif;
                                                        if(!empty($job_det->contact_country)):
                                                        $contact_country = Countrys::where('id', $job_det->contact_country)->first();
                                                        endif;
                                               return view('recruit.details')->with(array('job_details'=>$job_det,'user_det'=>$user_det,'recruit_details'=>$rec_user_det,'industry_data'=>$industry_data,'roles_data'=>$roles_data,'country_name'=>$country_name,'state_name'=>$state_name,'contact_state'=>$contact_state,'contact_country'=>$contact_country));						
                                       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 recruit_delete($del_id)
               {   
                    if(is_numeric($del_id)):
                      $pic_id=Recruitment::find($del_id)->get();
                     
                    if(isset($pic_id[0])):

                        $delete1 = Recruitment::where('id', '=', $del_id)->delete();
                       if($delete1):
                           return Redirect::back()->with('succ_msg',"Recruit Deleted Successfully");   
                       else:
                          return Redirect::back()->with('error_msg',"Invalid Request");    
                       endif;
                    else:
                       return Redirect::back()->with('error_msg',"Invalid Request");    
                    endif;
;
                    else:
                      return Redirect::back()->with('error_msg',"Invalid Request");   
                    endif;

               }
                public function sendjobspec(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(); 
                    $contact_state="";$contact_country="";
                    
                    if($input['profileList'])
                    {
                        
			if(isset($input['jobspec'])) 
			{
                            
				$title        =    $input['title'];
                                $type_job     =    $input['type_job'];
                                $desc_jobspec =    $input['desc_jobspec'];
                                
                               
				
				$insert_data=array();
				foreach ($input['profileList'] as $key => $value) 
                                {
				     
                                     
                                     $insert_data = array(
							'receiver_profile_id' => $value,
							'sender_profile_id' => Auth::user()->id,
							'title' =>$title,
							'msg_content' => $desc_jobspec,
                                                        'job_id' => $type_job,
                                                        'created_at' => date('Y-m-d h:i:s')
						             );
                                     
                                     $insert_recruit = Recruitment::create($insert_data);
                                      
                                     // return $type_job;exit;
                                     
                                     $job_spec = JobSpecifications::where('id', $type_job)->first();
                                     $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();
                                     $industry_data = Industry::getList();
                                     $roles_data = Roles::getList();
                                     
                                     if(!empty($job_spec->country)):
                                     $country_name = Countrys::where('id', $job_spec->country)->first();
                                     endif;
                                     
                                     if(!empty($job_spec->contact_country)):
                                     $contact_country = Countrys::where('id', $job_spec->contact_country)->first();
                                     endif;
                                     
                                     if(!empty($job_spec->state)):
                                     $state_name = States::where('id', $job_spec->state)->first();
                                     endif;
                                     
                                     if(!empty($job_spec->contact_state)):
                                     $contact_state = States::where('id', $job_spec->contact_state)->first();
                                     endif;
                                     
                                     
                                     Mail::send('emails.jobspec', ['name' => $rec_name['name'],'firstname'=>$send_name['name'],'data' => $insert_data,'job_spec'=>$job_spec,'industry_data'=>$industry_data,'roles_data'=>$roles_data,'country_name'=>$country_name,'contact_state'=>$contact_state,'contact_country'=>$contact_country,'state_name'=>$state_name], function($message)
					        use($rec_email){
					            $message->to($rec_email['email'], $rec_email['name'])->subject('Job Specification Form Details');       		
					        });
                                                
                                          if (view()->exists('Job.jobdesc')) {
                                              $job_desc= view('Job.jobdesc')->with(['name' => $rec_name['name'],'firstname'=>$send_name['name'],'data' => $insert_data,'job_spec'=>$job_spec,'industry_data'=>$industry_data,'roles_data'=>$roles_data,'country_name'=>$country_name,'contact_state'=>$contact_state,'contact_country'=>$contact_country,'state_name'=>$state_name]);
                                            }
                                            else
                                            {
                                                $job_desc="";
                                            }
                                     
                                     $store_msg = array(
							'receiver_profile_id' => $value,
							'sender_profile_id' => Auth::user()->id,
							'title' =>$job_spec->title,
							'msg_content' => $job_desc,
                                                        'message_type'=> 'JOBSPEC',
                                                        'created_at' => date('Y-m-d h:i:s')
						             );
                                    
                                     $insert_msg = Messages::create($store_msg);
                                     $last_id[]=$insert_msg->id;
                                     
                                     $insert_sen[] = array(
							'profile_id' => Auth::user()->id,
							'message_id' => $insert_msg->id,
							'folder' => 'S',
                                                        'created_at' => date('Y-m-d h:i:s')
						        );
                                     
                                     $insert_rec[] = array(
							'profile_id' => $value,
							'message_id' => $insert_msg->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);
                                
                             
				return redirect(Url('/search/'))->with('succ_msg',"Your Job Specification has been sent successfully");
			}	

			$jobs = JobSpecifications::where('profile_id', '=', $this->current_profile_id)->orderBy('id', 'desc')->get();
                        $profiles = Profile::whereRaw("id IN (".implode(',',$input['profileList']).")")->get();
		        return view('Job.job_list')->with(['share_inquire'=>$profiles,'private_type'=>$private_type,'jobspec'=>$jobs]);
		
                    }
                    else
                    {
                            return redirect(URL::previous())->with('error_msg',"Invalid To address");
                    }
	        }
                public function view_job(Request $request)
                {
                    $countries = Countries::orderBy('name')->get();
                    $industry_data = Industry::getList();
                    $roles_data = Roles::getList();
	            return View('Job.jobspec')->with(['countries'=>$countries,'industry_data'=>$industry_data,'roles_data'=>$roles_data]);
                }
                public function delete_job($msg_id)
                {
                    if(is_numeric($msg_id)):
			$msg_job_det = JobSpecifications::where('id',$msg_id)->first();
                
			if(isset($msg_job_det->id)):
				$msg_recruit_det = Recruitment::where('job_id',$msg_id)->first(); 
                                  $suc=$msg_recruit_det->delete();
                                  if($suc):
                                    $success=$msg_job_det->delete();   
                                  endif;
                               if($success):
				return redirect('jobspec/')->with('succ_msg',"Job Specification Deleted Successfully");
                               else:
                                 return redirect('jobspec/')->with('error_msg',"Invalid Request");  
                               endif;
			else:
				return redirect('jobspec/')->with('error_msg',"Invalid Request");
			endif;
		    endif;
                }
                 public function edit_job($msg_id,Request $request)
                {   
                    if(is_numeric($msg_id)):
                        $msg_job_det = JobSpecifications::where('id',$msg_id)->first();
                        if(isset($msg_job_det->id)):
                        $countries = Countries::orderBy('name')->get();
                        $industry_data = Industry::getList();
                        $roles_data = Roles::getList();
                        return View('Job.jobspec_edit')->with(['countries'=>$countries,'industry_data'=>$industry_data,'roles_data'=>$roles_data,'job_spec'=>$msg_job_det]); 
                        else:
                                   return redirect('jobspec/')->with('error_msg',"Invalid Request");  
                        endif;
                    else:
				return redirect('jobspec/')->with('error_msg',"Invalid Request");
	            endif;
                    
                }
                public function jobspec_add(Request $request)
                {  
                  
                   if($request->input('signup')=='insert')
                   {   
                    $rule  =  [
                    'title' => 'required',
                    'company_name' => 'required',
                    'link_to_website' => 'required',
                    'industry'=>'required',
                    'country'=>'required',
                    'province'=>'required',
                    'sal_range'=>'required',   
                    'username'=>'required',
                    'email'=>'required|email',
                    'contact_company'=>'required',
                     ];
                    
                      foreach(Input::get('skill_level') as $key => $val)
                    {
                      $rule['skill_level.'.$key] = 'required|min:1';
                    }
                   
                    $validator = Validator::make(Input::all(),$rule);
                    if ($validator->fails())
                     {
                        return Redirect::to('jobspec')
                            ->withErrors($validator->messages());
                     }
                    else
                     { 
                          if(Input::get('anonymous')==""):
                                $anonymous=0;
                          else: $anonymous=1;
                          endif;
                        $succ_msg="";$error_msg="";
                        if(Input::get('hide_sal')=="")$hide_sal=0;else $hide_sal=1;
                       $object= JobSpecifications::create([
                                    'profile_id' => $this->current_profile_id,
                                    'title' => trim(Input::get('title')),
                                    'company_name' => trim(Input::get('company_name')),
                                    'link_to_website' => trim(Input::get('link_to_website')),
                                    'website_link' => trim(Input::get('website_link')),
                                    'company_desc' => trim(Input::get('company_desc')),
                                    'position_desc' => trim(Input::get('position_desc')),
                                    'country' => trim(Input::get('country')),
                                    'province' => trim(Input::get('province')),
                                    'city' => trim(Input::get('city')),
                                    'sal_range' => trim(Input::get('sal_range')),
                                    'hide_sal' => trim($hide_sal),
                                    'additional_elements' => trim(Input::get('additional_elements')),
                                    'jobtype'=>Input::get('jobtype'),
                                    'experience'=>Input::get('experience'),
                                    'qualification'=>Input::get('qualification'),
                                    'anonymous'=>$anonymous,
                                    'contact_province'=>Input::get('contact_province'),
                                    'username'=>Input::get('username'),
                                    'zip'=>Input::get('zip'),
                                    'email'=>Input::get('email'),
                                    'phone'=>Input::get('phone'),
                                    'apply'=>Input::get('apply'),
                                    'fax'=>Input::get('fax'),
                                    'contact_company'=>Input::get('contact_company'),
                                    'comment'=>Input::get('comment'),
                                    'street'=>Input::get('street'),
                                    'contact_city'=>Input::get('contact_city'),
                                    'contact_country'=>Input::get('contact_country'),
                                    'contact_state'=>Input::get('contact_state'),
                                   ]);
                       $obj_id=$object->id;
                       
                        $skill_level = Input::get('skill_level');
                                $var="";
                                for($i=0;$i<count($skill_level);$i++):
                                    if(!empty($var)) $var=$var.','.$skill_level[$i];else $var=$skill_level[$i]; 
                                endfor;
                        $state = Input::get('state');
                                $stt=""; 
                                for($i=0;$i<count($state);$i++):
                                    if(!empty($stt)) $stt=$stt.','.$state[$i];else $stt=$state[$i]; 
                                endfor;
                           
                         $industry = Input::get('industry');
                        
                                $indu=""; 
                                for($i=0;$i<count($industry);$i++):
                                    if(!empty($indu)) $indu=$indu.','.$industry[$i];else $indu=$industry[$i]; 
                                endfor; 
                                
                           $function = Input::get('function');
                        
                                $fun=""; 
                                for($i=0;$i<count($function);$i++):
                                    if(!empty($fun)) $fun=$fun.','.$function[$i];else $fun=$function[$i]; 
                                endfor;
                                
                        $success=JobSpecifications::where('id', '=', $obj_id)->update(array('skill_level' => $var,'state' => $stt,'industry' => $indu,'function' => $fun));
                        
                       if($success):
                          $succ_msg="Job Specification Details Added Successfully"; 
                       else:
                           return redirect(URL::previous())->with('error_msg',"Invalid To address");
                       endif;
                        
                     }
                  }
                   if($request->input('signup')=='update')
                   {  
                        if(Input::get('anonymous')==""):
                                $anonymous=0;
                          else: $anonymous=1;
                          endif;  
                         $job_id=Input::get('job_id');
                          if(Input::get('hide_sal')=="")$hide_sal=0;else $hide_sal=1;
                         $update = JobSpecifications::where('id', '=', $job_id)->update(array('profile_id' => $this->current_profile_id,
                                    'title' => trim(Input::get('title')),
                                    'company_name' => trim(Input::get('company_name')),
                                    'link_to_website' => trim(Input::get('link_to_website')),
                                    'website_link' => trim(Input::get('website_link')),
                                    'company_desc' => trim(Input::get('company_desc')),
                                    'position_desc' => trim(Input::get('position_desc')),
                                    'country' => trim(Input::get('country')),
                                    'province' => trim(Input::get('province')),
                                    'city' => trim(Input::get('city')),
                                    'sal_range' => trim(Input::get('sal_range')),
                                    'hide_sal' => trim($hide_sal),
                                    'additional_elements' => trim(Input::get('additional_elements')),
                                    'jobtype'=>Input::get('jobtype'),
                                    'experience'=>Input::get('experience'),
                                    'qualification'=>Input::get('qualification'),
                                    'anonymous'=>$anonymous,
                                    'contact_province'=>Input::get('contact_province'),
                                    'username'=>Input::get('username'),
                                    'zip'=>Input::get('zip'),
                                    'email'=>Input::get('email'),
                                    'phone'=>Input::get('phone'),
                                    'apply'=>Input::get('apply'),
                                    'fax'=>Input::get('fax'),
                                    'contact_company'=>Input::get('contact_company'),
                                    'comment'=>Input::get('comment'),
                                    'street'=>Input::get('street'),
                                    'contact_city'=>Input::get('contact_city'),
                                    'contact_country'=>Input::get('contact_country'),
                                    'contact_state'=>Input::get('contact_state')));
                         $skill_level = Input::get('skill_level');
                                $var="";
                                for($i=0;$i<count($skill_level);$i++):
                                    if(!empty($var)) $var=$var.','.$skill_level[$i];else $var=$skill_level[$i]; 
                                endfor;
                         $state = Input::get('state');
                                $stt="";    
                                 
                                 for($i=0;$i<count($state);$i++):
                                    if(!empty($stt)) $stt=$stt.','.$state[$i];else $stt=$state[$i]; 
                                endfor;
                                
                        $industry = Input::get('industry');
                       
                                $indu=""; 
                                for($i=0;$i<count($industry);$i++):
                                    if(!empty($indu)) $indu=$indu.','.$industry[$i];else $indu=$industry[$i]; 
                                endfor;
                                
                         $function = Input::get('function');
                        
                                $fun=""; 
                                for($i=0;$i<count($function);$i++):
                                    if(!empty($fun)) $fun=$fun.','.$function[$i];else $fun=$function[$i]; 
                                endfor;
                                
                        $success=JobSpecifications::where('id', '=', $job_id)->update(array('skill_level' => $var,'state' => $stt,'industry' => $indu,'function' => $fun));
                          
                         if(isset($update)):
                             $succ_msg="Job Specification Details Updated Successfully"; 
                         else:
                             return redirect(URL::previous())->with('error_msg',"Invalid To address");
                         endif;
                    }
                  return redirect(Url('/jobspec'))->with('succ_msg',$succ_msg);
               }
          
}
