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

if (!@$_GET['popup']){
	page(_("PaySlip"));
} else
	page(_("Payslip"), true);

check_db_has_employees(sprintf(_("There is no employee in this system. Kindly Open '%s' to update it"), "<a href='".$path_to_root."/modules/ExtendedHRM/manage/employees.php'>"._("Add And Manage Employees")."</a>"));
 
check_db_has_salary_account(_("There are no Salary Account defined in this system. Kindly Open")."<a href='".$path_to_root."/modules/ExtendedHRM/manage/hrm_settings.php'>"._("Settings")."</a> "._("to update it."));

if(isset($_GET['Added'])){
	display_notification(_('The Employee Payslip is added #')." ".$_GET['Added']);
}
if(user_theme() == 'Saaisaran'){ ?>
<style>
@media (min-width: 900px){  table {  width: auto !important; } 	}
</style>
<?php }
$employee_id = get_post('employee_id', '');
$month = get_post('month','');
$current_year =  get_current_fiscalyear();
$year = get_post('year',$current_year['id']);
if(isset($_GET['payslip_id'])){
	$sal_row_direct = GetRow('kv_empl_salary', ['id' => $_GET['payslip_id']]);

	$employee_id = $_POST['employee_id'] = $sal_row_direct['empl_id'];
	$month = $_POST['month'] = $sal_row_direct['month'];
	$year = $_POST['year'] = $sal_row_direct['year'];
	$db_has_employee_payslip = true;
}

if (isset($_GET['employee_id'])){
	$employee_id = $_POST['employee_id'] = $_GET['employee_id'];
}
if (isset($_GET['month'])){
	$month = $_POST['month'] = $_GET['month'];
}
if (isset($_GET['year'])){
	$year = $_POST['year'] = $_GET['year'];
}

if(list_updated('month') || get_post('RefreshInquiry') || list_updated('employee_id')|| list_updated('year')) {
	$month = get_post('month');   
	//$_POST['lop_amount'] = 0;
	$Ajax->activate('totals_tbl');
}
if(list_updated('month') || list_updated('year') || list_updated('employee_id'))
	unset($_POST['lop_amount']);

$hrmsetup = get_hrm_option();
$home_nationality = $hrmsetup['home_nation'];
$_POST['ear_tot']= $_POST['payable_gross']=$_POST['deduct_tot']=$_POST['empl_dept']=$_POST['adv_sal']=$_POST['net_pay']=$ot_earnings=0;
if(!isset($_POST['lop_amount']))
	$_POST['lop_amount']= 0;
$dim = get_company_pref('use_dimension');
div_start('totals_tbl');
start_form();
	if (db_has_employees() && !isset($_GET['payslip_id'])) {
		start_table(TABLESTYLE_NOBORDER);
		start_row();
		kv_fiscalyears_list_cells(_("Fiscal Year").":", 'year', null, true);
		kv_current_fiscal_months_list_cell(_("Months"), "month", null, true, false,1);

		//0 - working days Start
		$months_with_years_list = kv_get_months_with_years_in_fiscal_year($year);
 		$ext_year = date("Y", strtotime($months_with_years_list[(int)get_post('month')]));	
		$payroll_monthly_choice =$hrmsetup['monthly_choice'];

 		if($month > 0 && $year > 0 ){
			if($payroll_monthly_choice == 1){
				$to = end_month(sql2date($months_with_years_list[(int)get_post('month')])); 
				$from = begin_month(sql2date($months_with_years_list[(int)get_post('month')])); 
				$total_days =  date("t", strtotime($ext_year."-".$month."-01"));
			} elseif($payroll_monthly_choice == 2){
				$total_days =  ((int)date("t", strtotime($ext_year."-".$month."-01"))-$hrmsetup['BeginDay'])+$hrmsetup['EndDay'];
				$nxt_mnth =  (($month < 12)? ($month+1) : 1);
				
				$from = sql2date(date('Y-m-d', strtotime($ext_year.'-'.$month.'-'.$hrmsetup['BeginDay'])));
				$to = sql2date(date('Y-m-d', strtotime($ext_year.'-'.$nxt_mnth.'-'.$hrmsetup['EndDay'])));
			}elseif($payroll_monthly_choice == 3){
				$pre_mnth = 0 ;
				$pre_mnth =  (($month > 1)? ($month-1) : 12);
						if($pre_mnth == 12 )
							$prev_ext_year = $ext_year-1;
						else
							$prev_ext_year = $ext_year;

						$total_days =  date("t", strtotime($prev_ext_year."-".$pre_mnth."-01"));
				
				$from = sql2date(date('Y-m-d', strtotime($prev_ext_year.'-'.$pre_mnth.'-'.$hrmsetup['BeginDay'])));
				$to = sql2date(date('Y-m-d', strtotime($ext_year.'-'.$month.'-'.$hrmsetup['EndDay'])));				
			}
		}
		//0 - working days End
		$db_has_employee_payslip = db_has_employee_payslip($employee_id, $month, $year);
		if($db_has_employee_payslip == true){
			if ($dim >= 1){
				dimensions_list_cells(_("Dimension")." 1", 'dimension_id', null, true, " ", false, 1);
				if ($dim > 1)
					dimensions_list_cells(_("Dimension")." 2", 'dimension2_id', null, true, " ", false, 2);
			}
			if ($dim < 1)
				hidden('dimension_id', 0);
			if ($dim < 2)
				hidden('dimension2_id', 0);
		}
		end_row();
		start_row();
		department_list_cells(_("Select a Department")." :", 'dept_id', null, _("No Department"), true, check_value('show_inactive'));
		employee_list_cells(_("Select an Employee")." :", 'employee_id', null,	_("Select Employee"), true, check_value('show_inactive'),false, false,true);	
		end_row();
		end_table();
		br();
		if (get_post('_show_inactive_update')) {
			$Ajax->activate('employee_id');
			$Ajax->activate('month');
			$Ajax->activate('year');
			set_focus('employee_id');
		}
	} 
	else {	
		hidden('employee_id');
		hidden('month');
		hidden('year');
		echo '<h4><center> Payslip #'.$_GET['payslip_id'].'</center></h4>';
	}
	$payslip_month = GetSingleValue('kv_empl_salary','month',array('year'=>get_post('year'),'empl_id' =>$_POST['employee_id']));
	if(isset($payslip_month) && $payslip_month > $_POST['month']){
			display_warning(_("You can't input payroll salary for older months when the system processed new months."));
			display_footer_exit();
	}
if(!isset($_GET['payslip_id']))
	$sal_row = get_empl_sal_details($employee_id, $month, $year); 
else
	$sal_row = $sal_row_direct;
