<?php
/****************************************
/*  Author 	: Kvvaradha
/*  Module 	: Extended HRM
/*  E-mail 	: admin@kvcodes.com
/*  Version : 1.0
/*  Http 	: www.kvcodes.com
*****************************************/
$page_security = 'HR_EMPL_INFO';
$path_to_root = "../../..";
include($path_to_root . "/includes/session.inc");
add_access_extensions();

include($path_to_root . "/modules/ExtendedHRM/includes/Payroll.inc" );
include($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/includes/data_checks.inc");
include_once($path_to_root . "/modules/ExtendedHRM/includes/db/custom_fields_db.inc");
include_once($path_to_root . "/modules/ExtendedHRM/includes/ui/custom_fields_ui.inc");
include($path_to_root . "/modules/ExtendedHRM/includes/db/picklist.inc" );
include_once($path_to_root. "/admin/db/users_db.inc");

if (isset($_GET['vw']))
	$view_id = $_GET['vw'];
else
	$view_id = find_submit('view');
if ($view_id != -1){	//echo $view_id;
	$row = GetRow('kv_empl_license', array('id' => $view_id));
	if ($row['unique_name'] != ""){
		if(in_ajax()) {
			$Ajax->popup($_SERVER['PHP_SELF'].'?vw='.$view_id);
		} else {
			$type = ($row['filetype']) ? $row['filetype'] : 'application/octet-stream';	
    		header("Content-type: ".$type);
    		header('Content-Length: '.$row['filesize']);
 			header("Content-Disposition: inline");
 			//display_error( company_path(). "/attachments/empldocs/".$row['unique_name']);
	    	echo file_get_contents(company_path(). "/attachments/licenses/".$row['unique_name']);
    		exit();
		}
	}	
}
if (isset($_GET['dl']))
	$download_id = $_GET['dl'];
else
	$download_id = find_submit('download');

if ($download_id != -1){
	$row = GetRow('kv_empl_cv', array('id' => $download_id));
	if ($row['unique_name'] != ""){
		if(in_ajax()) {
			$Ajax->redirect($_SERVER['PHP_SELF'].'?dl='.$download_id);
		} else {
			
    		header("Content-type: 'application/octet-stream' ");
	    	//header('Content-Length: '.$row['filesize']);
    		header('Content-Disposition: attachment; filename='.$row['filename']);
    		echo file_get_contents(company_path()."/attachments/empldocs/".$row['unique_name']);
	    	exit();
		}
	}	
}

$version_id = get_company_prefs('version_id');

$js = '';
if($version_id['version_id'] == '2.4.1'){
	if ($SysPrefs->use_popup_windows) 
		$js .= get_js_open_window(900, 500);	

	if (user_use_date_picker()) 
		$js .= get_js_date_picker();
	
}else{
	if ($use_popup_windows)
		$js .= get_js_open_window(900, 500);
	if ($use_date_picker)
		$js .= get_js_date_picker();
}

page(_("Employees"), @$_REQUEST['popup'], false, "", $js);
echo '<script language="javascript" type="text/javascript" src="'.$path_to_root.'/modules/ExtendedHRM/js/nicEdit-latest.js"></script>';
if(kv_check_payroll_table_exist()){}else {
	display_error(_("There are no Allowance defined in this system. Kindly Setup")." <a href='".$path_to_root."/modules/ExtendedHRM/manage/allowances.php' target='_blank'>"._("Allowances")."</a> "._("Your Allowances."));
	end_page();
    exit;
}
if(db_has_gross_pay()){ } else{
	display_error(_("Gross Pay is not Setup in the system. Kindly Setup")." <a href='".$path_to_root."/modules/ExtendedHRM/manage/allowances.php' target='_blank'>"._('Gross Pay')."</a> here.");
	end_page();
    exit;
}
// if(db_has_basic_pay()){ } else{
// 	display_error(_("Basic Pay is not Setup in the system. Kindly Setup")." <a href='".$path_to_root."/modules/ExtendedHRM/manage/allowances.php' target='_blank'>"._('Basic Pay')."</a> here.");
// 	end_page();
//     exit;
// }
/*if(db_has_tax_pay()){ } else{
	display_error(_("Tax is not Setup in the system. Kindly Setup") <a href='".$path_to_root."/modules/ExtendedHRM/manage/allowances.php' target='_blank'>Tax </a> here.");
	end_page();
    exit;
}
*/
check_db_has_Departments(_("There is no Department in the system to add employees. Please Add some")." <a href='".$path_to_root."/modules/ExtendedHRM/manage/department.php' target='_blank'>"._("Department")."</a> ");

$new_item = get_post('empl_id')=='' || get_post('cancel') || get_post('clone'); 
//------------------------------------------------------------------------------------

if (isset($_GET['empl_id']))
{
	$_POST['empl_id'] = $_GET['empl_id'];
}
if(list_updated('dept_id'))
	$Ajax->activate('empl_id');
if (list_updated('empl_id')) {
	$empl_id = get_post('empl_id');
    clear_data();
   $_POST['empl_id'] = $_POST['employee_id'] = $empl_id;
	$Ajax->activate('details');
	$Ajax->activate('controls');
	$Ajax->activate('profile');
}
$empl_id = get_post('empl_id');
if (get_post('cancel')) {
	$_POST['employee_id'] = $empl_id = $_POST['empl_id'] = '';
    clear_data();
	set_focus('empl_id');
	$Ajax->activate('_page_body');
}
if(isset($_GET['Added']) && $_GET['Added'] == 'yes')
	display_notification(_("A new Employee has been added."));
elseif(isset($_GET['Updated']) && $_GET['Updated'] == 'yes')
	display_notification(_("The Selected Employee Information has been Updated."));
$basic_id = kv_get_basic();

if(get_hrm_option('enable_pf')) {
	$pf_sql = "SELECT amt_limit FROM ".TB_PREF."kv_empl_esic_pf WHERE date = (SELECT MAX(date) FROM ".TB_PREF."kv_empl_esic_pf WHERE allowance_id='pf' LIMIT 0, 1) AND allowance_id = 'pf'"; 
	$pf_result = db_query($pf_sql, _("Can't get esic amount"));
	if($pf_row =  db_fetch_assoc($pf_result)){
		$pf_basic_pay =  $pf_row['amt_limit'];
	}else{
		display_warning(_("No PF Limit set. Please set it under HRM-> ESIC PF Settngs"));
	}		
}else 
	$pf_basic_pay = 0;

if(get_hrm_option('enable_esic')) {
	$pf_sql = "SELECT amt_limit FROM ".TB_PREF."kv_empl_esic_pf WHERE date = (SELECT MAX(date) FROM ".TB_PREF."kv_empl_esic_pf WHERE allowance_id='esic' LIMIT 0, 1) AND allowance_id = 'esic'"; 
	$pf_result = db_query($pf_sql, _("Can't get esic amount"));
	if($pf_row =  db_fetch_assoc($pf_result)){
		$esic_gross_pay =  $pf_row['amt_limit'];
	}else{
		display_warning(_("No ESIC Limit set. Please set it under HRM-> ESIC PF Settngs"));
	}		
}else 
	$esic_gross_pay = 0;

// if((get_post('RefreshInquiry')|| get_post('gross')) && (get_post('grade_id') == '' || get_post('grade_id') == 0 )) {
if(get_post('RefreshInquiry')|| (get_post('gross') && (get_post('grade_id') == '' || get_post('grade_id') == 0 ))) {
	$_POST['grade_id'] = GetSalaryGrade(input_num('gross')*12);	
	$Ajax->activate('payroll_tbl');
}
if((list_updated('grade_id') || get_post('RefreshInquiry')|| get_post('gross')) && (!isset($_POST['addupdate']) && input_num('gross') > 0 && $_POST['_tabs_sel'] == 'personal')) {
	if(get_post('empl_id')) {
		$empl_type = GetSingleValue('kv_empl_job', 'empl_type', ['empl_id' => $_POST['empl_id']]);
	} else {
		$empl_type = $_POST['empl_type'];
	}
		$Allowance = get_allowances(null, null, null, null, 0, get_post('grade_id'));
		$KVAllowance = kv_get_allowances(null, 0, get_post('grade_id'));
		$allowance_var_ar = array();
		$basic_id = 0;
		foreach($KVAllowance as $single) {
			$allowance_var_ar[$single['id']] = '{$'.$single['unique_name'].'}';			
			$_POST['E_'.$single['id']] = 0;	
			if($single['basic'] == 1)
				$basic_id = $single['id'];		
		}
		while ($single = db_fetch($Allowance)) {			
			if($single['formula'] == '' && $single['value'] == 'Percentage' && $single['percentage']>0){			
				$_POST['E_'.$single['id']] = input_num('E_'.$basic_id)*($single['percentage']/100);
			}elseif($single['value'] == 'Gross Percentage' && $single['percentage']>0){			
				$_POST['E_'.$single['id']] = input_num('gross')*($single['percentage']/100);
			}elseif($single['formula'] != '' && is_numeric($single['formula'])) {
				$_POST['E_'.$single['id']] = $single['formula'];					
			} elseif($single['value'] == 'Formula' && $single['formula'] != '' && !is_numeric($single['formula']) && (strpos($single['formula'], '{$ctc}') === false)){
				if($single['pf'] == 1 ){
					foreach($allowance_var_ar as $key => $allown){						
						if($key == $basic_id && input_num('E_'.$key) > $pf_basic_pay){	
							$allowance_amt = $pf_basic_pay;		
							$single['formula'] = str_replace($allown, $allowance_amt,strtolower($single['formula']));					
						}
						else{
							$allowance_amt =(isset($_POST['E_'.$key]) ? input_num('E_'.$key) : 0);
							$single['formula'] = str_replace($allown, $allowance_amt,strtolower($single['formula']));
						}
					}					
				}else {
					foreach($allowance_var_ar as $key => $allown){
						$single['formula'] = str_replace($allown, (isset($_POST['E_'.$key]) ? input_num('E_'.$key) : ''),strtolower($single['formula']));
					}
				}
				if(strpos($single['formula'], '{$gros}'))
						$single['formula'] = str_replace('{$gros}', (isset($_POST['gross']) ? input_num('gross') : 0 ), strtolower($single['formula']));

				if(strpos($single['formula'], '{$grlp}'))
						$single['formula'] = str_replace('{$grlp}', (isset($_POST['gross']) ? input_num('gross') : 0 ), strtolower($single['formula']));
                //display_error(calculate_string($single['formula']));
				$_POST['E_'.$single['id']] = round(calculate_string($single['formula']),2);
				if($single['esic'] == 1 ){					
					if(input_num('gross') > $esic_gross_pay)
						$_POST['E_'.$single['id']] = 0;
					
				}
			}elseif($single['value'] == 'Function') {
				if(function_exists($single['formula'])){
					$res = $single['formula']($single['id'], $_POST, $KVAllowance, (isset($_POST['employee_id']) ? $_POST['employee_id'] : '' ), 0 );
					if(is_numeric($res))
						$_POST['E_'.$single['id']] = $res;					
				} 
			}

			if($single['Tax'] && ($empl_type == 1 || $empl_type == 3)){
				$year = get_company_pref('f_year');
				$_POST['E_'.$single['id']] = kv_get_tax_for_an_employee($single['id'], $_POST['empl_id'], $year, input_num('gross'), date('m'));	
			}	
			if(($empl_type != 1 && $empl_type != 3) && ($single['esic'] == 1 || $single['pf'] == 1 || $single['Tax'] == 1)){
				$_POST['E_'.$single['id']] = 0;
			}
		}		
		$Ajax->activate('payroll_tbl');
}

if (get_post('cancel')) {
	$_POST['empl_id'] = $empl_id = $_POST['empl_id'] = '';
    clear_data();
	set_focus('empl_id');
	$Ajax->activate('_page_body');
}
if (list_updated('category_id') || list_updated('mb_flag') || list_updated('date_of_birth')) {
	$Ajax->activate('details');
}

if (list_updated('mod_of_pay')) {
	$Ajax->activate('payroll_tbl');
}

function clear_data(){
	unset($_POST['empl_id']);
	unset($_POST['empl_salutation']); 
	unset($_POST['empl_firstname']); 
	unset($_POST['empl_lastname']); 
	unset($_POST['addr_line1']); 
	unset($_POST['addr_line2']); 
	unset($_POST['address2']); 
	unset($_POST['empl_city']); 
	unset($_POST['empl_state']); 
	unset($_POST['gender']); 
	unset($_POST['date_of_birth']); 
	unset($_POST['age']);  
	unset($_POST['marital_status']); 
	unset($_POST['home_phone']);	
	unset($_POST['mobile_phone']);  
	unset($_POST['email']);  
	unset($_POST['status']); 
	unset($_POST['del_image']); 
	unset($_POST['pic']);
	unset($_POST['ice_name']); 
	unset($_POST['ice_phone_no']);  
}

function validate_mobile($mobile){
    return preg_match('/^[0-9]{10}+$/', $mobile);
}

//------------------------------------------------------------------------------------
$upload_file = "";
if (isset($_POST['addupdate'])) {
		
	$input_error = 0;
	if ($upload_file == 'No')
		$input_error = 1;
/*	if (!validate_mobile($_POST['mobile_phone'])) {
		display_error(_("The Employee mobile number is not valid one.").$_POST['gross']);
		set_focus('mobile_phone');
		return false;
	}*/

	if (strlen($_POST['employee_id']) == 0) {
		display_error(_("The employee Id Can't be empty."));
		set_focus('employee_id');
		return false;
	} 
/*	if (!isset($_POST['weekly_off']) ) {
		display_error(_("The employee doesn't have any weekly off day"));
		set_focus('weekly_off');
		return false;
	} 
	if (count($_POST['weekly_off']) == 0 ) {
		display_error(_("The employee doesn't have any weekly off day"));
		set_focus('weekly_off');
		return false;
	} */
	if($new_item && ctype_alnum($_POST['employee_id']) == false){
		display_error(_("The employee Id must be Combinations of Letters and Numbers, Not symbols."));
		set_focus('employee_id');
		return false;	
	}
	/*if ($new_item && db_has_selected_employee($_POST['empl_id']) !=null ) {
		display_error(_("The employee Id Already Exist."));
		set_focus('empl_id');
		return false;
	} */
	if (strlen($_POST['empl_firstname']) == 0) {
		display_error(_("The employee name cannot be empty."));
		set_focus('empl_firstname');
		return false;
	} 
	
	if (strlen($_POST['mobile_phone']) == 0) {
		display_error(_("The employee mobile number Can't be empty."));
		set_focus('mobile_phone');
		return false;
	}
	if (strlen($_POST['ice_name']) == 0) {
		display_error(_("The Emergency Contact name cannot be empty."));
		set_focus('ice_name');
		return false;
	} 
	
	if (strlen($_POST['ice_phone_no']) == 0) {
		display_error(_("The Emergency Contact mobile number Can't be empty."));
		set_focus('ice_phone_no');
		return false;
	}
	/*if ($new_item &&strlen($_POST['aadhar']) == 0) {
		display_error(_("The employee Aadhar Number Can't be empty."));
		set_focus('aadhar');
		return false;
	}
	if ($new_item &&strlen($_POST['aadhar']) >12) {
		display_error(_("The employee Aadhar Number in not valid."));
		set_focus('aadhar');
		return false;
	}*/
	/*if ($new_item &&strlen($_POST['ESIC']) == 0) {
		display_error(_("The employee ESIC number Can't be empty."));
		set_focus('ESIC');
		return false;
	}
	if ($new_item &&strlen($_POST['PF']) == 0) {
		display_error(_("The employee PF number Can't be empty."));
		set_focus('PF');
		return false;
	}*/
	/*if ($new_item &&strlen($_POST['PAN']) == 0) {
		display_error(_("The employee PAN Card number Can't be empty."));
		set_focus('PAN');
		return false;
	}*/
	if($_POST['employee_id'] == $_POST['report_to']){
		display_error(_("The report to Can't be same employee."));
		set_focus('report_to');
		return false;
	}

	/*if(!preg_match('/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/', $_POST['mobile_phone']))
    {
     display_error(_("The employee mobile number Can't be Invalid."));
		set_focus('mobile_phone');
		return false;
    } */
    if ($new_item && db_has_employee_email($_POST['email'])) {
		display_error(_("The E-mail already in Use."));
		set_focus('email');
		return false;
	} 

	if (isset($_POST['email']) && strlen(trim($_POST['email']))>0 && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === true) {
		display_error(_("The Entered E-Mail is not Valid."));
		set_focus('basic');
		return false;
	}

	if($new_item &&  date2sql($_POST['joining']) > date('Y-m-d')){
		display_error(_("Invalid Joining Date for the Employee."));
		set_focus('joining');
		return false;
	}
	/*if(strlen($_POST['age']) >2 || !check_num('age', 0)){
		display_error(_("The entered age is invalid."));
		set_focus('age');
		return false;
	}	*/
	
	 if ($new_item){
		$joining = new DateTime(date2sql($_POST['joining']));
		$dob = new DateTime(date2sql($_POST['date_of_birth']));

		$diff = $dob->diff($joining);

	 	if($diff->y < 18){
	 		display_error(_("The employee Date of Birth is not valid one."));
			set_focus('date_of_birth');
			return false;
	 	}
	 }
	
	if (!isset($_POST['empl_id']) && (!isset($_POST['weekly_off']) || count($_POST['weekly_off']) == 0)) {
		display_error(_("The employee weeky off Can't be empty."));
		set_focus('weekly_off');
		return false; 
	} 

	if (isset($_POST['role']) && strlen($_POST['role']) == 0 && isset($_POST['user_id']) && $_POST['user_id'] <= 0) {
		display_error(_("The Access role Can't be empty."));
		set_focus('role');
		return false;
	} 
 /*
	if ($new_item && strlen($_POST['empl_da']) == 0) {
		display_error(_("The employee DA Can't be empty."));
		set_focus('empl_da');
		return false;
	} 
	if ($new_item && strlen($_POST['empl_hra']) == 0) {
		display_error(_("The employee HRA Can't be empty."));
		set_focus('empl_hra');
		return false;
	} 

	if ($new_item && strlen($_POST['conveyance']) == 0) {
		display_error(_("The employee Conveyance Can't be empty."));
		set_focus('conveyance');
		return false;
	} 

	if ($new_item && strlen($_POST['edu_other']) == 0) {
		display_error(_("The employee Education Can't be empty."));
		set_focus('edu_other');
		return false;
	} 
	if ($new_item && strlen($_POST['medical_allowance']) == 0) {
		display_error(_("The employee Medical Allowance Can't be empty."));
		set_focus('medical_allowance');
		return false;
	} 

	if ($new_item && strlen($_POST['empl_pf']) == 0) {
		display_error(_("The employee PF Can't be empty."));
		set_focus('empl_pf');
		return false;
	} 
	if ($new_item &&  strlen($_POST['bank_name']) == 0 && $_POST['mod_of_pay']== 2) {
		display_error(_("The employee Bank Name Can't be empty."));
		set_focus('bank_name');
		return false;
	} 
	if ($new_item &&  strlen($_POST['acc_no']) == 0 && $_POST['mod_of_pay']== 2) {
		display_error(_("The employee Account Number Can't be empty."));
		set_focus('acc_no');
		return false;
	} 	*/
	
	if ($input_error != 1){
		if (check_value('del_image') || isset($_FILES['pic']) && $_FILES['pic']['name'] != '')	{
			$get_old_ext = GetSingleValue('kv_empl_info', 'empl_pic', array('empl_id' => $_POST['empl_id']));
			$filename = company_path().'/images/empl/'.$get_old_ext;
			if (file_exists($filename) && !is_dir($filename))
				unlink($filename);
		}
		$extension = '';
		if (isset($_FILES['pic']) && $_FILES['pic']['name'] != '') {
			$empl_id = $_POST['employee_id']; 
			$max_image_size = 500;
			$result = $_FILES['pic']['error'];
			$upload_file = 'Yes'; //Assume all is well to start off with
			$filename = company_path().'/images/empl';
			if (!file_exists($filename))
				mkdir($filename);

			$path_parts = pathinfo($_FILES["pic"]["name"]);
			$extension = $path_parts['extension'];	
			$flname = empl_img_name($empl_id).".".$extension;
			$filename .= "/".$flname;
						
			if ((list($width, $height, $type, $attr) = getimagesize($_FILES['pic']['tmp_name'])) !== false)
				$imagetype = $type;
			else
				$imagetype = false;
			
			if ($imagetype != IMAGETYPE_GIF && $imagetype != IMAGETYPE_JPEG && $imagetype != IMAGETYPE_PNG){	
				display_warning( _("Only graphics files can be uploaded"));
				$upload_file ='No';
			}
			elseif (!in_array(strtoupper(substr(trim($_FILES['pic']['name']), strlen($_FILES['pic']['name']) - 3)), array('JPG','PNG','GIF'))){
				display_warning(_("Only graphics files are supported - a file extension of .jpg, .png or .gif is expected"));
				$upload_file ='No';
			} 
			elseif ( $_FILES['pic']['size'] > ($max_image_size * 1024)) { //File Size Check
				display_warning(_("The file size is over the maximum allowed. The maximum size allowed in KB is") . ' ' . $max_image_size);
				$upload_file ='No';
			} 
			elseif (file_exists($filename) && !is_dir($filename)){
				$result = unlink($filename);
				if (!$result) 	{
					display_error(_("The existing image could not be removed"));
					$upload_file ='No';
				}
			}
			
			if ($upload_file == 'Yes'){
				$result  =  move_uploaded_file($_FILES['pic']['tmp_name'], $filename);
			}
			$Ajax->activate('details');	 
		} else 
			$flname = null ;
		$array_info =  array( 'empl_salutation' => $_POST['empl_salutation'], 'empl_firstname' => $_POST['empl_firstname'],			'empl_lastname' => $_POST['empl_lastname'], 
				'addr_line1' => $_POST['addr_line1'], 'addr_line2' => $_POST['addr_line2'], 'address2' => $_POST['address2'], 'empl_city' => $_POST['empl_city'],
				'empl_state' => $_POST['empl_state'], 'country' => $_POST['country'], 'gender' =>$_POST['gender'], 'date_of_birth' => array($_POST['date_of_birth'], 'date'),
				'marital_status' => $_POST['marital_status'], 'home_phone' => $_POST['home_phone'], 'mobile_phone' => $_POST['mobile_phone'], 'email' => $_POST['email'],
				'status' => $_POST['status'], 'report_to' => $_POST['report_to'],'supervisor' => $_POST['supervisor'], 'ice_name' => $_POST['ice_name'], 'ice_phone_no' => $_POST['ice_phone_no'],'p_period' => (isset($_POST['p_period']) ? array($_POST['p_period'], 'date'):'0000-00-00'),'cmy_period' => (isset($_POST['cmy_period']) ? array($_POST['cmy_period'], 'date'):'0000-00-00'), 'salary_payable_account' => $_POST['salary_payable_account']);
		if($flname)
			$array_info['empl_pic'] = $flname;
		if (!$new_item) { /*so its an existing one */
			begin_transaction();
			$kv_empl_id = $_POST['empl_id']; 
			$date_of_change = end_month(Today());
			if(isset($_POST['old_status']) && $_POST['old_status'] != $_POST['status'] && $_POST['status'] != 1){
				$array_info['reason_status_change'] = '';
				$array_info['date_of_status_change'] = array($date_of_change, 'date');
			}
			$job = GetRow('kv_empl_info', array('empl_id' => $empl_id));
			//access
			
			if(check_value('check_user')){
				if($_POST['user_id'] >0){
						$array_info['user_id'] = $_POST['user_id'];
				} else {
					$user_id_ = GetSingleValue('users','id', array('user_id' => $_POST['employee_id']));
					if($user_id_ > 0){
						$_POST['role'] = GetSingleValue('users', 'role_id' , ['id' => $user_id_]);
						update_user($user_id_, $_POST['employee_id'], $_POST['empl_firstname'], $_POST['mobile_phone'], $_POST['email'], $_POST['role'], 'C', 1, 1, 1);
					} else {
						add_user($user_id, $_POST['empl_firstname'],  md5($_POST['password']), $_POST['mobile_phone'], $_POST['email'], $_POST['role'], 'C', 1, 1, 1);
							$user_id_ = db_insert_id();
					}	
					if($user_id_ > 0)
						$array_info['user_id'] = $user_id_;
				}
						
			} else 
				$array_info['user_id'] = 0 ;

			Update('kv_empl_info', array('empl_id' => $empl_id), $array_info);
			if(isset($_POST['grade_id']))
			Update('kv_empl_job', array('empl_id' => $empl_id), array('grade' => $_POST['grade_id'] ));
			custom_field_update('employees',$empl_id);
			set_focus('employee_id');
			commit_transaction();
			$array_info["date_of_birth"]=date2sql($_POST['date_of_birth']);

			if(get_hrm_option('allow_recalculate')) {
				$Allowance = get_allowances(null, null, null, null, 0, $_POST['grade_id']);
				$gross_Earnings = 0 ;
				while ($single = db_fetch($Allowance)) {	
					if(input_num('E_'.$single['id'])){
						$jobs_arr[$single['id']] = input_num('E_'.$single['id']);
						if($single['type'] == 'Earnings')
							$gross_Earnings += input_num('E_'.$single['id']);
					}				
				} 
				if(input_num('gross')  > 0 )
					$jobs_arr['gross'] = input_num('gross');
				else
					$jobs_arr['gross'] = $gross_Earnings;
				$jobs_arr['gross_pay_annum'] = $jobs_arr['gross']*12;

				Update('kv_empl_job', array('empl_id' => $empl_id), $jobs_arr);
			}

			/*$last_change=Today();
			foreach ($result as $key => $value) {
				Insert('kv_empl_history', array('empl_id' => $_POST['empl_id'], 'option_name' => $key, 'option_value' => $value,'last_change' =>array($last_change,'date')));
			}*/
			meta_forward($_SERVER['PHP_SELF'], "empl_id=$kv_empl_id&Updated=yes"); 			
		} 
		else { //it is a NEW part
			begin_transaction();

			$array_info['empl_id'] = $kv_empl_id = $_POST['employee_id']; 			
			
			$jobs_arr =  array('empl_id' => $_POST['employee_id'],
							 'grade' => $_POST['grade_id'],
							 'al' => $_POST['al'],
							 'sl' => $_POST['sl'],
							 'ml' => $_POST['ml'],
							 'department' => $_POST['department'],
							 'desig_group' => input_num('desig_group'),
							 'desig' => $_POST['desig'],
							 'shift' => $_POST['shift'],
							 'currency' => $_POST['currency'],
							 'nationality' => $_POST['nationality'],
							 'family' => $_POST['family'],
							 'weekly_off' => base64_encode(serialize($_POST['weekly_off'])),					 				 
							
							 'empl_type' =>  $_POST['empl_type'], 
							 'empl_contract_type' => $_POST['empl_contract_type'],
							 'expd_percentage_amt' =>  ($_POST['expd_percentage_amt'] == '' ? 0 : $_POST['expd_percentage_amt']), 
							 'working_branch' =>  $_POST['working_place'],
						 	 'mod_of_pay' => $_POST['mod_of_pay'],
							 'nominee_address' => $_POST['nominee_address'],
							 'nominee_name' => $_POST['nominee_name'],
							 'nominee_phone' => $_POST['nominee_phone'],
							 'nominee_email' => $_POST['nominee_email'], 							 
							 'aadhar' => $_POST['aadhar'], 
							 'bloog_group' => $_POST['bloog_group'],						 
							 'ESIC' => $_POST['ESIC'], 
							 'PF' => $_POST['PF']);

			if(GetHRMOption('medical_preimum'))
				$jobs_arr['medi_category'] = $_POST['medi_category'];

			if($_POST['mod_of_pay'] == 1 ){	
				$jobs_arr['bank_name'] = $_POST['bank_name'];
				$jobs_arr['branch_detail'] = $_POST['branch_detail'];
				$jobs_arr['acc_no'] = $_POST['acc_no'];
				$jobs_arr['ifsc'] = $_POST['ifsc'];
			}

			if(isset($_POST['bond_period']))
				$jobs_arr['bond_period'] = date2sql($_POST['bond_period']);
				$jobs_arr['joining'] = date2sql($_POST['joining']);
				
			$Allowance = get_allowances(null, null, null, null, 0, $_POST['grade_id']);
			$gross_Earnings = 0 ;
			while ($single = db_fetch($Allowance)) {	
				if(input_num('E_'.$single['id'])){
					$jobs_arr[$single['id']] = input_num('E_'.$single['id']);
					if($single['type'] == 'Earnings')
						$gross_Earnings += input_num('E_'.$single['id']);
				}				
			} 
			if(input_num('gross')  > 0 )
				$jobs_arr['gross'] = input_num('gross');
			else
				$jobs_arr['gross'] = $gross_Earnings;
			$jobs_arr['gross_pay_annum'] = $jobs_arr['gross']*12;
			Insert('kv_empl_job', $jobs_arr);
			UploadHandle($_POST['employee_id']);
			if(db_has_auto_empl_id()) {
				kv_update_next_empl_id_new($kv_empl_id);   
			}
			if(check_value('check_user')){
				if($_POST['user_id'] >0){
					$array_info['user_id'] = $_POST['user_id'];
				} else {
					$user_id_ = GetSingleValue('users','id', array('user_id' => $_POST['employee_id']));
					if($user_id_ > 0){
						$_POST['role'] = GetSingleValue('users', 'role_id' , ['id' => $user_id_]);
						update_user($user_id_, $_POST['employee_id'], $_POST['empl_firstname'], $_POST['mobile_phone'], $_POST['email'], $_POST['role'], 'C', 1, 1, 1);
					} else {
						add_user($user_id, $_POST['empl_firstname'],  md5($_POST['password']), $_POST['mobile_phone'], $_POST['email'], $_POST['role'], 'C', 1, 1, 1);
							$user_id_ = db_insert_id();
					}	
					if($user_id_ > 0)
						$array_info['user_id'] = $user_id_;
				}
						
			} else 
				$array_info['user_id'] = 0 ;

			$array_info['salary_payable_account'] = $_POST['salary_payable_account'];
			Insert('kv_empl_info', $array_info);

			if((isset($_POST['ual']) && $_POST['ual'] != '') || (isset($_POST['usl']) && $_POST['usl'] != '')||(isset($_POST['uml']) && $_POST['uml'] != '')){
				$fiscal_year = get_current_fiscalyear();
				$previous_month = str_pad((date("m", strtotime($fiscal_year['begin']))-1), 2, '0', STR_PAD_LEFT);
				Insert('kv_empl_salary', array('empl_id' => $_POST['employee_id'], 'year' => $fiscal_year['id'], 'month' => (int)$previous_month, 'date' => array(Today(), 'date'),	'al' => -($_POST['ual']),'sl' => -($_POST['usl']), 'ml' => -($_POST['uml']), 'net_pay' => -1 ));
			}
			clear_data();	
			$_POST['empl_id'] = $kv_empl_id;
			custom_field_update('employees',$_POST['empl_id']);		
			set_focus('empl_id');
			$Ajax->activate('_page_body');
			commit_transaction();
			//meta_forward($_SERVER['PHP_SELF'], "empl_id=$kv_empl_id&Added=yes");
		}			
	}
}

//------------------------------------------------------------------------------------
if (isset($_POST['delete']) && strlen($_POST['delete']) > 1) {
	$empl_id = $_POST['empl_id'];

	if (key_in_foreign_table($empl_id, 'kv_empl_salary', 'empl_id')){		
		display_error(_("Cannot delete this Employee because Payroll Processed to this employee And it will be  added in the financial Transactions."));
	} else {
		$get_old_ext = GetSingleValue('kv_empl_info', 'empl_pic', array('empl_id' => $empl_id));
		delete_employee($empl_id);
		$filename = company_path().'/images/empl/'.$get_old_ext;
		if (file_exists($filename) && !is_dir($filename))
			unlink($filename);
		display_notification(_("Selected Employee has been deleted."));
		$_POST['empl_id'] = '';
		clear_data(); 
		set_focus('empl_id');
		$new_item = true;
		$Ajax->activate('_page_body');	
	}}
//------------------------------------------------------------------------------------
function empl_personal_data(&$empl_id='') {
	br();
	global $Ajax, $SysPrefs, $path_to_root, $page_nested, $new_item,$Refs;	
	if(get_post('empl_id') || list_updated('empl_id'))
		$Ajax->activate('profile');

	div_start('profile');
	start_outer_table(TABLESTYLE2);
	table_section(1);
	table_section_title(_("Employee Informations"));	
	//$_POST['employee_id']=$Refs->get_next(ST_EMPLOYEE_ID, null, null);
	if(get_post('empl_id') || ( list_updated('empl_id') && get_post('empl_id') )|| $empl_id)	{ // Must be modifying an existing item
		//if (get_post('employee_id') != $empl_id || get_post('addupdate')) { // first item display
			if(get_post('empl_id'))
				$_POST['employee_id'] = $_POST['empl_id'];
			else
				$_POST['employee_id'] = $empl_id;

			$row['role'] = GetSingleValue('users','role_id', array('user_id' => $_POST['employee_id']));
			if(!isset($_POST['empl_type']))
				$_POST['empl_type'] = GetSingleValue('kv_empl_job', 'empl_type', ['empl_id' => $_POST['employee_id']]);
			$myrow = GetRow('kv_empl_info', array('empl_id' => $_POST['employee_id']));
			
			$_POST['empl_salutation'] = $myrow["empl_salutation"];
			$_POST['empl_firstname'] = $myrow["empl_firstname"];
			$_POST['empl_lastname'] = $myrow["empl_lastname"];
			$_POST['addr_line1']  = $myrow["addr_line1"];
			$_POST['addr_line2']  = $myrow["addr_line2"];
			$_POST['address2']  = $myrow["address2"];
			$_POST['empl_city']  = $myrow["empl_city"];
			$_POST['country']  = $myrow["country"];
			$_POST['empl_state']  = $myrow["empl_state"];
			$_POST['empl_type']  = $_POST['empl_type'];
			$_POST['role']  = $row['role'];
			$_POST['home_phone']	= $myrow["home_phone"];
			$_POST['mobile_phone']  = $myrow["mobile_phone"];
			$_POST['email']  = $myrow["email"];
			$_POST['gender']  = $myrow["gender"];
			$_POST['report_to']  = $myrow["report_to"];
			$_POST['supervisor']  = $myrow["supervisor"];
			$_POST['ice_name']	= $myrow["ice_name"];
			// $_POST['user_id']	= $myrow["user_id"];

			$_POST['ice_phone_no']  = $myrow["ice_phone_no"];
			//$_POST['n_period'] = sql2date($myrow['n_period']);
			

			if(!isset($myrow['date_of_birth']) || $myrow['date_of_birth'] == '0000-00-00')
				$_POST['date_of_birth']=add_years(Today(), -20);
			else
				$_POST['date_of_birth']  = (isset($_POST['date_of_birth']) ? $_POST['date_of_birth'] : sql2date($myrow["date_of_birth"]));
			$_POST['marital_status']  = $myrow["marital_status"];
			if(list_updated('status'))
				$_POST['status'] = get_post('status');
			else
				$_POST['status'] = $myrow["status"];			
			$_POST['empl_pic'] = $myrow["empl_pic"];			
			$_POST['del_image'] = 0;
			$_POST['pic'] = '';

			hidden('old_status', $myrow["status"]);
		if (!isset($_POST['empl_id']) || $new_item) {
			text_row(_("Employee Id").":", 'employee_id', $_POST['employee_id'], 21, 20);
		}else
			label_row(_("Employee Id")."*:",$_POST['employee_id']);

		hidden('employee_id', $_POST['employee_id']);
		
		set_focus('description');
			
	}  else {
		if(get_hrm_option('empl_ref_type')){
			if(!isset($_POST['employee_id']))
				$_POST['employee_id'] = $employee_id = $Refs->get_next(ST_EMPLOYEE_ID, null, null);
		}
		
		if(!isset($_POST['employee_id']))
			$_POST['employee_id'] = '';
			
		text_row(_("Employee Id").":", 'employee_id', $_POST['employee_id'], 21, 20);		
		//unset($_POST['empl_id']);
		$_POST['inactive'] = 0;
		if(!isset($_POST['empl_firstname']))
			$_POST['empl_firstname'] = '';
		if(!isset($_POST['empl_lastname']))
			$_POST['empl_lastname'] = '';
		if(!isset($_POST['addr_line1']))
			$_POST['addr_line1']= ''; 
		if(!isset($_POST['addr_line2']))
			$_POST['addr_line2']= ''; 
		if(!isset($_POST['empl_city']))
			$_POST['empl_city']= ''; 
		if(!isset($_POST['empl_state']))
			$_POST['empl_state']= ''; 
		if(!isset($_POST['date_of_birth']) || $_POST['date_of_birth'] == '0000-00-00')
			$_POST['date_of_birth']=add_years(Today(), -20);
		if(!isset($_POST['medi_category']))
				$_POST['medi_category'] = '';
		if(!isset($_POST['family']))
				$_POST['family'] = '';
		// if(!isset($_POST['weekly_off']))
		// 		$_POST['weekly_off'] = '';
		$_POST['nationality'] = (isset($_POST['nationality']) ? $_POST['nationality'] : get_hrm_option('nationality'));
	}

	kv_empl_salutation_list_row( _("Salutation").":", 'empl_salutation', null);
	text_row(_("First Name").":*", 'empl_firstname', null, 35, 100);
	text_row(_("Last Name").":", 'empl_lastname', null,  35, 100);
	table_section_title(_("Permanent Address"));
	text_row(_("Line 1").":", 'addr_line1', null, 35, 100);
	text_row(_("Line 2").":", 'addr_line2', null, 35, 100);
	text_row(_("City").":", 'empl_city', null, 35, 100);
	text_row(_("State").":", 'empl_state', null, 35, 100);

	// elseif(get_hrm_option('empl_role')){
	// 	security_roles_list_cells(_("Access Role").":". "&nbsp;", 'role', get_hrm_option('empl_role'), false, false, check_value('show_inactive'));
	// }

	// if(isset($_POST['role'])) //$_POST['employee_id']
	// 	security_roles_list_cells(_("Access Role").":". "&nbsp;", 'role', $_POST['role'] , false, false, check_value('show_inactive'));

	if(!isset($_POST['country']))
		$_POST['country'] = get_hrm_option('home_country');
 	country_list_row(_("Country").":", 'country', null);

 	table_section_title(_("Residential Address"));
	textarea_row(_("Residential Address").":", 'address2', null, 30, 5);
	
	table_section_title(_("Contact Details"));
	text_row(_("Home Phone").":", 'home_phone', null,  35, 100);
	text_row(_("Mobile Phone")."*:", 'mobile_phone', null,  35, 100);
	text_row(_("Email").":", 'email', null, 35, 100);	

	if (!isset($_POST['empl_id']) || $new_item) {		
		kv_empl_gender_list_row( _("Gender").":", 'gender', null);
		date_row(_("Date of Birth") . ":", 'date_of_birth', null, null, 0,0,0,null, true);
		if (list_updated('date_of_birth') || $new_item) {
			$_POST['age'] = date_diff(date_create(date2sql($_POST['date_of_birth'])), date_create('today'))->y;
		}
		label_row(_("Age").":", $_POST['age']);	
		hrm_empl_marital_list_row( _("Marital Status").":", 'marital_status', null);	
		hrm_empl_nationality_row( _("Nationality").":", 'nationality', null);	
		kv_empl_number_list_row(_("Family").":", 'family', null, 0, 20); 
		hrm_empl_medical_premium_row(_("Medical Category").":", 'medi_category', null); 

		if(!isset($_POST['weekly_off'])){
			$_POST['weekly_off'] = get_hrm_option('weekly_off');				
		}
		hrm_empl_workings_days(_("Weekend/Weekly Off")."*:", 'weekly_off', null, false, true);	
				
	} 
if(!isset($_POST['salary_payable_account']))
	$_POST['salary_payable_account'] = get_hrm_option('salary_payable');
gl_all_accounts_list_row(_("Salary Payable Account")." :", 'salary_payable_account', null, false,false, false);
$single['user_id'] = GetSingleValue('kv_empl_info','user_id', array('empl_id' => $empl_id));	
if($single['user_id'] == 0 ){
	check_cells(_("Add user to Employee"), 'check_user', null,true);
		if(check_value('check_user') == 1){
			kv_empl_user_list_row(_('User Account'),'user_id', null, _("New user"), true,true);
		
			if($_POST['user_id']  > 0){ } else {
				$_POST['password'] = "";
				password_row(_("Password:"), 'password', $_POST['password']);
				security_roles_list_cells(_("Access Role").":". "&nbsp;", 'role', $_POST['role'] , false, false, check_value('show_inactive'));
			}
			//if(isset($_POST['role'])){
			// $_POST['role'] = GetSingleValue('security_roles','role', array('role' => 'Employee Sellf Portal'));
			// security_roles_list_cells(_("Access Role").":". "&nbsp;", 'role', $_POST['role'] , false, false, check_value('show_inactive'));
			// }
		}
}	
	hrm_empl_status_list(_("Status")."*:", 'status', null, true);
	if(isset($_POST['empl_id']) && list_updated('status')){		
		if($_POST['status'] != 1)
			textarea_row(_("Reason for Leaving").":", 'reason_status_change', null, 30, 5);
	} else {
		hrm_empl_type_row(_("Employment Type")."*:", 'empl_type', null,true);
		if(list_updated('empl_type') && get_post('empl_type')== 3)
			empl_picklist_row(_("Contract Type").":", 'empl_contract_type',null, false, false, 4);
		else
			hidden('empl_contract_type',0);
	}

	//for custom fields
	if(isset($_POST['empl_id']))
	custom_field_section('employees',$_POST['empl_id'],1);
	//end custom fields	
			
								 
	table_section(2); 
	div_start('payroll_tbl');	// Add image upload for New Item 
	table_section_title(_("Personal Details"));
	$stock_img_link = "";
	$check_remove_image = false;
	if ($empl_id!= '' && file_exists(company_path().'/images/empl/'.$_POST['empl_pic']) && !is_dir(company_path().'/images/empl/'.$_POST['empl_pic'])){	
		$stock_img_link .= "<img id='empl_profile_pic' alt = '[".$_POST['empl_pic']."]' src='".company_path().'/images/empl/'.$_POST['empl_pic']."?nocache=".rand()."'"." height='150' border='1'>";
		$check_remove_image = true;
	} else {
		$stock_img_link .= "<img id='empl_profile_pic' alt = '[".$_POST['employee_id'].".jpg"."]' src='".$path_to_root.'/modules/ExtendedHRM/images/no-image.png'. "?nocache=".rand()."'"." height='150' border='1'>";
	}
	label_row("&nbsp;", $stock_img_link);		
	kv_hrm_image_row(_("Photo (.jpg)").":", 'pic', 'pic');
	if ($check_remove_image)
		check_row(_("Delete Image").":", 'del_image');	 	
	if (isset($_POST['empl_id']) && !$new_item){
		kv_empl_gender_list_row( _("Gender").":", 'gender', null);
		date_row(_("Date of Birth").":", 'date_of_birth', null, null, 0,0,0,null, true);
		if (list_updated('date_of_birth') || $new_item|| get_post('date_of_birth')) {
			$_POST['age'] = date_diff(date_create(date2sql($_POST['date_of_birth'])), date_create('today'))->y;
		}
		label_row(_("Age").":", $_POST['age']);	
		hidden('age', $_POST['age']);
		hrm_empl_marital_list_row( _("Marital Status").":", 'marital_status', null);
	}	
	
	hidden('empl_page', 'info') ; 
	//$allow_recalculate = true;
	if (!isset($_POST['empl_id']) || $new_item || get_hrm_option('allow_recalculate')) { 
		if(!isset($_POST['currency'])){
			$company_record = get_company_prefs();
			$_POST['currency']  = $company_record["curr_default"];
		}	
		
		if(get_hrm_option('allow_recalculate') && isset($_POST['empl_id']) && $_POST['empl_id'] != '' && get_post('grade_id') <= 0 ){
			$job_row = GetRow('kv_empl_job', array('empl_id' => $_POST['empl_id']));
			$_POST['grade_id']	= $job_row["grade"];
			$_POST['gross'] = $job_row['gross'];
		}

		currencies_list_row(_("Currency"), 'currency', null);

		$gross = GetRow('kv_empl_allowances', array('gross' => 1));
			$basic_allowed = true;
			if($gross){
				kv_basic_row(get_allowance_name($gross['id']), 'gross', 15, 100, null, true);
			} else {
				$basic = GetRow('kv_empl_allowances', array('basic' => 1));
				kv_basic_row(get_allowance_name($basic['id']), $basic['id'], 15, 100, null, true);
				$basic_allowed = false;
			}
			
			kv_empl_grade_list_row( _("Grade").":", 'grade_id', null, _("Select a Grade"), true);
		if(get_post('grade_id') > 0 ){
			$EarAllowance = get_allowances('Earnings', 'Profile Input', 'Percentage', 'Gross Percentage', 0, get_post('grade_id'), 'Formula');
		
			if(db_num_rows($EarAllowance) > 0){
				$KVAllowance = kv_get_allowances(null, 0, get_post('grade_id'));
				$allowance_var_ar = array();
				foreach($KVAllowance as $single) {
					$allowance_var_ar[$single['id']] = '{$'.$single['unique_name'].'}';	
				}
				
				table_section_title(_("Earnings"));
				while ($single = db_fetch($EarAllowance)) {							
				
					if((($single['basic'] != 1 || $basic_allowed ) && $single['gross'] != 1 ) ){
						kv_text_row_ex(_($single['description']).":", 'E_'.$single['id'], 15, 100, null, null, null, null, true); 
					}
				}
			}

			label_row(_("Total Earning(Gross Salary)").":", price_format($_POST['gross']), 'style="color:#FF9800; background-color:#f9f2bb;"', 'style="color:#FF9800; background-color:#f9f2bb;"');
			$reimburse = 0;
			table_section_title(_("Benefits"));
			$ReimbursementAllowance = get_allowances('Reimbursement', 'Profile Input', 'Percentage', 'Gross Percentage', 0, get_post('grade_id'), 'Formula');
			if(db_num_rows($ReimbursementAllowance) > 0){
				while ($single = db_fetch($ReimbursementAllowance)){			
					 kv_text_row_ex(_($single['description'].":"), 'E_'.$single['id'], 15, 100, null, null, null, null, true); 

					$reimburse += input_num('E_'.$single['id']);				
				}
			}

			label_row(_("Total Benefits").":", price_format($reimburse), 'style="color:#FF9800; background-color:#f9f2bb;"', 'style="color:#FF9800; background-color:#f9f2bb;"');
			$empl_contribution = 0;
			table_section_title(_("Employer Contribution"));
			$CTCAllowance = get_allowances('Employer Contribution', 'Profile Input', 'Percentage', 'Gross Percentage', 0, get_post('grade_id'), 'Formula');	

			if(db_num_rows($CTCAllowance) > 0){	
				while ($single = db_fetch($CTCAllowance)){			
					kv_text_row_ex(_($single['description'].":"), 'E_'.$single['id'], 15, 100, null, null, null, null, true); 
					$empl_contribution += input_num('E_'.$single['id']);
				}
			}
			label_row(_('Total CTC only'), price_format($empl_contribution), 'style="color:#9C27B0; background-color:rgba(156, 39, 176, 0.23);"', 'style="color:#9C27B0; background-color:rgba(156, 39, 176, 0.23);"');
			if($_POST['gross']){
				$Overall = $empl_contribution+$reimburse+$_POST['gross'];
				label_row(_('Overall CTC'), price_format($Overall), 'style="color:#9C27B0; background-color:rgba(156, 39, 176, 0.23);"', 'style="color:#9C27B0; background-color:rgba(156, 39, 176, 0.23);"');
			}
			$deduct_tot = 0 ;
			table_section_title(_("Deductions"));
			$DedAllowance = get_allowances('Deductions', 'Profile Input', 'Percentage', 'Gross Percentage', 0, get_post('grade_id'), 'Formula');
			if(db_num_rows($DedAllowance) > 0){			
				while ($single = db_fetch($DedAllowance)) {				
					if($single['loan'] != 1)
					kv_text_row_ex(_($single['description'].":"), 'E_'.$single['id'], 15, 100, null, null, null, null, true); 					
					$deduct_tot += input_num('E_'.$single['id']);
				}
			}
			label_row(_("Total Deductions"), price_format($deduct_tot), 'style="color:#f55; background-color:#fed;"', 'style="color:#f55; background-color:#fed;"');
		}
		table_section_title(_("Payment Mode"));
		hrm_empl_mop_list(_("Mode of Pay")."*:", 'mod_of_pay', null,true);	
		if($_POST['mod_of_pay'] == 1 ){	
		text_row(_("Bank Name").":", 'bank_name', null,  15, 100);
		text_row(_("Bank Account No").":", 'acc_no', null,  15, 100);
		text_row(_("Bank Branch").":", 'branch_detail', null,  15, 100);
		text_row(_("IFSC Code").":", 'ifsc', null,  15, 100);	
		}			
	}
	table_section_title(_("Contact(ICE)"));
	text_row(_("Name").":*", 'ice_name', null,  35, 100);
	text_row(_("Mobile Phone").":*", 'ice_phone_no', null,  35, 100);
	table_section_title(_("Period Settings"));
		//if(isset($myrow['n_period'])&& $myrow['n_period'] != '0000-00-00')
		//	$_POST['n_period_setting'] = 1;
		if(isset($myrow['p_period'])&& $myrow['p_period'] != '0000-00-00')
			$_POST['p_period_setting'] = 1;
		if(isset($myrow['cmy_period'])&& $myrow['cmy_period'] != '0000-00-00')
			$_POST['c_period_setting'] = 1;
		/*check_row(_("Notice Period"), 'n_period_setting',null,true);				
		if((list_updated('n_period_setting') || get_post('n_period_setting'))&& check_value('n_period_setting')==1){
				$n1_period = get_hrm_option('n_period');
			date_row(_("Notice Period (Days) :") , 'n_period',null,null,$n1_period);
			$Ajax->activate('profile');
		}*/
		check_row(_("Probationary Period"), 'p_period_setting',null,true);				
		if((list_updated('p_period_setting')|| get_post('p_period_setting')) && check_value('p_period_setting')==1){
			$p1_period = get_hrm_option('p_period');
			$_POST['p_period'] = (isset($myrow['p_period']) ? sql2date($myrow['p_period']) : Today());
			$_POST['p_period'] = add_months($_POST['p_period'], $p1_period);		
			
			date_row(_("Probationary Period (Month)").":" , 'p_period',null,null,0,$p1_period);
			$Ajax->activate('profile');
		}
		check_row(_("Contract Period"), 'c_period_setting',null,true);				
		if((list_updated('c_period_setting')|| get_post('c_period_setting')) && check_value('c_period_setting')==1){
			$_POST['cmy_period'] = (isset($myrow['cmy_period']) ? sql2date($myrow['cmy_period']) : Today());  //sql2date($myrow['cmy_period']);
			$cm1_period = get_hrm_option('cm_period');
			$cy1_period = get_hrm_option('cy_period');
			date_row(_("Contract Period (Month/Year)").":" , 'cmy_period',null,null,0,$cm1_period,$cy1_period);
			$Ajax->activate('profile');
		}	
	employee_list_row(_("Report To").":", 'report_to', null, _("Select an Employee"));	
	employee_list_row(_("Supervisor"), 'supervisor', null, _("Select"));		
	

	if(!isset($_POST['empl_id']) || $new_item){	
		table_section_title(_("Bond Details"));
		check_row(_("Bond Period"), 'b_period_setting',null,true);				
		if((list_updated('b_period_setting') || get_post('b_period_setting'))&& check_value('b_period_setting')==1){
				$_POST['bond_period']=Today(); 
				date_row(_("End of bond date") . ":", 'bond_period');
				$Ajax->activate('payroll_tbl');
				kv_doc_row(_("Select Docs") . ":", 'kv_attach_name', 'kv_attach_name');			
		}/*else{
			hidden('bond_period','0000-00-00');
		}*/

		table_section(3);
		table_section_title(_("Job Details"));
			if(list_updated('department')){		
				$_POST['role'] = GetSingleValue('kv_empl_departments','role', array('id' => get_post('department')));
				$Ajax->activate('role');

				
			}
		department_list_row( _("Department").":", 'department', null, false,true, false,false, true);
		// get_post('department');
		hrm_empl_desig_group(_("Designation Group")."*:", 'desig_group', null);
		designation_list_row(_("Designation")."*:", 'desig', null);
		//text_row(_("Desgination *:"), 'desig', null,  35, 100);
		//text_row(_("Basic Salary *:"), 'basic_salary', null, 30, 30);
		date_row(_("Date of Join").":", 'joining');
		
			//hrm_empl_contract_type_row(_("Contract Type*:"), 'empl_contract_type', null);

		workcenter_list_row(_("Working Place")."*:", 'working_place');
		table_section_title(_("KYC IDS"));
		text_row(_("ESIC").":", 'ESIC', null,  30, 100);
		text_row(_("PF").":", 'PF', null,  30, 100);
		//text_row(_("PAN Card No*:"), 'PAN', null,  30, 100);
		if(!isset($_POST['expd_percentage_amt']))
			$_POST['expd_percentage_amt'] = get_hrm_option('expd_percentage_amt');
		text_row_ex(_("Maximum allowed Limit Percentage").":", 'expd_percentage_amt', 10, 10, '', null, null, "% for Loan Monthly Pay");
		if(!list_updated('department')){
		hidden($_POST['role'] = '');
	}
		// if(check_value('check_user') == 0){
		// 	if(get_hrm_option('enable_employee_access'))
		// 		security_roles_list_cells(_("Access Role").":". "&nbsp;", 'role', get_hrm_option('empl_role'), true, false, check_value('show_inactive'));
		// }
		empl_shifts_list_row(_("Employee Shift"), 'shift', null, _("Company Time"));
		table_section_title(_("KYC Details")); 
		hrm_empl_blood_list(_("Blood Group").":", 'bloog_group', null);		
		text_row(_("National ID No").":", 'aadhar', null,  25, 100);
		text_row(_("Nominee Name").":", 'nominee_name', null,  25, 100);
		text_row(_("Nominee Phone Number").":", 'nominee_phone', null,  25, 100);
		text_row(_("Nominee Email").":", 'nominee_email', null,  30, 100);		
		textarea_row(_("Nominee Address").":", 'nominee_address', null,  30, 5);

		table_section_title(_("Leave Details"));
		$_POST['al'] = $_POST['sl'] = $_POST['ml']= 0;
		if(get_post('grade_id') || list_updated('grade_id')){
			$leave_values = GetRow('kv_empl_grade', array('id' => get_post('grade_id')));
			$_POST['al'] = round($leave_values['al']);
			$_POST['sl'] = round($leave_values['sl']);			
			$_POST['ml'] = round($leave_values['ml']);		
		}
		text_row(_('Annual Leave'), 'al', null,  5, 10);
		text_row(_('Sick Leave Days'), 'sl', null,  5, 10);		
		text_row(_('Maternity Leave'), 'ml', null,  5, 10);
		table_section_title(_("Unused Existing Leave Details"));
		text_row(_('Annual Leave'), 'ual', null,  5, 10);
		text_row(_('Sick Leave Days'), 'usl', null,  5, 10);
		text_row(_('Maternity Leave'), 'uml', null,  5, 10);		
	}
	//for custom fields
	if(isset($_POST['empl_id']))
	custom_field_section('employees',$_POST['empl_id'],2);
	//end custom fields 	
	end_outer_table(1);
	div_end();
	div_end();
	div_start('controls');
	br();
	if (!isset($_POST['empl_id']) || $new_item) {
		submit_center('addupdate', _("Add New Employee"), true, '', 'default');
	} else {
		submit_center_first('addupdate', _("Update Employee Information"), '',@$_REQUEST['popup'] ? true : 'default');
		submit('delete', _("Delete employee"), true, '', true);
		echo '<a target="_blank" href="'.$path_to_root.'/modules/ExtendedHRM/reports/rep812.php?PARAM_0=0&PARAM_1='.$_POST['empl_id'].'&rep_v=yes" class="printlink"><button  name="print" id="Print" value="Print"><img src="'.$path_to_root.'/themes/default/images/print.png" style="vertical-align:middle;width:12px;height:12px;border:0;" title="Print">'.'<span>'._("Print Employee Details").'</span>'.'</button></a>';
		submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
	}
	div_end();
	br();	
}

//-----------------------------------------------------------------------------------------
function empl_increment_data($empl_id){
	global $Ajax;
	$job_details = get_employee_job($empl_id);
	
	$incremnt_per = 1; 
	if(!isset($_POST['increment_percent']))
		$_POST['increment_percent'] = '';
	if(get_post('RefreshIncrement') && input_num('increment_percent') > 0 ) {		
		$incremnt_per = input_num('increment_percent')/100;		
		$Ajax->activate('Increment_table');
	}

	if (isset($_POST['applyincrement'])) {
		$Allowance = kv_get_allowances(null, 0, $job_details['grade']);
		$gross_Earnings = 0;
		foreach($Allowance as $single) {
			if(isset($_POST[$single['id'].'_'])){	
				$job_arr[$single['id']] = input_num($single['id'].'_');
				
				if($single['type'] == 'Earnings')
					$gross_Earnings += input_num($single['id'].'_');
			}
		}

		if(!isset($_POST['gross'])){
			$job_arr['gross'] = $gross_Earnings;
			$job_arr['gross_pay_annum'] = $gross_Earnings*12;
		} else {
			$job_arr['gross'] = $_POST['gross'];
			$job_arr['gross_pay_annum'] = $_POST['gross']*12;
		}
		Update('kv_empl_job', array('empl_id' => $_POST['empl_id']), $job_arr);
		foreach($Allowance as $single) {
			unset($_POST[$single['id']]);
		}
		display_notification(_('Your Increment').$_POST['increment_percent']._('% Was Applied to the Selected Employee'));
	}

	div_start('Increment_table');
	$Allowance = kv_get_allowances(null,0, $job_details['grade']);
	//$DedAllowance = kv_get_allowances('Deductions',0, $job_details['grade']);
	//$Reimbursement = kv_get_allowances('Reimbursement',0, $job_details['grade']);
	//$AddToCTC = kv_get_allowances('Employer Contribution',0, $job_details['grade']);
	$Ear_allowance = $Ded_allowance = array();
	foreach($Allowance as $single){
		if($single['type'] == 'Earnings')
			$_POST[$single['id'].'_'] = ($incremnt_per != 1 ? (is_numeric($job_details[$single['id']])? $job_details[$single['id']] : 0 )+((isset($job_details[$single['id']]) && is_numeric($job_details[$single['id']])) ? (float)$job_details[$single['id']] : 0 )*$incremnt_per : 0);
		if($single['type'] == 'Deductions')
			$_POST[$single['id'].'_'] = ($incremnt_per != 1 ? (is_numeric($job_details[$single['id']])? $job_details[$single['id']] : 0 )+((isset($job_details[$single['id']]) && is_numeric($job_details[$single['id']])) ? (float)$job_details[$single['id']] : 0 )*$incremnt_per : 0);
	}
	br();
	start_outer_table(TABLESTYLE);
	table_section(1);
		table_section_title(_("Current Salary"));		
		$basic_id = kv_get_basic();
		table_section_title(_("Earnings"));
		$AddToCTC = $Reimbursement = $DedAllowance = 0;
		foreach($Allowance as $single) {
			if($single['type'] == 'Earnings'){
				label_row(_($single['description']), $job_details[$single['id']] /*.($_POST[$single['id']] > 0 ? ('+'.$_POST[$single['id']].'='.($job_details[$single['id']]+$_POST[$single['id']]))  : '' )*/);
					
				if($single['basic'] == 1 ){
					$_POST[$basic_id.'_'] = $job_details[$single['id']];
				}
			} 
			if($single['type'] == 'Reimbursement')
				$Reimbursement++;
			if($single['type'] == 'Employer Contribution')
				$AddToCTC++;
			if($single['type'] == 'Deductions')
				$DedAllowance++;
		}
		if(count_array($Reimbursement) > 0 ){
			table_section_title(_("Reimbursement"));
			foreach($Allowance as $single) {
				if($single['type'] == 'Reimbursement')
					label_row(_($single['description']), $job_details[$single['id']] );	
			}
		}

		label_row(_("Gross Salary"), price_format($job_details['gross'], 2));
		if(count_array($AddToCTC) > 0){
			table_section_title(_("AddToCTC"));
			foreach($Allowance as $single) {
				if($single['type'] == 'Employer Contribution')
					label_row(_($single['description']), $job_details[$single['id']]);				
			}
		}
		if(count_array($DedAllowance) > 0){
			table_section_title(_("Deductions"));
			$prof_tax = kv_get_Tax_allowance();
			$loan_id = kv_get_loan_field();
			foreach($Allowance as $single) {
				if($single['type'] == 'Deductions' && $single['id'] != $prof_tax && $single['loan'] != 1)
					label_row(_($single['description']), $job_details[$single['id']]);				
			}
		}
		table_section(2);
		table_section_title(_("Current Salary + Increment"));
		text_row_ex(_("Increment Percentage").":", 'increment_percent', 10, 10, '', null, null, "%");	
		echo '<tr><td> </td>';
		submit_cells('RefreshIncrement', _("Refresh"),'',_("Show Results"), 'default');
		echo '</tr>';
		
		if(input_num('increment_percent') > 0 )
			$_POST[$basic_id.'_'] = $_POST[$basic_id.'_'] + $_POST[$basic_id.'_']*(input_num('increment_percent')/100);
		
		kv_text_row_ex(_(get_allowance_name($basic_id))." :", $basic_id.'_', 15, 100, null, null, null, null, true); 
		$EarAllowance = get_allowances('Earnings', null, null, null, 0, $job_details['grade']);		
		foreach($Allowance as $single) {	
			if($single['type'] == 'Earnings'){
				if($single['value'] == 'Percentage' && $single['percentage']>0){			
					$default_value = (get_post($basic_id.'_') +  get_post($basic_id.'_')*(input_num('increment_percent')/100))*($single['percentage']/100);
				}else {
					$default_value = $job_details[$single['id']];					
				}
				if($single['id'] != $basic_id){
					$_POST[$single['id']] = $default_value;
					kv_text_row_ex(_($single['description']).":", $single['id'].'_', 15, 100, null, $default_value, null, null, true); 
					//$gross_pay += get_post($single['id']);						
				}					
			}					
		}
// !is_numeric
		$ReimbursementAllowance = get_allowances('Reimbursement', null, null, null, 0, $job_details['grade']);
		if(count_array($Reimbursement) > 0 ){
			table_section_title(_("Reimbursement"));
			foreach($Allowance as $single){
				if($single['type'] == 'Reimbursement'){
					if($single['formula'] == '' && is_numeric($single['formula']) && $single['value'] == 'Percentage' && $single['percentage']>0){	
						$default_value = (get_post($basic_id) +  get_post($basic_id)*(input_num('increment_percent')/100))*($single['percentage']/100);
					}else {
						$default_value = $job_details[$single['id']];
					}
					$_POST[$single['id']] = $default_value;
					kv_text_row_ex(_($single['description'])." :", $single['id'].'_', 15, 100, null, $default_value, null, null, true);
				}
			}
		}
		$gross_increment = $job_details['gross']+($job_details['gross']*(input_num('increment_percent')/100));
		label_row(_("Gross Salary"), price_format($gross_increment, 2));
		hidden('gross', $gross_increment);
		$CTCAllowance = get_allowances('Employer Contribution', null, null, null, 0, $job_details['grade']);
		if(count_array($CTCAllowance) > 0){					
			table_section_title(_("Employer Contribution"));
			foreach($Allowance as $single){
				if($single['type'] == 'Employer Contribution'){
					if($single['formula'] == '' && is_numeric($single['formula']) && $single['value'] == 'Percentage' && $single['percentage']>0){		
						$default_value = (get_post($basic_id) +  get_post($basic_id)*(input_num('increment_percent')/100))*($single['percentage']/100);
					}else {
						$default_value = $job_details[$single['id']];
					}
					$_POST[$single['id']] = $default_value;
					kv_text_row_ex(_($single['description'])." :", $single['id'].'_', 15, 100, null, $default_value); 
					//$to_ctc += get_post($single['id']);
				}
			}
		}

		$DedAllowance = get_allowances('Deductions', null, null, null, 0, $job_details['grade']);
		if(count_array($DedAllowance) > 0){	
			table_section_title(_("Deductions"));		
			foreach($Allowance as $single) {				
				if($single['type'] == 'Deductions'){
					if(is_numeric($single['value']) && $single['value'] == 'Percentage' && $single['percentage']>0){		
						$default_value = (get_post($basic_id) +  get_post($basic_id)*(input_num('increment_percent')/100))*($single['percentage']/100);
					}else {
						$default_value = $job_details[$single['id']];
					}
					if($single['id'] != $prof_tax && $single['loan'] != 1 && $single['value'] != 'Payroll Input' ){
						$_POST[$single['id']] = $default_value;
						kv_text_row_ex(_($single['description'])." (-) :", $single['id'].'_', 15, 100, null, $default_value); 							
					}		
				}
			}
		}		
	end_outer_table(2);
	br();
	submit_center('applyincrement', _("Apply Increment"), true, '', 'default');
	br();
	div_end();
}	

//-----------------------------------------------------------------------------------------
function empl_termination($empl_id){
	global $Ajax;	
	if (isset($_POST['changeStatus'])) {
		Update('kv_empl_info', array('empl_id' => $_POST['empl_id']), array('reason_status_change' => $_POST['reason_status_change'],'n_period' => (isset($_POST['n_period']) ? array($_POST['n_period'], 'date'):'0000-00-00'), 'status' => $_POST['status'], 'date_of_status_change' => date2sql($_POST['date'])));
		display_notification(_("Status Changed successfully with reason"));
	}
	$empl_details = GetRow('kv_empl_info', array('empl_id' => $empl_id));
	$_POST['n_period']=sql2date($empl_details['n_period']);
	br();
	div_start('termination');
	start_table(TABLESTYLE);
		label_row(_("Employee ID"), $empl_details['empl_id']);
		label_row(_("Employee Name"), $empl_details['empl_firstname'].' '.$empl_details['empl_lastname']);
		hrm_empl_status_list(_("Status")."*:", 'status', null, true);
		if( $empl_details['user_id'] > 0 )
			hidden('user_id', $empl_details['user_id']);
		textarea_row(_("Reason for Leaving").":", 'reason_status_change', $empl_details['reason_status_change'], 30, 5);
		date_row(_("Date") . ":", 'date');
		if(isset($empl_details['n_period'])&& $empl_details['n_period'] != '0000-00-00')
			$_POST['n_period_setting'] = 1;
				check_row(_("Notice Period"), 'n_period_setting',null,true);				
		if((list_updated('n_period_setting') || get_post('n_period_setting'))&& check_value('n_period_setting')==1){
				$n1_period = get_hrm_option('n_period');
			date_row(_("Notice Period (Days)").":", 'n_period',null,null,$n1_period);
			$Ajax->activate('termination');
		}

	end_outer_table(2);
	br();
	submit_center('changeStatus', _("Change Status"), true, '', 'default');
	br();	
	div_end();
}	

//-----------------------------------------------------------------------------------------
function empl_notes($empl_id){
	global $Ajax;
	if (isset($_POST['submitNote'])) {
		Update('kv_empl_info', array('empl_id' => $_POST['empl_id']), array('notes' => $_POST['description']));
		display_notification(_("Note Updated successfully"));
	}
	br();
	$_POST['description'] = GetSingleValue('kv_empl_info', 'notes', array('empl_id' => $empl_id));
	start_table(TABLESTYLE);
		kv_hrm_textarea_row(null, 'description', null, 70, 10);
		//textarea_row(_("Notes:"), 'notes', null, 50, 8);	
	end_outer_table(2);
	br();
	submit_center('submitNote', _("Submit"), true, '', 'default');
	br();	
}
//-------------------------------------------------------------------------------------------- 
//-----------------------------------------------------------------------------------------
function empl_life_to_date_history($empl_id){
	global $Ajax;
	$empl_history = GetAll('kv_empl_history', array('empl_id' => $empl_id),array('last_change'=>'DESC'));
	$date_group = '0000-00-00';
	br(2);
	start_table(TABLESTYLE);
		foreach($empl_history as $history )	{
			if($date_group != $history['last_change']){
					$date_group = $history['last_change'];
					table_section_title(sql2date($history['last_change']));
				}
				label_row($history['option_name'], $history['option_value']);
			}
	end_outer_table(2);
	br();
	
}
//-------------------------------------------------------------------------------------------- 
start_form(true);
if (db_has_employees()) {
	start_table(TABLESTYLE_NOBORDER);
	start_row();
    department_list_cells(_("Select a Department")." :", 'dept_id', null,	_("No Department"), true, check_value('show_inactive'));
	employee_list_cells(_("Select an Employee")." :", 'empl_id', null,	_("New Employee"), true, check_value('show_inactive'), false, false,true);
	check_cells(_("Show inactive:"), 'show_inactive', null, true);
	$new_item = get_post('empl_id')=='';
	end_row();
	end_table();
	if (get_post('_show_inactive_update')) {
		$Ajax->activate('empl_id');
		set_focus('empl_id');
	}
} else {
	hidden('empl_id', get_post('empl_id'));
}

div_start('details');
$empl_id = get_post('empl_id');
if (!$empl_id)
	unset($_POST['_tabs_sel']); // force settings tab for new customer

$tab_cont_ar = array(
		'personal' => array(_("Personal Info"), $empl_id),
		'job' => array(_("Job"), (user_check_access('HR_EMPL_INFO') ? $empl_id : null) ),				
		'leave' => array(_("Attendance"), $empl_id),
		'payroll' => array(_("Payroll History"), $empl_id), 	
		'license' => array(_("License"), $empl_id),
		'loan' => array(_("Loan History"), $empl_id), 
		'attachments' => array(_("Attachments"), $empl_id),		
		'appraisal' => array(_("Appraisal"),$empl_id),	
		'increments' => array(_("Increments"), $empl_id),
		'education' => array(_("Education"), $empl_id),
		'skills' => array(_("Language"), $empl_id),
		'previous_emplment' => array(_("Employment History"), $empl_id),
		'training' => array(_("Training"), $empl_id),			
		'family' => array(_("Family"), $empl_id),				
		'termination' => array(_("Termination"), $empl_id),		
		'note' => array(_("Notes"), $empl_id)
		//'history' => array(_("Life 2 Date"), $empl_id)			
	);
if(!get_hrm_option('license_mgr'))
		unset($tab_cont_ar['license']);

tabbed_content_start('tabs', $tab_cont_ar);	
	switch (get_post('_tabs_sel')) {
		default:
		case 'personal':
			empl_personal_data($empl_id); 
			break;
		case 'job':			
			//empl_job_data($empl_id);	
			$_GET['empl_id'] = $empl_id;
			$_GET['popup'] = 1;
			include_once($path_to_root."/modules/ExtendedHRM/manage/add_empl_info_job.php");			
			break;
		case 'loan':			
			//empl_job_data($empl_id);	
			$_GET['empl_id'] = $empl_id;
			$_GET['page_level'] = 1;
			include_once($path_to_root."/modules/ExtendedHRM/manage/loan_form.php");			
			break;
		case 'education':
			$degree = new degree('degree', $empl_id, 'employee');
			$degree->show();

			break;
		case 'skills':
			$degree = new skill('skills', $empl_id, 'employee');
			$degree->show();	
			break;
		case 'training':
			$training = new training('training', $empl_id, 'employee');
			$training->show();
			break;
		case 'previous_emplment':
			$exp = new experience('previous_emplment', $empl_id, 'employee');
			$exp->show();
			break;
		case 'license':
			$exp = new license('license', $empl_id, 'employee');
			$exp->show();
			break; 
		case 'leave':
			empl_leave_data($empl_id); 
			break;
		case 'payroll':			
			empl_payroll_data($empl_id); 
			break;
		case 'increments':
			empl_increment_data($empl_id); 
			break;
		case 'attachments':
			$_GET['empl_id'] = $empl_id;
			$_GET['page_level'] = 1;
			include_once($path_to_root."/modules/ExtendedHRM/manage/attachments.php"); 
			break;
		case 'appraisal':
			$_GET['empl_id'] = $empl_id;
			$_GET['page_level'] = 1;
			br();
			include_once($path_to_root."/modules/ExtendedHRM/manage/appraisal.php"); 
			break;

		case 'family':
			$_GET['empl_id'] = $empl_id;
			$_GET['page_level'] = 1;
			include_once($path_to_root."/modules/ExtendedHRM/manage/family_data.php"); 
			break;
		case 'termination':
			empl_termination($empl_id); 
			break;
		case 'note':
			empl_notes($empl_id); 
			break;
		//case 'history':
			//empl_life_to_date_history($empl_id); 
			//break;
	}
br();
tabbed_content_end();
div_end();
end_form();
echo "<script type='text/javascript'> kvcodes_crm_nicEditor();  </script> \n";
end_page(@$_REQUEST['popup']);
function UploadHandle($empl_id){
		if (isset($_FILES['kv_attach_name']) && $_FILES['kv_attach_name']['name'] != '') {
			$max_image_size = 5000;
			$result = $_FILES['kv_attach_name']['error'];
			$upload_file = 'Yes'; 
			$attr_dir = company_path().'/attachments' ; 
			if (!file_exists($attr_dir)){				
				mkdir($attr_dir);
			}
			$dir = $attr_dir.'/empldocs/'.$empl_id.'/';
			if (!file_exists($dir)){
				mkdir($dir);
			}	
			/*$doc_ext = substr(trim($_FILES['kv_attach_name']['name']), strlen($_FILES['kv_attach_name']['name'])-3); 
			if($doc_ext == 'ocx' ) {
				$doc_ext = substr(trim($_FILES['kv_attach_name']['name']),strlen($_FILES['kv_attach_name']['name'])-4); 
			}*/
			$filename = basename($_FILES['kv_attach_name']['name']);
			$tmp = explode('.', $filename);
			$ext = strtolower(end($tmp));
			
			if(in_array($ext, array('docx','doc', 'pdf', 'jpg', 'jpeg', 'gif', 'png', 'bmp', 'rtf', 'txt'))){	
				
				$filesize = $_FILES['kv_attach_name']['size'];
				$filetype = $_FILES['kv_attach_name']['type'];
				
				$unique_name = $empl_id.'-'.$filename;

				if ( $filesize > ($max_image_size * 1024)) { //File Size Check
					display_warning(_('The file size is over the maximum allowed. The maximum size allowed in KB is') . ' ' . $max_image_size);
					$upload_file ='No';
				}elseif (file_exists($dir."/".$unique_name)){
					$result = unlink($dir."/".$unique_name);
					if (!$result) 	{
						display_error(_('The existing Bill could not be removed'));
						$upload_file ='No';
					}
				}else {
					$attach = GetRow('kv_empl_job', array('empl_id' => $empl_id));
					$attr_dir = company_path().'/attachments/empldocs/'.$attach['empl_id'].'/'.$attach['bond_doc']; 
					if($attach['bond_doc'] && file_exists($attr_dir) && !is_dir($attr_dir))
						unlink($attr_dir);
				}
					
				if ($upload_file == 'Yes'){
					$result = move_uploaded_file($_FILES['kv_attach_name']['tmp_name'], $dir."/".$unique_name);			
				}
				Update('kv_empl_job', array('empl_id' => $empl_id), array( 'bond_doc' => $unique_name));
			} else 
				display_error(_("The Selected File format is not supported, try files within this format (.jpg, png, doc,docx, rtf,pdf)"));
		}
	}
?>
<style>
#empl_profile_pic { border: 1px solid rgba(128, 128, 128, 0.68);    border-radius: 2px;}
td#kv_gross_amt {	color: #FF9800;    /*background-color: #f9f2bb; */ }
td#kv_ctc_amt{	color: #9C27B0;    /*background-color: rgba(156, 39, 176, 0.23); */ }
td#kv_net_amt{	color: #107B0F;   /* background-color: #B7DBC1; */}
td#kv_ded_amt{	color: #107B0F;   /* background-color: #f55; */}
ul.ajaxtabs li button {      padding: 3px 8px; } 
/*table { width: auto; }*/
table.tablestyle_noborder {    width: 70%;}
</style>