<?php
@session_start();
include_once("../class/class.MySQL.php");
require '../class/resizeImage.php';
include_once("showpath.php");
$db	=new MySQL();
$action = $_GET['action'];
//error_reporting(-1);
if($action == 'insert'){
	$data['e_id'] = $_POST['device_empid'];
	$data['device_id'] = $_POST['device']?implode(',',$_POST['device']):"";
	$data['e_fname'] = $_POST['name'];
	$data['e_mob'] = $_POST['phone'];
	$data['e_mail'] = $_POST['email'];
	$data['e_post'] = $_POST['designation'];
	$data['branchid'] = $_POST['branch'];
	$data['departid'] = $_POST['department'];
	$data['imd_supervisor_id'] = $_POST['imdatesupervisor'];
	$data['e_dstart'] = date("Y-m-d");
	$data['status'] = 1;
	$data['password'] = $_POST['password'];
	$data['e_gender'] = $_POST['gender'];
	$data['sel_candidate_id'] = $_POST['sel_id'];
	$data['emp_basic_pay'] = $_POST['emp_basic_pay'];
	$data['date_join'] = $_POST['dt_join'];
	
	
	if($_POST['department'] == 3){
		$data['user_type'] = 'SubadminHR';
	}else{
		$data['user_type'] = 'Subadmin';
	}
	
	if(isset($_POST['branch_admin'])){
		$data['branch_admin'] = 'Y';
	}else{
		$data['branch_admin'] = 'N';
	}

	$totalEmp = $db->CountRows("employee");
	
	$emp=array();
	
	if($totalEmp > 1000){
			$emp['error'] = "limit";
	}else{
	
	$db->Insert($data,'employee');
	$employeeId = $db->LastInsertID();
	
	
	
	
	
	
	/*if($data['e_post'] == 'Supplier'){
	
		$sup['name'] =$_POST['name'];
		$sup['contact'] =$_POST['phone'];
		
		$data->Insert($sup,'supplier');
	}
	
	*/
	$timedata['e_id'] = $employeeId;
	$db->Insert($timedata,'time');
	
	$supdata['name']  = htmlentities($_POST['name']);
	$supdata['contact']  = htmlentities($_POST['phone']);
	
	$username= str_replace(' ', '', $supdata['name']);
	$randumnumber = rand(1234, 9985);
		
	$supdata['username']	=mb_substr($username, 0, 5).$randumnumber;
	$supdata['passwd']		=mb_substr($username, 2, 4).$randumnumber;

	if($_POST['designation'] == 'Supplier'){
	
		$catname = $db->Insert($supdata,'1');
		$userid = $db->LastInsertID();
		
		$userdata['type']		= '1';

	}elseif($_POST['designation'] == '3' ){
		$userdata['type']		= '3'; // cook / chef
	}
	
	$designation = $db->fetchQuery("SELECT * FROM designation WHERE desig_id = '".$_POST['designation']."'");
	
	foreach($designation as $designation){
		$designation= $designation['type'];
	}
	
	
	$empdata['username']	=	$supdata['username'];
	//$empdata['password']	=	$supdata['passwd'];
	$empwhere['e_id']		= $employeeId ;
	$db->Update('employee',$empdata,$empwhere);
	
	# send username and password 
	
	$to      = $_POST['email'];
	$subject = 'Login Details';
	$message = 'Dear '.$_POST['name']. "\r\n".'
	 You have successfully created as a user of HRM'. "\r\n".'
	 Username:'.$empdata['username']. "\r\n".'Password:'.$_POST['password']. "\r\n".
	'Please click on this link to login http://'.BASEPATH;
	$headers = 'From: info@addhrm.com' . "\r\n" ;
	mail($to, $subject, $message, $headers);
	
	$userdata['userid']		= $employeeId;
	$userdata['username']	= mb_substr($username, 0, 5).$randumnumber;
	$userdata['password']	= md5(mb_substr($username, 2, 4).$randumnumber);	
	$userdata['type']		= $designation;
	
	//$userdata['type']		= '1';
	
	
	$tabuser = $db->Insert($userdata,'tab_user');
	
	$experienceinsert['e_id']=$employeeId ;
	$db->Insert($experienceinsert,'employee_expirence');
	
	$dataprofile['photo']		= 'noimg.jpg';
	$dataprofile['e_id']		= $employeeId;
	$db->Insert($dataprofile,'file');
	
	$idprofile['filetype']		= '';
	$idprofile['file']		= '';
	$idprofile['e_id']		= $employeeId;
	$db->Insert($idprofile,'idproof');
	
		$emp['eid'] = $employeeId;
		
	
	
	  $deisgss =  mysql_fetch_array(mysql_query("SELECT * FROM designation where desig_id = '".$_POST['designation']."'"));
	  
	 $thePostIdArray = explode(',', $deisgss['desig_rights']);
	 
	 foreach($thePostIdArray as $user_right){
	


    $datam['user_id'] = $employeeId;
	$datam['m_menu_id'] = $user_right;
	/*$data['s_submenu_id'] = $_POST['chkadd'.$cntid];*/
	$datam['add_right'] = 1;
	$datam['edit_right'] = 1;
	$datam['view_right'] = 1;
	$datam['delete_right'] = 1;
	


	$db->Insert($datam,'tbl_user_rights');
	
	$sub_menuss =  mysql_query("SELECT * FROM menu_sub where menu_id = '".$user_right."'");
	while($sub_m_id=mysql_fetch_array($sub_menuss))
	 {
	      $datas['user_id'] = $employeeId;
	      $datas['m_menu_id'] = $user_right;
	      $datas['s_submenu_id'] = $sub_m_id['s_id'];
	      $datas['add_right'] = 1;
	      $datas['edit_right'] = 1;
	      $datas['view_right'] = 1;
	      $datas['delete_right'] = 1;
		  $db->Insert($datas,'tbl_user_rights');
	 }
	 
	
	     }
		
	}
	
	echo json_encode($emp);
	
}elseif($action =="updatebankdetails"){

	$set['e_account']		= $_POST['accountname'];
	$set['e_bank']			= $_POST['bankname'];
	$set['e_accountno']		= $_POST['accountno'];
	$set['e_bankadd']		= $_POST['bankaddress'];
	$set['e_code']			= $_POST['ifsccode'];
	//print_r($set); exit(); 
	$where['e_id']			= $_POST['employee_id'];
	$db->Update('employee',$set,$where);
	
}elseif($action =="updateprofile"){

	$set['e_fname']		= $_POST['f_name'];
	$set['username']		= $_POST['empuser_name'];
	$set['password']		= $_POST['emppassword'];
	$set['e_mname']			= $_POST['m_name'];
	$set['e_lname']		= $_POST['l_name'];
	$set['e_mail']		= $_POST['e_mail'];
	$set['e_mob']			= $_POST['mobile_no'];
	$set['e_phone']			= $_POST['phone_no'];
	$where['e_id']			= $_POST['e_id'];
	
	$db->Update('employee',$set,$where);
	
}elseif($action =="newbasicdetails"){


	$set['branchid']		= $_POST['branch'];
	$set['departid']		= $_POST['department'];
	$set['e_post']		= $_POST['designation'];
	$set['imd_supervisor_id']			= $_POST['imdatesupervisor'];
	if($_POST['branch_admin']=='on'){
		$set['branch_admin'] = 'Y';
	}else{
		$set['branch_admin'] = 'N';
	}
	
	$where['e_id']			= $_GET['empid'];
	
	$db->Update('employee',$set,$where);
	
	if($_GET['old_del'])
	{
		$eids= $_GET['empid'];
	$userdetails = $db->fetchQuery("SELECT * FROM salary_structure_employee where employee_id='$eids'");
	$st_id=$userdetails[0]['salary_structure_id'];
	
	
	$wheres['employee_id']			= $_GET['empid'];
	
	$deductions = $db->Delete('salary_structure_employee',$wheres);
	
		$wherer['structure_id']			= $st_id;
	
	$deductions = $db->Delete('salary_structure',$wherer);
	
	}
	
	
	
}elseif($action =="updateimage"){

	if(isset($_FILES['profileimage']['name'])){
	
		$randnum		=rand(1200,9999);
		$image			=$randnum.$_FILES['profileimage']['name'];
		$data['image']		=$image;
		$paththumb= "../upload/fullsize/".$randnum.$_FILES['profileimage']['name'];
		// move_uploaded_file($_FILES["profileimage"]["tmp_name"],$paththumb);
		 
		 $image1 = new ImageResize($_FILES['profileimage']['tmp_name']);
				$image1->resizeToWidth(500);
				$image1->save($paththumb);
		 
		 echo "http://localhost/HRMK/upload/fullsize/".$image;
		/*	try {
		
					$image = new ImageResize($_FILES['profileimage']['tmp_name']);
					
					//// Save thumb
					$image->resize(230,110);
					$image->save($paththumb);
					
	
			} catch (Exception $e) {
			}*/
		}
}elseif($action =="cropimage"){
	
	$file 		= $_POST['fileurl'];
	$cropx 		= $_POST['cropx'];
	$cropy 		= $_POST['cropy'];
	//$imgwidth 	= $_POST['imgwidth'];
	//$imgheight 	= $_POST['imgheight'];
	$zoomimgwidth 	= $_POST['zoomwidth'];
	$zoomheight 	= $_POST['zoomheight'];
	
	
	$x 	= $_POST['x'];
	$x 	= $_POST['y'];
	$w 	= $_POST['w'];
	$h 	= $_POST['h'];
	
	
	
	
	$filename = explode("/fullsize/",$file);
	$filename = $filename[1];
	$paththumb= "../upload/fullsize/12_".$filename;

	$targ_w =170;
	$targ_h = 172;
	$jpeg_quality = 100;

	$src ="../upload/fullsize/".$filename;
	
//	list($width, $height) = getimagesize($src);
//	echo $width.','.$height;
	//echo "<br/>".$imgwidth  = ($width/$zoomimgwidth)*170*1.025;
	//echo "<br/>".$imgheight = ($height/$zoomheight)*172*1.025;
	
	
	
	
	// $imgwidth."-".$imgheight."@@". 170/$width*$zoomimgwidth;
	
	$img_r = imagecreatefromjpeg($src);
	$dst_r = imagecreatetruecolor( $targ_w, $targ_h);

	imagecopyresampled( $dst_r,$img_r,0,0,$x,$y,$targ_w,$targ_h,$w,$h);
//	imagecopyresampled($dst_r,$img_r,0,0,$_POST['cropx'],$_POST['cropy'],
//	$targ_w,$targ_h,$_POST['imgwidth'],$_POST['imgheight']);
	//imagecopyresampled(
	//header('Content-type: image/jpeg');
	//imagejpeg($dst_r,null,$jpeg_quality);
	imagejpeg($dst_r, $paththumb);



}elseif($action == "employeeslist"){

	$employeelist = $db->fetchAll('employee');
	echo '{"employees":'.json_encode($employeelist).'}';

}elseif($action == "updateReferance"){
	$set['e_rname']			= $_POST['referanceName'];
	$set['e_relation']		= $_POST['referanceRelation'];
	$set['e_contact']		= $_POST['referanceContact'];
	$set['e_rlocation']		= $_POST['referanceloc'];
	$where['e_id']			= $_GET['empid'];
	$db->Update('employee',$set,$where);
}