if(get_post('employee_id')){
	$_POST['EmplName']=$_POST['desig']=''; 	
	$Empl_job_row =GetRow('kv_empl_job', array('empl_id' => get_post('employee_id')));
	$gross_lop = $Empl_job_row['gross'];
	$Empl_info_row =  GetRow('kv_empl_info', array('empl_id' => $employee_id));
	$empl_attendance_ar = array('joining' => $Empl_job_row['joining'], 'status' => $Empl_info_row['status'], 'date_of_status_change' => $Empl_info_row['date_of_status_change']);
	$Empl_grade = $Empl_job_row['grade'];
	hidden('grade_id', $Empl_grade);
	$Allowance  =  kv_get_allowances(null, 0, $Empl_grade);
	foreach($Allowance as $single) {	
		if($single['type']=='Earnings' && !isset($_POST[$employee_id.'_'.$single['id']])){
			$_POST[$employee_id.'_'.$single['id']] = 0;
		}
		if($single['type']=='Reimbursement' && !isset($_POST[$employee_id.'_'.$single['id']])){
			$_POST[$employee_id.'_'.$single['id']] = 0;
		}
		if($single['type']=='Deductions' && !isset($_POST[$employee_id.'_'.$single['id']])){
			$_POST[$employee_id.'_'.$single['id']] = 0;
		}
		if($single['type']=='Employer Contribution' && !isset($_POST[$employee_id.'_'.$single['id']])){ 
			$_POST[$employee_id.'_'.$single['id']] = 0;
		}					
	}
	$pf_amt_actual = $gross_4_LOP = $ctc_final = 0; 
 	$months_with_years_list = kv_get_months_with_years_in_fiscal_year($year);
 	// display_error(json_encode($months_with_years_list));
 	//$total_working_hours =  Get_Monthly_WorkingHours($year, get_post('month'), true);
 	if(!isset($_GET['payslip_id']))
 	$duration  = GetEmplAttendanceDuration($employee_id,null,null, (int)get_post('month'), $year,-1,-1, ($Empl_info_row['status'] > 1 ? sql2date($Empl_info_row['date_of_status_change']) : null),$Empl_job_row['weekly_off']);
 	if(!empty($duration))
		$employee_Lop_hours = $duration[0]['total_hrs'] - ($duration[0]['Duration']+$duration[0]['off_days']);
	else
		$employee_Lop_hours = 0;
	
	$workedHours  = $otHours = $SplotHours = 0 ;
	if(!empty($duration)){
		foreach($duration as $key => $single){
			$workedHours += $single['Duration'];			
			$otHours += $single['OT'];
			$SplotHours += $single['SOT'];
		}
	}

 	$joining_date = $Empl_job_row['joining'];
 	$month_name = kv_month_name_by_id(get_post('month'));
	$end_of_selected_month = end_month(sql2date($months_with_years_list[(int)get_post('month')])); 
	$ext_year = date("Y", strtotime($months_with_years_list[(int)get_post('month')]));

	if($hrmsetup['monthly_choice'] == 2){
		$secondMonth = $month+1;
	} elseif($hrmsetup['monthly_choice'] == 3) {				
		$secondMonth = $month;
	} else {
		$secondMonth = $month;
	}
			
	$payroll_process_end = date("Y-m-d", strtotime($ext_year."-".$secondMonth."-".$hrmsetup['EndDay']));

		$_POST['today_date']=date("d-F-Y");

		if(isset($employee_id) && $employee_id != '' && date2sql($end_of_selected_month) >= $joining_date && ($Empl_info_row['status'] == 1 || ($Empl_info_row['status']>1 && $Empl_info_row['date_of_status_change'] >= date2sql($end_of_selected_month) ) )) {
			$_POST['empl_dept']=GetSingleValue('kv_empl_departments', 'description', array('id' => $Empl_job_row['department']));
			$_POST['desig'] = $Empl_job_row['desig'];
			$_POST['EmplName']=$Empl_info_row ['empl_firstname'].' '.$Empl_info_row['empl_lastname'];
			$end_of_selected_month = end_month(sql2date($months_with_years_list[(int)get_post('month')])); 
			$begin_this_month = begin_month(sql2date($months_with_years_list[(int)get_post('month')])); 
			$gross_4_LOP = $ctc_cal = $Reimbursement = $basic_id = $gross_calculation = 0 ;
			$_POST['lop_amount'] = 0;
			if(!isset($sal_row['net_pay'])){
				if(!isset($_POST['lop_amount']) || $_POST['lop_amount'] == 0){
					if(isset($duration[0]['total_hrs']) && $duration[0]['total_hrs'] > 0 ){		
							
						if($duration[0]['total_hrs'] == $employee_Lop_hours){
							$_POST['lop_amount'] = round($Empl_job_row['gross'], 2);							
						}	else {					
							$_POST['lop_amount'] = round((($Empl_job_row['gross']/$duration[0]['total_hrs'])*abs($employee_Lop_hours)), 2);						
						}
					} else
						$_POST['lop_amount'] = $Empl_job_row['gross'];							
				}
			}
			$_POST['payable_grosss'] = $Empl_job_row['gross'];
			$_POST['net_gross'] = $Empl_job_row['gross']- $_POST['lop_amount'];
			$Empl_job_row['gross'] = $_POST['net_gross'];
			$allowance_var_ar = array();
			$basic_allowance =0;
			foreach($Allowance as $single) {	
				if(!isset($sal_row['net_pay'])){			
					if($single['al_type'] == 0 ){
						$allowance_var_ar[$employee_id.'_'.$single['id']] = '{$'.$single['unique_name'].'}';
						if(!isset($sal_row['net_pay'])){
							if($single['formula'] == '' && $single['value'] == 'Percentage' && $single['percentage']>0){			
								$_POST[$employee_id.'_'.$single['id']] = input_num($employee_id.'_'.$basic_id)*($single['percentage']/100);
							}elseif($single['value'] == 'Gross Percentage' && $single['percentage']>0){			
								$_POST[$employee_id.'_'.$single['id']] = $Empl_job_row['gross']*($single['percentage']/100);
							}elseif($single['formula'] != '' && is_numeric($single['formula'])) {
								$_POST[$employee_id.'_'.$single['id']] = $single['formula'];					
							}
						} else {

							if($single['type']=='Earnings'){
								
								if( (isset($sal_row[$single['id']]) && $sal_row[$single['id']] > 0))	
									$_POST[$employee_id.'_'.$single['id']] = ((isset($sal_row[$single['id']]) && $sal_row[$single['id']] > 0 ) ? $sal_row[$single['id']] : (isset($_POST[$employee_id.'_'.$single['id']]) ? $_POST[$employee_id.'_'.$single['id']] : 0 ));				
							}
							if($single['type']=='Reimbursement'){
								$allowance_var_ar[$employee_id.'_'.$single['id']] = '{$'.$single['unique_name'].'}';
								if((isset($sal_row[$single['id']]) && $sal_row[$single['id']] > 0))	
									$_POST[$employee_id.'_'.$single['id']] = ((isset($sal_row[$single['id']]) && $sal_row[$single['id']] > 0 ) ? $sal_row[$single['id']] : (isset($_POST[$employee_id.'_'.$single['id']]) ? $_POST[$employee_id.'_'.$single['id']] : 0 ));
							}
							if($single['type']=='Deductions'){
								$allowance_var_ar[$employee_id.'_'.$single['id']] = '{$'.$single['unique_name'].'}';
								if((isset($sal_row[$single['id']]) && $sal_row[$single['id']] > 0))	
									$_POST[$employee_id.'_'.$single['id']] = ((isset($sal_row[$single['id']]) && $sal_row[$single['id']] > 0 ) ? $sal_row[$single['id']] : (isset($_POST[$employee_id.'_'.$single['id']]) ? $_POST[$employee_id.'_'.$single['id']] : 0 ));
							}
							if($single['type']=='Employer Contribution'){ 
								$allowance_var_ar[$employee_id.'_'.$single['id']] = '{$'.$single['unique_name'].'}';
								if( (isset($sal_row[$single['id']]) && $sal_row[$single['id']] > 0))	
									$_POST[$employee_id.'_'.$single['id']] = ((isset($sal_row[$single['id']]) && $sal_row[$single['id']] > 0 ) ? $sal_row[$single['id']] : (isset($_POST[$employee_id.'_'.$single['id']]) ? $_POST[$employee_id.'_'.$single['id']] : 0 ));
							}	
						}
						if(!empty($duration) && $duration[0]['Duration'] == 0 && ($single['esic'] == 1 || $single['pf'] == 1))  //ESIC and PF will be 0 for full month absents.
							$_POST[$employee_id.'_'.$single['id']] = 0 ;
						if($single['basic'] == 1) {
							$basic_id = $single['id'];
						}				
						
						if($single['pf'] == 1){
							if($single['type'] == 'Earnings')
								$pf_amt_actual = $_POST[$employee_id.'_'.$single['id']];
							if($single['type'] == 'Reimbursement')
								$pf_amt_actual = $_POST[$employee_id.'_'.$single['id']];
							if($single['type'] == 'Employer Contribution')
								$pf_amt_actual = $_POST[$employee_id.'_'.$single['id']];
							if($single['type'] == 'Deductions')
								$pf_amt_actual = $_POST[$employee_id.'_'.$single['id']];
						}	

						if($single['loan'] == 1 && !isset($sal_row['net_pay'])) {
							$loans = GetDataJoinRow('kv_empl_loan_types AS type', array( 
									0 => array('join' => 'INNER', 'table_name' => 'kv_empl_loan AS loan', 'conditions' => '`type`.`id` = `loan`.`loan_type_id`'),
									1 => array('join' => 'INNER', 'table_name' => 'kv_empl_allowances AS info', 'conditions' => '`type`.`allowance_id` = `info`.`id`'), 	
									), 
									array('`loan`.`monthly_pay`, `loan`.`start_date`, `loan`.`periods_paid` , `loan`.`periods`, `loan`.`id`'), array('`loan`.`empl_id`' => $employee_id, '`info`.`id`' => $single['id'], '`loan`.`status`' => "0"));
							//display_notification($loans['date'] .'<='. $months_with_years_list[(int)get_post('month')]);
							// display_error(json_encode($loans['start_date']));
							if(!empty($loans) && $loans['periods_paid'] < $loans['periods'] && strtotime(date('Y-m-01', strtotime($loans['start_date']))) <= strtotime($months_with_years_list[(int)get_post('month')]) ){
								// display_error(json_encode($loans));
								$_POST[$employee_id.'_'.$single['id']] = (isset($_POST[$employee_id.'_'.$single['id']]) ? $_POST[$employee_id.'_'.$single['id']] : 1); //$loans[0]['monthly_pay'];	
								$_POST['loan_'.$single['id']] = $loans['id'];
								$_POST['loan_mnth_pay_'.$single['id']] = $loans['monthly_pay'];		
								hidden('loan_'.$single['id'], $_POST['loan_'.$single['id']]);
								hidden('loan_mnth_pay_'.$single['id'], $_POST['loan_mnth_pay_'.$single['id']]);
							}					
						}  

						if($single['Tax'] == 1 && !isset($sal_row['net_pay'])) {
							$_POST[$employee_id.'_'.$single['id']] = kv_get_tax_for_an_employee($single['id'], $employee_id, get_post('year'), $Empl_job_row['gross'], get_post('month'));	
						}
						if($single['value'] == 'Function'){
								$_POST[$employee_id.'_'.$single['id']] = 0;		
						}
					}elseif($single['al_type']==1){  // LMRA Calculation	
													
								$amount =GetRow('kv_empl_lmra_fees',  array('nationality' => $Empl_job_row['nationality'])); 
								if(!empty($amount))
									$_POST[$employee_id.'_'.$single['id']] = $amount['amount'];
								elseif($amount2 =  GetSingleValue('kv_empl_lmra_fees', 'amount', array('nationality' => 0)))
									$_POST[$employee_id.'_'.$single['id']] = $amount2;
								else
									$_POST[$employee_id.'_'.$single['id']] = 0 ;
					}elseif($single['al_type']==3){  // Medical Allowance
								$medi_category= GetSingleValue('kv_empl_medical_premium', 'month', array('id' => $Empl_job_row['medi_category'])); 
								if($medi_category)
									$_POST[$employee_id.'_'.$single['id']] = $medi_category;
								else
									$_POST[$employee_id.'_'.$single['id']] = null;
					} elseif($single['al_type']==4){	// Visa and immgration
								$visa_details= GetRow('kv_empl_visa_exp', array('nationality' => $Empl_job_row['nationality'], 'family' => $Empl_job_row['family']));							
								if ($visa_details){  
									$_POST[$employee_id.'_'.$single['id']] = $visa_details['month'];
								}else {
									$_POST[$employee_id.'_'.$single['id']] = GetSingleValue('kv_empl_visa_exp', 'month', array('nationality' => 0, 'family' => $Empl_job_row['family']));
								}
					} elseif($single['al_type']==5){ //Leave Travel
								$leave_travel= GetRow('kv_empl_leave_travel', array('nationality' => $Empl_job_row['nationality'], 'family' => $Empl_job_row['family']));
								if ($leave_travel){  
									$_POST[$employee_id.'_'.$single['id']] = $leave_travel['month'];
								}else {
									$_POST[$employee_id.'_'.$single['id']] = GetSingleValue('kv_empl_leave_travel', 'month', array('nationality' => 0, 'family' => $Empl_job_row['family']));
								}
					} elseif($single['al_type']==6){   // Leave Salary 
								$ALDays = ($Empl_job_row['al']/12);
								
								$amt_for_cal = 0 ;
									foreach($Allowance as $singl) {									
										if( !empty($hrmsetup['leave_pay']) && in_array($singl['id'], $hrmsetup['leave_pay']))
											$amt_for_cal += $_POST[$employee_id.'_'.$singl['id']] ;
									}								
									if($amt_for_cal==0)
										$amt_for_cal = $gross_calculation;								
									
								$_POST[$employee_id.'_'.$single['id']] =((($amt_for_cal*12)/365)*$ALDays);
								if(date2sql($begin_this_month) < $Empl_job_row['joining']){
									$days = 30 - (int)date('d', strtotime($Empl_job_row['joining']));								
									$ALDays = ($ALDays/30)*$days;
									$_POST[$employee_id.'_'.$single['id']] =((($amt_for_cal*12)/365)*($ALDays));
								} 
								if(!isset($sal_row['net_pay']) && $Empl_info_row['status']>1 && $Empl_info_row['date_of_status_change'] > date2sql($begin_this_month) && $Empl_info_row['date_of_status_change'] < date2sql($end_of_selected_month) ) {
									$days = (int)date('d', strtotime($Empl_info_row['date_of_status_change']));								
									$ALDays = ($ALDays/30)*$days;
									$_POST[$employee_id.'_'.$single['id']] =((($amt_for_cal*12)/365)*($ALDays));
								}
					} elseif($single['al_type']==7){   // Indemnity
								if($home_nationality  != $Empl_job_row['nationality']){
									$date1 = new DateTime($Empl_job_row['joining']);
									$date2 = new DateTime(date('Y-m-d'));
									$interval = $date1->diff($date2);
									$years_exp = $interval->y + ($interval->m/12) + ($interval->d/365);							
									$cal_days = (($years_exp > 3) ? 30 : 15 );
									$amt_for_cal = 0 ;
									foreach($Allowance as $singl) {									
										if( !empty($hrmsetup['indemnity']) && in_array($singl['id'], $hrmsetup['indemnity']))
											$amt_for_cal += $_POST[$employee_id.'_'.$singl['id']] ;
									}								
									if($amt_for_cal==0)
										$amt_for_cal = $gross_calculation;
									$_POST[$employee_id.'_'.$single['id']] =((($amt_for_cal*12)/365)*$cal_days)/12;								
								} else {
									$_POST[$employee_id.'_'.$single['id']] = 0;
								}
					} elseif($single['al_type'] == 2) {
								if((!isset($_POST[$employee_id.'_'.$single['id']]) || $_POST[$employee_id.'_'.$single['id']] == '')){ //GOSI Calculation
									
									$gosi_emplee= GetRow('kv_empl_gosi_settings', array('nationality' => $Empl_job_row['nationality']));
									if(empty($gosi_emplee))
										$gosi_emplee =  GetRow('kv_empl_gosi_settings', array('nationality' => 0));
									$gosi_cal_amt = 0 ;
									$gosi_al = unserialize(base64_decode($gosi_emplee['allowances']));
									if(!empty($gosi_al)){									
										foreach($gosi_al as $singl){
											$gosi_cal_amt += input_num($employee_id.'_'.$singl);
										}
									} 
									if($gosi_cal_amt == 0 )
										$gosi_cal_amt = $gross_calculation; 
									
									if($single['type']=='Deductions' ){									
										if ($gosi_emplee){  							
											$_POST[$employee_id.'_'.$single['id']] = $gosi_cal_amt * ($gosi_emplee['employee']/100);
										}else {  	
											$_POST[$employee_id.'_'.$single['id']] = $gosi_cal_amt * ($gosi_emplee['employee']/100);
										}
									}	elseif( $single['type']=='Employer Contribution' ){									
										if ($gosi_emplee){  							
											$_POST[$employee_id.'_'.$single['id']] = $gosi_cal_amt * ($gosi_emplee['employer']/100);
										} else {  
											$_POST[$employee_id.'_'.$single['id']] = $gosi_cal_amt * ($gosi_emplee['employer']/100);
										}
									}
									// display_error($_POST[$employee_id.'_'.$single['id']].json_encode($gosi_emplee));
								} 
					}
				} else {
					$_POST[$employee_id.'_'.$single['id']] = $sal_row[$single['id']];
				}
			
				if($single['type'] == 'Earnings' && $single['value'] != 'Payroll Input'){
					$gross_4_LOP += input_num($employee_id.'_'.$single['id']);
					
				}
				if($single['type']=='Earnings')
						$gross_calculation  += input_num($employee_id.'_'.$single['id']);
				if($single['type'] == 'Reimbursement') { 
					$Reimbursement += input_num($employee_id.'_'.$single['id']);
				}
				if( $single['type'] == 'Employer Contribution' ){  
					$ctc_cal += input_num($employee_id.'_'.$single['id']);
				}	
				if($single['basic'] == 1)	
						$basic_allowance = input_num($employee_id.'_'.$single['id']);
			}
			foreach($Allowance as $single) {
				$yes = false;
				if($single['type'] == 'Earnings'  && $_POST[$employee_id.'_'.$single['id']] < 1)
					$yes =true; 
				if($single['type'] == 'Deductions'  && $_POST[$employee_id.'_'.$single['id']] < 1)
					$yes =true; 
				if($single['type'] == 'Reimbursement'  && $_POST[$employee_id.'_'.$single['id']] < 1)
					$yes =true; 
				if($single['type'] == 'Employer Contribution'  && $_POST[$employee_id.'_'.$single['id']] < 1)
					$yes =true; 

				if($single['value'] == 'Formula' && $single['formula'] != '' && !isset($sal_row['net_pay']) && !is_numeric($single['formula']) && $yes && (strpos($single['formula'], '{$ctc}') === false)){

					foreach($allowance_var_ar as $key => $allown){
						if(isset($_POST[$key]))
						$single['formula'] = str_replace($allown,$_POST[$key],strtolower($single['formula']));
					}

					if (strpos($single['formula'], '{$gros}') !== false) {					 	
					 	$single['formula'] = str_replace('{$gros}', $_POST['net_gross'] ,strtolower($single['formula']));
					}if (strpos($single['formula'], '{$grlp}') !== false) {					 	
					 	$single['formula'] = str_replace('{$grlp}', $_POST['net_gross'] ,strtolower($single['formula']));
					}
					if (strpos($single['formula'], '{$ctc}') !== false) {					 	
					 	$single['formula'] = str_replace('{$ctc}', $ctc_final ,strtolower($single['formula']));
					}

					if($single['type'] == 'Earnings')							
						$_POST[$employee_id.'_'.$single['id']] = round(calculate_string($single['formula']),2);	

					if($single['type'] == 'Employer Contribution')							
						$_POST[$employee_id.'_'.$single['id']] = round(calculate_string($single['formula']),2);	

					if($single['type'] == 'Reimbursement')							
						$_POST[$employee_id.'_'.$single['id']] = round(calculate_string($single['formula']),2);	

					if($single['type'] == 'Deductions')							
						$_POST[$employee_id.'_'.$single['id']] = round(calculate_string($single['formula']),2);	
							
				}

				if(($Empl_job_row['empl_type'] != 1 && $Empl_job_row['empl_type'] != 3 ) && ($single['esic'] == 1 || $single['pf'] == 1 || $single['Tax'] == 1 )){
					$_POST[$employee_id.'_'.$single['id']] = 0;
				}

				if($single['type'] == 'Earnings' && $single['value'] != 'Payroll Input'){
					$gross_4_LOP += input_num($employee_id.'_'.$single['id']);
					
				}
				if($single['type']=='Earnings')
						$gross_calculation  += input_num($employee_id.'_'.$single['id']);
				if($single['type'] == 'Reimbursement') { 
					$Reimbursement += input_num($employee_id.'_'.$single['id']);
				}
				if( $single['type'] == 'Employer Contribution' ){  
					$ctc_cal += input_num($employee_id.'_'.$single['id']);
				}	
				if($single['basic'] == 1)	
						$basic_allowance = input_num($employee_id.'_'.$single['id']);

			}
			//$basic_allowance = input_num('149_4');	 
			if($gross_4_LOP > 0 )
				$gross_amt = $gross_4_LOP;
			else
				$gross_amt = $Empl_job_row['gross'];
			$ctc_final = $ctc_cal + $gross_amt+ $Reimbursement;	
					
			if(isset($sal_row['net_pay'])){
				$_POST['lop_amount'] =  $sal_row['lop_amount'];
				$_POST['adv_sal']= $sal_row['adv_sal'];
				$_POST['net_pay'] = $sal_row['net_pay'];		 
				$ot_earnings = $sal_row['ot_earnings'];			 
				$_POST['today_date'] = $sal_row['date'];					
				//$_POST['loan'] = $sal_row['loan'] ;
			} else{
				$advance_salary = GetAll('kv_empl_salary_advance', array('empl_id' => $employee_id));
				if(is_array($advance_salary)) {
					foreach($advance_salary as $ad_v_sal){		
						//display_error(json_encode($duration).'__'.$duration[0]['from'].'__'.$duration[0]['to']);		
						if(date2sql($from) < $ad_v_sal['date'] && $ad_v_sal['date'] < date2sql($to)){
							$_POST['adv_sal']= $ad_v_sal['amount'];
							$_POST['adv_date']= $ad_v_sal['date'];
						}
					}
				}							
				$basic_amount = ($basic_id ? $Empl_job_row[$basic_id] : 0 );
				$ot_mul_factor =$hrmsetup['ot_factor'];

				if(!empty($duration) && $duration[0]['days_count'] > 0 )
					$days_count = $duration[0]['days_count'];
				else					
					$days_count = 30; 
			
				$shift_time = GetRow('kv_empl_shifts', array('id' => $Empl_job_row['shift']));
				if(!empty($shift_time)){
					$BeginTime = $shift_time['BeginTime'];
					$EndTime = $shift_time['EndTime'];
				} else {
					$BeginTime = $hrmsetup['BeginTime'];
					$EndTime = $hrmsetup['EndTime'];
				}
				if((strtotime($EndTime)-strtotime($BeginTime)) < 0){
					$attendance_date_plus_1 = date2sql(add_days(Today(), 1));
					$EndTime  = $attendance_date_plus_1.' '.$EndTime; 
				}	
				//SplitHours
				if($basic_allowance > 0){
    				$ot_earnings = round((((int)$hrmsetup['ot_factor']) * (($basic_allowance/$days_count)/(strtotime($EndTime)-strtotime($BeginTime)))*$otHours),2);
    				$ot_earnings += round((((float)$hrmsetup['special_ot_factor']) * (($basic_allowance/$days_count)/(strtotime($EndTime)-strtotime($BeginTime)))*$SplotHours),2);
				}else
				    $ot_earnings = 0;
				    
				$_POST['net_gross'] += $ot_earnings;
			}				
		}else{
			if($months_with_years_list[(int)get_post('month')] < $joining_date)
				display_warning(_("You can't Pay Employee Salary before his Joining Date!"));
		}		
		$gross_4_grand = 0 ;
		foreach($Allowance as $single) {	
			if($single['type'] == 'Earnings' ){
				$gross_4_grand += (float)round(input_num($employee_id.'_'.$single['id']), 3);	
			}								
		}		
		$_POST['ear_tot'] = $ot_earnings+round($gross_4_grand, 3);		
		if(!isset($sal_row['net_pay'])){
			if($duration == true){
				hidden('from_a_date',$duration[0]['from']);
				hidden('to_a_date',$duration[0]['to']);
				hidden('used_al',$duration[0]['al']);
				hidden('used_sl',$duration[0]['sl']);
				hidden('used_ml',$duration[0]['ml']);
				hidden('days',$duration[0]['days']);
			}else{
				hidden('from_a_date',$from);
				hidden('to_a_date',$to);
				hidden('used_al',0);
				hidden('used_sl',0);
				hidden('used_ml',0);
				hidden('days',0);
			}
		} else {
			 $workedHours = $sal_row['pay_hrs'];
			 $otHours = $sal_row['ot_hrs'];
			 $SplotHours = $sal_row['spl_ot_hrs'];
		}		
		start_outer_table(TABLESTYLE);
		table_section(1);
		label_row(_("Employee No").":", $employee_id);
		label_row(_("Employee Name").":",  '<a target="_blank" onclick="javascript:openWindow(this.href,this.target); return false;" href="'.$path_to_root.'/modules/ExtendedHRM/manage/employees.php?empl_id='.$Empl_job_row['empl_id'].'" >'.$_POST['EmplName'].'</a>' );
		label_row(_("Department").":", $_POST['empl_dept']);
		label_row(_("Designation").":", GetSingleValue('kv_empl_designation', 'description', array('id' => $_POST['desig'])));
		label_row(_("Month of Payment").":", '<a target="_blank" href="'.$path_to_root.'/modules/ExtendedHRM/inquires/attendance_inquiry.php?month='.$month.'&selected_id='.$Empl_job_row['department'].'&empl_id='.$employee_id.'"> '.$month_name.'</a>');
		if(isset($sal_row['currency']) && $sal_row['currency'] != ''){
			$curr_code =  $sal_row['currency'];
			$ex_dat = (isset($sal_row['date']) ? sql2date($sal_row['date']) : Today());
			$ex_rate = number_format(get_exchange_rate_from_home_currency($curr_code, $ex_dat), 4);
		} else{
			$curr_code = get_company_currency();
			$ex_rate = 1; 
		} 
		label_row(_("Currency").":", GetSingleValue('currencies', 'currency', array('curr_abrev' => $curr_code)));
		hidden('currency', $curr_code);
if(isset($_POST['payable_grosss']) && $_POST['payable_grosss'] != '')
		label_row(_("Gross Salary").":", price_format($_POST['payable_grosss']), '', ' style=" text-align:right;" '); //
		if(!isset($sal_row['net_pay']))
			amount_row(_("Absent Deduction").":", 'lop_amount', null, null, null, null, true);
		else
			label_row(_("Absent Deduction"), price_format($_POST['lop_amount']), '', ' style=" text-align:right;" ');
if(isset($_POST['net_gross']) && $_POST['net_gross'] != '' && !isset($sal_row['net_pay'])){
		label_row(_("Gross after LOP").":", price_format($_POST['net_gross']), 'style="color:#FF9800; background-color:#f9f2bb;"', 'style="color:#FF9800; background-color:#f9f2bb;text-align:right"');	
		hidden('gross_for_cal', $_POST['net_gross']);
} else 
if(isset($_POST['lop_amount']) && $_POST['lop_amount'] !='')
	label_row(_("Gross after LOP").":", price_format($_POST['payable_grosss']-$_POST['lop_amount']), 'style="color:#FF9800; background-color:#f9f2bb;"', 'style="color:#FF9800; background-color:#f9f2bb;text-align:right"');	
		table_section_title(_("Earnings"));
		foreach($Allowance as $single) {	
			if($single['type'] == 'Earnings' ){
				if($single['value'] == 'Payroll Input' && $single['basic'] != 1){
					if(isset($sal_row['net_pay']))
						label_row(_($single['description']), price_format($_POST[$employee_id.'_'.$single['id']]), '', ' style=" text-align:right;" ');
					else
						amount_row(_($single['description']), $employee_id.'_'.$single['id'], null, null, null, null, true);
				}elseif($_POST[$employee_id.'_'.$single['id']] == ($_POST[$employee_id.'_'.$single['id']] >-$_POST[$employee_id.'_'.$single['id']])){
					label_row(_($single['description']), price_format($_POST[$employee_id.'_'.$single['id']]), '', ' style=" text-align:right;" ');
				}
			} 
		}
		label_row(_("OT Earnings").":", price_format($ot_earnings), '', ' style=" text-align:right;" ');
		hidden('ot_earnings', $ot_earnings);
		$_POST['payable_grosss'] = $_POST['ear_tot'];
		
		$reimburse = 0; 
		table_section_title(_("Benefits"));
		foreach ($Allowance as $single) {
			if($single['type'] == 'Benefits' ){	
				if(!isset($sal_row['net_pay']) && $single['value'] == 'Payroll Input')
					amount_row(_($single['description']), $employee_id.'_'.$single['id'], null, null, null, null, true);
				else
					label_row(_($single['description']), price_format($_POST[$employee_id.'_'.$single['id']]), '', ' style=" text-align:right;" ');
				$reimburse += input_num($employee_id.'_'.$single['id']);
			}
		}		
		//$_POST['payable_gross'] = $_POST['ear_tot']+ $reimburse;
		label_row(_("Total Benefits").":", price_format($reimburse), 'style="color:#FF9800; background-color:#f9f2bb;"', 'style="color:#FF9800; background-color:#f9f2bb;text-align:right"');	
	//	hidden('gross_for_cal', $_POST['payable_gross']);
		table_section_title(_(" "));

		$empl_contribution = 0;
		table_section_title(_("Employer Contribution"));
		foreach ($Allowance as $single) {
			if($single['type'] == 'Employer Contribution' ){  
				//if($single['esic'] != 1 && $single['pf'] != 1){
					if(!isset($sal_row['net_pay']) && $single['value'] == 'Payroll Input')
						amount_row(_($single['description']), $employee_id.'_'.$single['id'], null, null, null, null, true);
					else
						label_row(_($single['description']), price_format($_POST[$employee_id.'_'.$single['id']]), '', ' style=" text-align:right;" ');
					$empl_contribution += input_num($employee_id.'_'.$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);text-align:right;"');
		
		label_row(_('Overall CTC '), price_format($empl_contribution+$_POST['ear_tot']+$reimburse), 'style="color:#9C27B0; background-color:rgba(156, 39, 176, 0.23);"', 'style="color:#9C27B0; background-color:rgba(156, 39, 176, 0.23);text-align:right;"');
		table_section(2);
		hidden('ctc', $empl_contribution+$_POST['ear_tot']+$reimburse);
		label_row(_("Date of Payslip").":", date("d-F-Y", strtotime($_POST['today_date'])));
		label_row(_("Grade").":", '<a target="_blank" onclick="javascript:openWindow(this.href,this.target); return false;" href="'.$path_to_root.'/modules/ExtendedHRM/manage/allowances.php?grade_id='.$Empl_job_row['grade'].'" >'.GetSingleValue('kv_empl_grade', 'description', array('id' => $Empl_job_row['grade'])).'</a>');
		//label_row(_("Total No of days").":", $duration[0]['total_days']);
		hidden('workedHours', $workedHours);
		hidden('otHours', $otHours);
		hidden('SplotHours', $SplotHours);		
		$hours = floor($workedHours / 3600);
		$mins = floor($workedHours / 60 % 60);
		$employee_working_hours_display = ($hours < 10 ? '0'.$hours : $hours).':'.($mins < 10 ? '0'.$mins : $mins); 
		$ot_hours = floor($otHours / 3600);
		$ot_mins = floor($otHours / 60 % 60);
		$employee_OT_hours_display = ($ot_hours < 10 ? '0'.$ot_hours : $ot_hours).':'.($ot_mins < 10 ? '0'.$ot_mins : $ot_mins);
				
		label_row(_("Payable Hours").":", $employee_working_hours_display);
		label_row(_("OT Hours").":", $employee_OT_hours_display);		
		$sot_hours = floor($SplotHours / 3600);
		$sot_mins = floor($SplotHours / 60 % 60);
		$employee_sOT_hours_display = ($sot_hours < 10 ? '0'.$sot_hours : $sot_hours).':'.($sot_mins < 10 ? '0'.$sot_mins : $sot_mins);
		
		label_row(_("Special OT Hours").":", $employee_sOT_hours_display);	
		if(!isset($sal_row['net_pay']) && !empty($duration))			
			label_row(_("Days Worked").":", $duration[0]['days'].' days');	
		else{
			$sal_row['days_worked'] = isset($sal_row['days_worked']) ? $sal_row['days_worked'] : 0;
			label_row(_("Days Worked").":", $sal_row['days_worked'].' days');	
		}
					
	    label_row(_("Exchange Rate").":", number_format2($ex_rate,4));
	    hidden('rate', $ex_rate); 
		table_section_title(_("Deduction"));		
		$deduct_tot = 0 ;		 
		foreach($Allowance as $single) {
			if($single['type'] == 'Deductions'){
					if(!isset($sal_row['net_pay']) && $single['value'] == 'Payroll Input' && $single['loan'] != 1){
						amount_row($single['description'], $employee_id.'_'.$single['id'], null, null, null, null, true);
						$deduct_tot += input_num($employee_id.'_'.$single['id']);
					} elseif( $single['loan'] != 1 || isset($sal_row['net_pay'])){
						label_row(_($single['description']), price_format($_POST[$employee_id.'_'.$single['id']]), '', ' style=" text-align:right;" ');
						$deduct_tot += $_POST[$employee_id.'_'.$single['id']];
					} elseif(isset($_POST['loan_mnth_pay_'.$single['id']])) {
						kv_loan_balance_dropdown_row($single['description'], $employee_id.'_'.$single['id'], get_post('loan_'.$single['id']), false, true);
						$deduct_tot += $_POST[$employee_id.'_'.$single['id']]*$_POST['loan_mnth_pay_'.$single['id']];
						$periods_cot= $_POST[$employee_id.'_'.$single['id']];
						if(list_updated($employee_id.'_'.$single['id']))
							$Ajax->activate('totals_tbl');
					}	
			}
		}
		label_row(_("Advance Salary").":", price_format($_POST['adv_sal']), '', ' style=" text-align:right;" ');	
		hidden('adv_sal', $_POST['adv_sal']);
		if(!isset($sal_row['net_pay'])){
			submit_cells('RefreshInquiry', _("Refresh"),'',_('Show Results'), 'default');
		}		
		table_section_title(_(" "));
		$deduct_tot += $_POST['adv_sal'];	
		label_row(_("Total Deductions"), price_format($deduct_tot), 'style="color:#f55; background-color:#fed;"', 'style="color:#f55; background-color:#fed;text-align:right;"');
		label_row(_(" "), '', null, 30, 30);
		if(!isset($sal_row['net_pay'])){
			if(isset($_POST['net_gross']))
			$_POST['net_pay'] = $_POST['net_gross']-$deduct_tot + $reimburse;
		}		
		label_row(_("Net Salary Payable").":", price_format($_POST['net_pay']), 'style="color:#107B0F; background-color:#B7DBC1;"', 'style="color:#107B0F; background-color:#B7DBC1;text-align:right;"');
		end_outer_table();
		
		if($db_has_employee_payslip == false && $employee_id != null){
			br(2);		
			foreach($Allowance as $single) {	
				if($single['type'] == 'Deductions')
					hidden($single['id'], $_POST[$employee_id.'_'.$single['id']]);
			}
			hidden('net_pay', $_POST['net_pay']);
			if($payroll_process_end < date('Y-m-d'))
					submit_center('pay_salary', _("Process Payout"), true, _('Payout to Employees'), 'default');
			else
				display_warning(_("You can't Process Payroll of future!"));
			br();
			end_form();
		}
		if($db_has_employee_payslip == true && $employee_id != null){
			br(2);
			if(!isset($sal_row['id'])){
				echo "<p><center>"._("No general ledger transactions have been created for")."</center></p><br>";
				end_page(true);
				exit;
			}
			$result = get_gl_trans(ST_EMPLOYEE_SALARY, $sal_row['id']);
			hidden('payslip_id', $sal_row['id']);
			//submit_center('DeletePayslip', _("Delete"), true, _('Delete Payslip'), 'default');
			if (db_num_rows($result) == 0){
				echo "<p><center>"._("No general ledger transactions have been created for")."</center></p><br>";
				end_page(true);
				exit;
			}
			/*show a table of the transactions returned by the sql */
			$dim = get_company_pref('use_dimension');

			if ($dim == 2)
				$th = array(_("Account Code"), _("Account Name"), _("Dimension")." 1", _("Dimension")." 2", _("Debit"), _("Credit"), _("Memo"));
			else if ($dim == 1)
				$th = array(_("Account Code"),_("Account Name"),_("Dimension"),_("Debit"),_("Credit"),_("Memo"));
			else		
				$th = array(_("Account Code"), _("Account Name"), _("Debit"), _("Credit"), _("Memo"));
			$k = 0; //row colour counter
			$heading_shown = false;

			$credit = $debit = 0;
			while ($myrow = db_fetch($result)) 	{
				if ($myrow['amount'] == 0) continue;
				if (!$heading_shown){
					//display_gl_heading($myrow);
					start_table(TABLESTYLE, "width='95%'");
					table_header($th);
					$heading_shown = true;
				}	
				alt_table_row_color($k);
				
				label_cell($myrow['account']);
				label_cell($myrow['account_name']);
				if ($dim >= 1)
					label_cell(get_dimension_string($myrow['dimension_id'], true));
				if ($dim > 1)
					label_cell(get_dimension_string($myrow['dimension2_id'], true));

				display_debit_or_credit_cells($myrow['amount']);
				label_cell($myrow['memo_']);
				end_row();
				if ($myrow['amount'] > 0 ) 
					$debit += $myrow['amount'];
				else 
					$credit += $myrow['amount'];
			}
			if ($heading_shown){
				start_row("class='inquirybg' style='font-weight:bold'");
				label_cell(_("Total"), "colspan=2");
				if ($dim >= 1)
					label_cell('');
				if ($dim > 1)
					label_cell('');
				amount_cell($debit);
				amount_cell(-$credit);
				label_cell('');
				end_row();
				end_table(1);
			}

			echo '<center> <a href="'.$path_to_root.'/modules/ExtendedHRM/reports/rep802.php?PARAM_0='.$year.'&PARAM_1='.$month.'&PARAM_2='.$employee_id.'&rep_v=yes" target="_blank" class="printlink">'._("Print").' </a> </center>'; 
			br();		
			//submit_center('Void', _("Void"), true, _('Void'), 'default');
			echo '<center>
			<button class="inputsubmit" type="submit" aspect="default nonajax process" name="Void" id="Void" value="Void"><img src="'.$path_to_root.'/themes/Saaisaran/images/ok.gif" height="12" alt=""><span>'._("Void").'</span></button>

			<!--<button class="inputsubmit" type="submit" aspect="default nonajax process" name="DeletePayslip" id="Void" value="Void"><span>'._("Delete").'</span></button>  -->
			</center>';
			end_form();
		}
	}
	div_end();
	if(get_post('Void')){
		DeleteEmplSalary($_POST['payslip_id']);
		display_notification(_("Selected Payslip Voided Successfully"));
		echo "<script type='text/javascript'>function kv_setComboItem(){  window.opener.location.reload(); window.close();  } kv_setComboItem(); </script>";
	}

	if(isset($_POST['DeletePayslip'])){
		//Void_Payroll($_POST['payslip_id']);
		DeleteEmplSalary($_POST['payslip_id']);
		display_notification(_("Selected Payslip Voided Successfully"));
		echo "<script type='text/javascript'>function kv_setComboItem(){  window.opener.location.reload(); window.close();  } kv_setComboItem(); </script>";
	}

	if(get_post('pay_salary')) {
		$Ajax->activate('totals_tbl');
		begin_transaction();
		$jobs_arr =  array('empl_id' => $_POST['employee_id'],
							 'month' => $_POST['month'],
							 'days_worked' => $_POST['days'],
							 'from_date' => date2sql($_POST['from_a_date']),
							 'to_date' => date2sql($_POST['to_a_date']),
							 'year' => $_POST['year'],
							 'currency' => $_POST['currency'],
							 'rate' => input_num('rate'),
							 'gross' => input_num('ear_tot'),							 
							 'pay_hrs' => input_num('workedHours'),
							 'ot_hrs' => input_num('otHours'),
							 'spl_ot_hrs' => input_num('SplotHours'),			 
							 'al' => $_POST['used_al'],								 
							 'sl' => $_POST['used_sl'],								 
							 'ml' => $_POST['used_ml'],								 
							 'dimension' => 0,
							 'dimension2' => 0, 						 
							 'ctc' => input_num('ctc'),							 
							 'date' => array(Today(), 'date'), 
							 'adv_sal' => input_num('adv_sal'),
							 'net_pay' =>  input_num('net_pay'),							
							 'ot_earnings' =>  input_num('ot_earnings'),
						 	 'lop_amount' => input_num('lop_amount'));
			$Allowance = kv_get_allowances(null, 0, $_POST['grade_id']);
			$loan_id = $loan_repay_id = array();
			$loan_id_amount = $paid_now = 0;
			$myloan = GetAll('kv_empl_loan', array('empl_id' => $_POST['employee_id'])); 
			foreach($Allowance as $single) {	
				if($single['type'] == 'Deductions' && $single['loan'] != 1)
					$jobs_arr[$single['id']] = input_num($_POST['employee_id'].'_'.$single['id']);	
				if($single['type'] == 'Earnings')
					$jobs_arr[$single['id']] = input_num($_POST['employee_id'].'_'.$single['id']);	
				if($single['type'] == 'Reimbursement')
					$jobs_arr[$single['id']] = input_num($_POST['employee_id'].'_'.$single['id']);	
				if($single['type'] == 'Employer Contribution')
					$jobs_arr[$single['id']] = input_num($_POST['employee_id'].'_'.$single['id']);	
				if($single['loan'] == 1 && isset($_POST['loan_'.$single['id']])){
					$loan_id[] = array($_POST['loan_'.$single['id']], $_POST['loan_mnth_pay_'.$single['id']], $_POST[$_POST['employee_id'].'_'.$single['id']]);  
					$jobs_arr[$single['id']] = input_num($_POST['employee_id'].'_'.$single['id'])*$_POST['loan_mnth_pay_'.$single['id']];
					$loan_id_amount += input_num($_POST['employee_id'].'_'.$single['id'])*$_POST['loan_mnth_pay_'.$single['id']];
					$loan_type_id = GetSingleValue('kv_empl_loan_types', 'id', ['allowance_id' => $single['id']]);
			
					//Re-Pay-Ment
					if(is_array($myloan)) {
						foreach($myloan as $myrow){
							if($myrow['loan_type_id'] == $loan_type_id){
								$paid_now  = $myrow['periods_paid'] + $_POST[$_POST['employee_id'].'_'.$single['id']];	
								if($paid_now > 0){
									$loan_repay_id[] = Insert('kv_empl_loan_repayment', array('loan_id' => $myrow['id'], 're_pay_date' => date("Y-m-d"), 're_pay_amount' => $loan_id_amount, 'periods_paid' => $paid_now));						
									if($myrow['periods'] == $paid_now)
										$sql = "UPDATE ".TB_PREF."kv_empl_loan SET periods_paid = ".db_escape($paid_now).", status = 3 WHERE id = ".db_escape($myrow['id']);
									else
										$sql = "UPDATE ".TB_PREF."kv_empl_loan SET periods_paid = ".db_escape($paid_now)." WHERE id = ".db_escape($myrow['id']);
									//display_notification($sql);
									db_query($sql, _("could not update employee loan"));		
								}
							}
						}
					}
					//Re-Pay-Ment 
				}				
			}
			$jobs_arr['loans'] = base64_encode(serialize($loan_id));
			$pay_slip_id = Insert('kv_empl_salary', $jobs_arr);

			if($_POST['adv_sal'] > 0){				
				Update('kv_empl_salary_advance', array('empl_id' =>$_POST['employee_id'], 'date' => $_POST['adv_date']), array('inactive' => '1', 'payslip_id' => $pay_slip_id));
			}

			if($paid_now > 0 && !empty($loan_repay_id)){
				foreach($loan_repay_id as $loan){
					Update('kv_empl_loan_repayment', array('id' => $loan), array('pay_slip_id' => $pay_slip_id));
				}
			}

			$_POST['join_date'] = GetSingleValue('kv_empl_job', 'joining', array('empl_id' => $_POST['employee_id']));

			ChangeAttendanceInactive($_POST['employee_id'], sql2date($_POST['join_date']), $_POST['to_a_date']);

			if(input_num('net_pay') < 0 ){
				//$month = ($_POST['month'] == 12 ? 1 : $_POST['month']+1 );
				Insert('kv_empl_salary_advance', array('empl_id' => $_POST['employee_id'], 'payslip_id_adv' => $pay_slip_id, 'amount' => abs(input_num('net_pay')), 'date' =>  array(Today(), 'date') , 'description' => 'Last month Salary of Net Deduction') );
			}

			//gl
		if($hrmsetup['postgl'] == 1)
			Direct_gl_entries($pay_slip_id,$_POST['adv_sal'],$loan_id_amount);
			//gl

		 //Re-pay-ment
		commit_transaction();
		meta_forward($_SERVER['PHP_SELF'], "Added=$pay_slip_id&employee_id=".$_POST['employee_id'].'&month='.$_POST['month'].'&year='.$_POST['year']);
	}	

end_page(); ?>