elseif($action == "updateDetails"){
	/*$set['employee_id']		= $_POST['emp_ids'];
	$set['date_join']		= $_POST['dat_join'];
	$set['blood_group']		= $_POST['blood_grp'];
	$set['pf_accnum']		= $_POST['pfac_num'];	
	$set['pf_nominee']		= $_POST['pf_nominee'];
	$set['esi_details']		= $_POST['esi_details'];
	
	$set['hist_dt_join']		= $_POST['histdt_join'];
	$set['hist_emptype']		= $_POST['emp_type'];
	$set['hist_dt_prev_pay']	= $_POST['dt_prev'];
	$set['hist_dt_pay']			= $_POST['dt_pay'];
	$set['hist_comp_prob']		= $_POST['comp_prob'];*/
	
	$set['e_dob']		= $_POST['emp_dob'];
	$set['e_gender']		= $_POST['emp_gender'];
	$set['e_mail']		= $_POST['emp_email'];
	$set['e_phone']		= $_POST['emp_phn'];	
	$set['employee_id']		= $_POST['emp_ids'];
	$set['hist_dt_join']		= $_POST['histdt_join'];
	
	$set['date_join']		= $_POST['dat_join'];
	$set['hist_date_releve']		= date('Y-m-d',strtotime($_POST['emp_date_rel']));
	$set['blood_group']	= $_POST['blood_grp'];
	$set['hist_pre_desig']			= $_POST['last_desg'];
	$set['esi_details']		= $_POST['esi_details'];
	$set['hist_emp_num']		= $_POST['emp_num'];
	if(isset($_POST['branch_admin'])){
		$set['branch_admin'] = 'Y';
	}else{
		$set['branch_admin'] = 'N';
	}
	
	
	$where['e_id']			= $_GET['empid'];
	$db->Update('employee',$set,$where);
}

elseif($action == "newexperiance"){
	
	$vars['e_id']		= $_GET['empid'];
	$vars['refer']		= $_POST['companyName'];
	$vars['emp']		= $_POST['companyAddress'];
	$vars['phno']		= $_POST['companyPhone'];
	$vars['email']		= $_POST['companyEmail'];
	$vars['from']		= $_POST['workFrom'];
	$vars['to']			= $_POST['workTo'];
	$vars['posi']		= $_POST['companyPosition'];
	$vars['sal']		= $_POST['companySalary'];
	$vars['rfl']		= $_POST['reasontoLeave'];
	
	
	
	$db->Insert($vars,'employee_expirence');
	
}

elseif($action == "rm_passport"){

	$emp_id		 	= $_GET['employ_id'];
	#get file name
	$employ   	    = $db->fetchQuery("Select passport_doc from employee where employee.e_id='".$emp_id."'");
	$passport       = $employ[0]['passport_doc'];						
	#unlink file
	$pathpassport   = "../upload/documents/".$passport;
	unlink($pathpassport);
	
	#updating passport doc field for removing document
	$cond['e_id']		 = $_GET['employ_id'];
	$set['passport_doc'] = "";
	$db->Update('employee',$set,$cond);
	
}

elseif($action == "rm_visa"){

	$emp_id	 	= $_GET['employ_id'];
	#get file name
	$employ   	= $db->fetchQuery("Select visa_doc from employee where employee.e_id='".$emp_id."'");
	$visa 		= $employ[0]['visa_doc'];						
	#unlink file
	$pathvisa   = "../upload/documents/".$visa;
	unlink($pathvisa);
	
	#updating passport doc field for removing document
	$cond1['e_id']		 = $_GET['employ_id'];
	$set['visa_doc'] = "";
	$db->Update('employee',$set,$cond1);
	
}
#remove empoye document
elseif($action == "rm_emp_doc"){

	$emp_doc_id	 	= $_GET['emp_doc_id'];
	#get file name
	$employ   	= $db->fetchQuery("Select doc from emp_documents where emp_doc_id='".$emp_doc_id."'");
	$doc 		= $employ[0]['doc'];						
	#unlink file
	$pathdoc   = "../upload/documents/".$doc;
	unlink($pathdoc);
	
	#updating passport doc field for removing document
	$cond2['emp_doc_id']	= $emp_doc_id;
	$db->Delete('emp_documents',$cond2);
	
}

#remove employee doc file
elseif($action == "rm_doc_file"){

	$emp_doc_id	 	= $_GET['emp_doc_id'];
	#get file name
	$employ   	= $db->fetchQuery("Select doc from emp_documents where emp_doc_id='".$emp_doc_id."'");
	$doc 		= $employ[0]['doc'];					
	#unlink file
	$pathdoc   = "../upload/documents/".$doc;
	unlink($pathdoc);
	
	#updating passport doc field for removing document
	$cond3['emp_doc_id']	= $emp_doc_id;
	$set['doc'] 			= "";
	$db->Update('emp_documents',$set,$cond3);
	
}

#change password
elseif($action == "change_password"){
	
	$e_id				= $_GET['empid'];	
	#get old password 
	$employ   			= $db->fetchQuery("Select password,e_mail,e_fname,e_mname,e_lname from employee where e_id='".$e_id."'");
	$password 			= $employ[0]['password']?$employ[0]['password']:"";
	
		$upd['password']	= $_POST['new_pass'];
		$cond4['e_id']		= $e_id;
		$db->Update('employee',$upd,$cond4);
		# send  password 
	
		$to      = $employ[0]['e_mail'];
		$subject = 'Change password';
		$message = 'Dear '.$employ[0]['e_fname']." ".$employ[0]['e_mname']." ".$employ[0]['e_lname']. ",\r\n".'
		 Your HRM password has been changed'. "\r\n".
		 'Username:'.$employ[0]['username']."\r\n".
		 'New Password:'.$_POST['new_pass']. "\r\n".
		'Please click on this link to login http://'.BASEPATH;
		$headers = 'From: info@addhrm.com' . "\r\n" ;
		mail($to, $subject, $message, $headers);
	
	
}
elseif($action=="joindate")
{
	$e_id				= $_GET['employees'];
	$dat_srch			= 	$_GET['year'].'-'.$_GET['month'].'-'.'01';
	#get file name
	//$employ   	     = $db->fetchQuery("Select date_join from employee where e_id='".$e_id."' AND month(STR_TO_DATE(date_join, '%d-%m-%Y')) <= '".$_GET['month']."' AND year(STR_TO_DATE(date_join, '%d-%m-%Y')) <= '".$_GET['year']."'");
	//echo "Select date_join from employee where e_id='".$e_id."' AND month(STR_TO_DATE(date_join, '%d-%m-%Y')) <= '".$_GET['month']."' AND year(STR_TO_DATE(date_join, '%d-%m-%Y')) <= '".$_GET['year']."'";
	$employ   	     = $db->fetchQuery("SELECT date_join FROM employee WHERE e_id = '".$e_id."' AND DATE( STR_TO_DATE( date_join,  '%d-%m-%Y' ) ) <=  NOW()");
	if(!empty($employ))
	{
	$date_join 		 = $employ[0]['date_join'];
	}
	else
	{
	$date_join 		 = '';
	}
	
	$sub_rights=mysql_fetch_array(mysql_query("select * from menu as m,menu_sub as s where  s.s_menu_name='Timesheet_show' and m.menu_id=s.menu_id "));
	
	$userid=$_SESSION['admin_id'];

	$where['user_id']	= $userid;
	$where['s_submenu_id']	= $sub_rights['s_id'];
	
	$m_rights=mysql_fetch_array(mysql_query("select * from tbl_user_rights where  user_id='$userid' and s_submenu_id='$sub_rights[s_id]'"));
	
	
	if($userid!=1)
	{
	if($m_rights['view_right']==0)
 {
 $date_join='<font color="red" size="3"><b>Sorry You Do Not Have Enough Permission To View This Form....</b></font>';
 }
   }
	
	echo $date_join;	
	
}
elseif($action=="empname"){ 
		   if($_SESSION['usertype']=='Superadmin') 
		   {
		
		
		
			   $sqlemp = $db->fetchQuery("select * from employee where status = 1 and user_type!='Superadmin' and emp_status NOT IN(2,3) order by e_fname asc");  
			   $str  = '<option value="">-Select-</option>';
			   foreach($sqlemp as $list){                            
				$str  .= '<option value="'.$list['e_id'].'">'.$list['e_fname'].'</option>';
			   }
				$str   .= '</select>';
		   
		   }
		   elseif($_SESSION['branchadmin']=='Y')
		   {
		   	 	$sqlemp = $db->fetchQuery("select * from employee where status = 1 and user_type!='Superadmin' and  emp_status NOT IN(2,3) and branchid=".$_SESSION['branch_id']." order by e_fname asc");  
			   $str  = '<option value="">-Select-</option>';
			   foreach($sqlemp as $list){                            
				$str  .= '<option value="'.$list['e_id'].'">'.$list['e_fname'].'</option>';
			   }
				$str   .= '</select>';
		   }
		   else
		   {
		  
		   $emp_hid_id=$_SESSION['admin_id'];
		   $sqlemp = $db->fetchQuery("select * from employee where status = 1 and e_id=$emp_hid_id order by e_fname asc");
		   $str  = '';
		   foreach($sqlemp as $list){                          
		   $str  .= '<option value="'.$list['e_id'].'">'.$list['e_fname'].'</option>';
		   } 
		   $str   .= '</select>';
		   }
		   
		   echo $str ;
		   
}
else if($action =="checkemployeeid"){
	$eids 		 = $_POST['device_empid'];
	$userdetails = $db->fetchQuery("SELECT count(e_id) as cnt FROM employee where e_id='$eids'");
	$cnt		 = $userdetails[0]['cnt'];
	if($cnt>0){
		echo 'false';
	}else {
		echo 'true';
	}
}
?>