<?php
include_once("../class/class.MySQL.php");
$db	=new MySQL();
session_start();
//error_reporting(-1);
$c=0;
$selected_amount_percentage_array = array();

//$amount_array=array();
//$percentage_array=array();
$action = $_POST['act'];
if($action == "EmployeePayStructure"){

//////////////////////////////user rights checking//////////////////////////////////////

$userid=$_SESSION['admin_id'];

$sub_rights=mysql_fetch_array(mysql_query("select * from menu as m,menu_sub as s where  m.menu_name='Salary' and m.menu_id=s.menu_id and s.s_menu_name='EmployeePayStructure'"));

$view_rights=mysql_fetch_array(mysql_query("select * from tbl_user_rights where user_id='$userid' and s_submenu_id='$sub_rights[s_id]'"));

//////////////////////////////user rights checking//////////////////////////////////////

	$cond='where 1';
	
	if($_POST['branch'])
	{
		$cond.=' and A.branchid='.$_POST['branch'].'';
	}
	if($_POST['memberid'] )
	{
		$cond.=' and A.e_id='.$_POST['memberid'].'';
	}
	if($userid!=1)
	{
	    if($view_rights['view_right']==0 )
        {
        $cond.=' and A.e_id='.$userid.'';
	    }
	}

	
	$EmpPayStructure_array= $db->fetchQuery("SELECT A.e_id,A.employee_id,B.desig_id,A.e_fname,desig_name,branch_name,emp_basic_pay FROM employee A join designation B on A.e_post=B.desig_id join branches C on A.branchid=C.branch_id ".$cond." ");

	$table_row='';
	foreach($EmpPayStructure_array as $EmpPayStructure_row)
	{
		
		$earning_total_amount=0;
		$deduction_total_amount=0;
		$netpay_total_amount=0;

		$condition_structure['employee_id'] = $EmpPayStructure_row['e_id'];
		$emp_str_count = $db->CountRows('salary_structure_employee',$condition_structure);
		
		if($emp_str_count == 0){
			$str_type=1;
			$collectid = $EmpPayStructure_row['desig_id'];
		}else{
			$str_type=2;
			$collectid = $EmpPayStructure_row['e_id'];
		}
		
		$salary_calculated_array=salaryCalculation($collectid,$EmpPayStructure_row['emp_basic_pay'],$str_type);
		
		if(empty($salary_calculated_array))
		{
			$expandable_earning_rows='<tr style="background-color:#eee;color:#000">
				<td colspan="3">No Earnings</td>
			</tr>';
			$expandable_deduction_rows='<tr style="background-color:#eee;color:#000">
				<td colspan="3">No Deductions</td>
			</tr>';
		}
		else
		{
			$expandable_earning_rows='';
			$expandable_deduction_rows='';
		}
		//print_r($salary_calculated_array);
		
		$actualED = salaryCalculation($EmpPayStructure_row['desig_id'],0,1);
		
		////////////////////////////////////////////////// EARNINGS//////////////////////////////////
		$earnings = $salary_calculated_array['earnings'];
		
		
		$total_monthly_earning_amount=0;
		$total_yearly_earning_amount = 0;
		if(empty($earnings))
		{
			$expandable_earning_rows='<tr style="background-color:#eee;color:#000">
				<td colspan="3">No Earnings</td>
			</tr>';
		}
		$z=0;
		foreach($earnings as $earnings):
			$maxamt="";
			if($actualED['earnings'][$z]['maxamount'] != "0.00"){
				$maxamt = "Max: ".$actualED['earnings'][$z]['maxamount'];	
			}
			$expandable_earning_rows.='<tr style="background-color:#eee;color:#000"  class="childrow-'.$earnings['parentid'].'">
										<td>'.$earnings['name'].' <br/><span style="font-size:10px;color:#0029FD;">'.$maxamt.'</span></td>
										<td>
								<input type="text" value="'.$earnings['calculateAmt'].'" name="earningamount[]" 
				class="earning-amount earning-deduction" data-id="'.$earnings['id'].'" data-parent="'.$earnings['parentid'].'"  data-eid="'.$EmpPayStructure_row['e_id'].'" />
								<input type="hidden" value="'.$earnings['id'].'" name="earningid[]">
								<input type="hidden" value="'.$earnings['percentage'].'" name="earning-percentage[]" class="percentage">
								<input type="hidden" value="'.$actualED['earnings'][$z]['maxamount'].'" name="earning-maxamount[]" class="maxamount">
								<input type="hidden" value="'.$earnings['calculateAmt'].'" name="earning-maxamount-org[]" class="calculatedamount">
										</td>
										<td class="earning-deduction-mth">'.round($earnings['calculateAmt']/12 ,2) .'</td>
									</tr>';
			$total_monthly_earning_amount +=$earnings['calculateAmt'];
			$total_yearly_earning_amount +=round($earnings['calculateAmt']/12 ,2);
			$z++;						
		endforeach;
		
		
		
		////////////////////////////////////////////////// DEDUCTION//////////////////////////////////
		$deduction = $salary_calculated_array['deduction'];
		
		$total_monthly_deduction_amount=0;
		$total_yearly_deduction_amount = 0;
		
		if(empty($deduction))
		{
			$expandable_deduction_rows='<tr style="background-color:#eee;color:#000">
				<td colspan="3">No Deductions</td>
			</tr>';
		}
		//$x=0;	
		foreach($deduction as $deduction):

			$maxamt="";
			if($actualED['deduction'][$z]['maxamount'] != "0.00"){
				$maxamt = "Max: ".$actualED['deduction'][$z]['maxamount'];
				
			}

			$expandable_deduction_rows.='<tr style="background-color:#eee;color:#000" class="childrow-'.$deduction['parentid'].'">
							<td>'.$deduction['name'].' <br/><span style="font-size:10px;color:#0029FD;">'.$maxamt.'</span></td>
							<td>
							<input type="text" value="'.$deduction['calculateAmt'].'" name="deductionamount[]" 
				class="deduction-amount earning-deduction" data-id="'.$deduction['id'].'"  data-parent="'.$deduction['parentid'].'"  data-eid="'.$EmpPayStructure_row['e_id'].'">
							<input type="hidden" value="'.$deduction['id'].'" name="deductionid[]">
							<input type="hidden" value="'.$deduction['percentage'].'" name="deduction-percentage[]" class="percentage">
							<input type="hidden" value="'.$actualED['deduction'][$z]['maxamount'].'" name="deduction-maxamount[]" class="maxamount">
							<input type="hidden" value="'.$deduction['calculateAmt'].'" name="deduction-maxamount-org[]" class="calculatedamount">
							</td>
							<td class="earning-deduction-mth">'.round($deduction['calculateAmt']/12 ,2) .'</td>
							</tr>';
			$total_monthly_deduction_amount +=$deduction['calculateAmt'];
			$total_yearly_deduction_amount +=round($deduction['calculateAmt']/12 ,2);						
		$z++;							
		endforeach;
		
		
		$earning_total_amount= $total_monthly_earning_amount;
		$deduction_total_amount= $total_monthly_deduction_amount;
		$netpay_total_amount = $total_monthly_earning_amount - $total_monthly_deduction_amount;
	
		$table_row.='<tr class="expand_parent_row" style="cursor:pointer">
			<td>'.$EmpPayStructure_row['employee_id'].'</td>
			<td>'.$EmpPayStructure_row['e_fname'].'</td>
			<td>'.$EmpPayStructure_row['branch_name'].'</td>
			<td>'.$EmpPayStructure_row['desig_name'].'</td>
			
			<td style="text-align:right">'.number_format($total_monthly_earning_amount,2, '.', '').'</td>
			<td style="text-align:right">'.number_format($total_monthly_deduction_amount,2, '.', '').'</td>
			<td style="text-align:right"><b>'.number_format($netpay_total_amount,2, '.', '').'</b></td>
		</tr>
		<tr class="row_to_expand" style="display:none;">
			<td colspan="8">
			
				<form id="salarystructure'.$EmpPayStructure_row['e_id'].'">
				
				<input type="hidden" value="'.$EmpPayStructure_row['desig_id'].'" name="designationid">
				
				<table class="table table-bordered" id="employee-details-'.$EmpPayStructure_row['e_id'].'">
					<thead>
						<tr style="background-color:#eee;color:#000">
							<th style="width:50%;"><translate>Earnings</translate></th>
							<th style="width:50%;"><translate>Deductions</translate></th>
						</tr>
					</thead>
					<tbody>
						<tr style="background-color:#eee;color:#000">
							<td>
								<table class="table">
									<thead>
										<tr style="background-color:#eee;color:#000">
											<th>Name</th>
											<th>Yearly Amount</th>
											<th>Monthly Amount</th>
										</tr>
									</thead>
									<tbody>'.$expandable_earning_rows.'</tbody>
									<tfoot>
										<tr style="background-color:#eee;color:#000">
											<td></td>
											<td>Total:<strong class="earning-mth-total">'.number_format($total_monthly_earning_amount,2, '.', '').'</strong></td>
											<td>Total:<strong class="earning-yrl-total">'.number_format($total_yearly_earning_amount,2, '.', '').'</strong></td>
										</tr>
										
										<tr style="background-color:#eee;color:#FF3399;font-size:14px;">
											<td colspan="3">Net Pay:<strong class="net-pay">'.number_format($netpay_total_amount,2, '.', '').'</strong> 
											<input type="button" value="Update Salary"  class="color-button save-salary-structure" data-id="'.$EmpPayStructure_row['e_id'].'">
									<input type="button" value="Reset Salary Structure"  class="color-button reset-salary-structure" data-id="'.$EmpPayStructure_row['e_id'].'">
											</td>
										</tr>
									</tfoot>
								</table>
							</td>
							<td>
								<table class="table">
									<thead>
										<tr style="background-color:#eee;color:#000">
											<th>Name</th>
											<th>Yearly Amount</th>
											<th>Monthly Amount</th>
										</tr>
									</thead>
									<tbody>'.$expandable_deduction_rows.'</tbody>
									<tfoot>
										<tr style="background-color:#eee;color:#000">
											<td></td>
											<td>Total:<strong  class="deduction-mth-total">'.number_format($total_monthly_deduction_amount,2, '.', '').'</strong></td>
											<td>Total:<strong class="deduction-yrl-total">'.number_format($total_yearly_deduction_amount,2, '.', '').'</strong></td>
										</tr>
									</tfoot>
								</table>
							</td>
						</tr>
					</tbody>
				</table>
				
				</form>
				
			</td>
		</tr>';
	}
	echo $table_row;
}
elseif($action == "LoadEmpBranch"){
	if($_POST['branch_id'])
	{
		$Employee_array= $db->fetchQuery("SELECT e_id,e_fname FROM employee where branchid=".$_POST['branch_id']." and user_type!='Superadmin' ");
	}
	else
	{
		$Employee_array= $db->fetchQuery("SELECT e_id,e_fname FROM employee where user_type!='Superadmin'");
	}
	//print_r($Employee_array);
	$employee_combo='<option value="">Choose Member</option>';
	if(!empty($Employee_array))
	{
		foreach($Employee_array as $employee_row)
		{
			$employee_combo.='<option value="'.$employee_row['e_id'].'">'.$employee_row['e_fname'].'</option>';
		}
	}
	echo $employee_combo;
}
elseif($action == "EmployeePaySalary" )
{

//////////////////////////////user rights checking//////////////////////////////////////

$userid=$_SESSION['admin_id'];

$sub_rights=mysql_fetch_array(mysql_query("select * from menu as m,menu_sub as s where  m.menu_name='Salary' and m.menu_id=s.menu_id and s.s_menu_name='paySalary'"));

$view_rights=mysql_fetch_array(mysql_query("select * from tbl_user_rights where user_id='$userid' and s_submenu_id='$sub_rights[s_id]'"));


$sub_rights_slip=mysql_fetch_array(mysql_query("select * from menu as m,menu_sub as s where  m.menu_name='Salary' and m.menu_id=s.menu_id and s.s_menu_name='Pay Slip'"));

$view_rights_slip=mysql_fetch_array(mysql_query("select * from tbl_user_rights where user_id='$userid' and s_submenu_id='$sub_rights_slip[s_id]'"));

//////////////////////////////user rights checking//////////////////////////////////////


	$cond='where 1';
	if($_POST['branch'])
	{
		$cond.=' and A.branchid='.$_POST['branch'].'';
	}
	if($_POST['memberid'])
	{
		$cond.=' and A.e_id='.$_POST['memberid'].'';
	}
	if($userid!=1)
	{
	if($view_rights['view_right']==0 )
    {
    $cond.=' and A.e_id='.$userid.'';
	}
	}
	$EmpPayStructure_array= $db->fetchQuery("SELECT A.e_id,A.employee_id,B.desig_id,A.e_fname,desig_name,branch_name,emp_basic_pay,date_join FROM employee A join designation B on A.e_post=B.desig_id join branches C on A.branchid=C.branch_id ".$cond." ");




	$table_row='';
	foreach($EmpPayStructure_array as $EmpPayStructure_row)
	{
		///////////////////////// Calculate LOP //////////////////////////////////////////////////
		$explode_date_of_join=explode('-',$EmpPayStructure_row['date_join']);
		if($_POST['salyear'])
		{
			$year=$_POST['salyear'];
		}
		else
		{
			$year=date("Y");
		}
		
		if($_POST['salmonth'])
		{
			$month=$_POST['salmonth'];
		}
		else
		{
			$month=date("m");
		}
		
		if($year==date('Y') && $month==date('m'))
		{
			// To find no of days between date ranges
			//$now = time();
			$yesterday_to_time=strtotime(date('Y-m-d',strtotime("-1 days")));
     		$first_date = strtotime(''.$year.'-'.$month.'-01');

     		$datediff = $yesterday_to_time - $first_date;
     		$last_day =floor($datediff/(60*60*24));
			
			$endOfLastmth=date('Y-m-d',strtotime("-1 days"));
		}
		else
		{
			$last_day = cal_days_in_month(CAL_GREGORIAN, $month, $year);
			$endOfLastmth=$year.'-'.$month.'-'.$last_day;
		}
		
		if($explode_date_of_join[2]==$year && $explode_date_of_join[1]==$month)
		{
			$firstOfLastmth=$year.'-'.$month.'-'.$explode_date_of_join[0].'';
		}
		else
		{
			$firstOfLastmth=$year.'-'.$month.'-01';
		}
		
		
		
		$availedleaves=0;
			
			
		//$endOfLastmth=date('Y-m-d');
		$lastMtnHolidays = $db->fetchQuery("SELECT * FROM payroll_holiday_calendar WHERE date between '".$firstOfLastmth."' and '".$endOfLastmth."' and is_blocked='0' ");
		$holidays=array();
		foreach($lastMtnHolidays as $lastMtnHolidays){
			  $holidays[]=$lastMtnHolidays['date'];
		}
			
		$noofholidays=count($holidays);

		$workingDays=  $db->getWorkingDays($firstOfLastmth,$endOfLastmth,$holidays);
		
		$lastyrattendance = $db->fetchQuery("SELECT count(distinct(e_date)) FROM time WHERE e_date>='".$firstOfLastmth."' and e_date<='".$endOfLastmth."' and e_id='".$EmpPayStructure_row['e_id']."'");
		$yrattendance=$lastyrattendance[0]['count(distinct(e_date))'];
		
		$approved_leaves_array =array();
		$approved_leaves_array = $db->fetchQuery("Select day_from from payroll_user_leave_requests where employee_id='".$EmpPayStructure_row['e_id']."' and is_cancelled=0 and imd_status=1 and is_blocked=0 and day_from>='".$firstOfLastmth."' and day_from<='".$endOfLastmth."' ");
			
		$approved_leaves_count=count($approved_leaves_array);
		$approved_leaves_present=0;
			
		if(!empty($approved_leaves_array))
		{
			foreach($approved_leaves_array as $approved_leaves_array){
			  $approved_leaves_date_array[]=$approved_leaves_array['day_from'];
			}	
			$leave_date_clause = join(',',$approved_leaves_date_array); 
			$approved_leaves_query=$db->fetchQuery("SELECT count(distinct(e_date)) as leave_count FROM time WHERE e_date in (".$leave_date_clause.") and e_id='".$EmpPayStructure_row['e_id']."' ");
				
			$approved_leaves_present=$approved_leaves_query[0]['leave_count']; 
			$approved_leaves_count=$approved_leaves_count-$approved_leaves_present;
		}
		
		$availedleaves=$workingDays-($yrattendance+$approved_leaves_count);
		
		///////////////////////////// End of LOP Calculations ////////////////////////////
		
		$earning_total_amount=0;
		$deduction_total_amount=0;
		$netpay_total_amount=0;
		$lop_total_amount=0;
		
		$basic_salary=$EmpPayStructure_row['emp_basic_pay'];
		if($year==$explode_date_of_join[2])
		{
			if($month<$explode_date_of_join[1])
			{
				$basic_salary=0;
			}
		}
		//$basic_salary=$EmpPayStructure_row['emp_basic_pay'];
		
		$condition_structure['employee_id'] = $EmpPayStructure_row['e_id'];
		$emp_str_count = $db->CountRows('salary_structure_employee',$condition_structure);
		
		if($emp_str_count == 0){
			$str_type=1;
			$collectid = $EmpPayStructure_row['desig_id'];
		}else{
			$str_type=2;
			$collectid = $EmpPayStructure_row['e_id'];
		}
		
		$salary_calculated_array=salaryCalculation($collectid,$basic_salary,$str_type);
		
		
		
	//	$salary_calculated_array=salaryCalculation($EmpPayStructure_row['desig_id'],$basic_salary);
		
		////////////////////////////////////////////////// EARNINGS//////////////////////////////////
		$earnings = $salary_calculated_array['earnings'];
		$expandable_earning_rows;
		
		$total_monthly_earning_amount=0;
		$total_yearly_earning_amount = 0;
		foreach($earnings as $earnings):
		
			$total_monthly_earning_amount +=$earnings['calculateAmt'];
			$total_yearly_earning_amount +=($earnings['calculateAmt']*12);
									
		endforeach;
		
		
		
		////////////////////////////////////////////////// DEDUCTION//////////////////////////////////
		$deduction = $salary_calculated_array['deduction'];
		$expandable_deduction_rows;
		$total_monthly_deduction_amount=0;
		$total_yearly_deduction_amount = 0;
		foreach($deduction as $deduction):
		
			$total_monthly_deduction_amount +=$deduction['calculateAmt'];
			$total_yearly_deduction_amount +=($deduction['calculateAmt']*12);						
									
		endforeach;
		
		
		$earning_total_amount= $total_monthly_earning_amount;
		$deduction_total_amount= $total_monthly_deduction_amount;
		//$lop_total_amount= (($salary_calculated_array['earnings'][0]['calculateAmt']/12)/$last_day)*$availedleaves;
		$lop_total_amount= ($salary_calculated_array['earnings'][0]['calculateAmt']/(12*(cal_days_in_month(CAL_GREGORIAN, $month, $year))))*$availedleaves;
		//$lop_total_amount=$availedleaves;
		$netpay_total_amount = ($total_monthly_earning_amount/12) - ($total_monthly_deduction_amount/12) - $lop_total_amount;
		
		 //////////////////////////////////////////////// Check Payment Status //////////////////////////////////////////////////////////////////////
		
		$givendate = "01-".$month."-".$year;
		$requestedDate = date('Y-m',strtotime($givendate)).'-01';
		$paymentDetails= $db->fetchQuery("SELECT * FROM payroll_salary_pay WHERE pay_period ='".$year."-".$month."-01' and userid='".$EmpPayStructure_row['e_id']."'");
		
		$salRows = count($paymentDetails);
		if($salRows > 0){	
			$paymentStatus = 'Paid';
		}
		else
		{
			$paymentStatus = 'Not Paid';
		}
		
		$table_row.='<tr class="expand_parent_row">
			<td>'.$EmpPayStructure_row['e_fname'].'</td>
			<td>'.$EmpPayStructure_row['branch_name'].'</td>
			<td>'.number_format(round($salary_calculated_array['earnings'][0]['calculateAmt']/12),2, '.', '') .'</td>
			<td>'.number_format(round($earning_total_amount/12),2, '.', '').'</td>
			<td>'.number_format(round($deduction_total_amount/12),2, '.', '').'</td>
			<td>'.number_format(round($lop_total_amount),2, '.', '').'</td>
			<td>'.number_format(round($netpay_total_amount),2, '.', '').'</td>
			<td><a style="cursor:pointer" onClick="pay_slip_view('.$EmpPayStructure_row['e_id'].')">Pay Slip</a></td>';
			
			if($userid!=1)
			{
			
			  if($view_rights_slip['view_right']==1){
			 $table_row.='<td><a style="cursor:pointer" onClick="pay_slip_view('.$EmpPayStructure_row['e_id'].')">Pay Slip</a></td>';
			   }
			   else
			   {
			  $table_row.='<td></td>'; 
			   }
			}
			else
			{
			$table_row.='<td><a style="cursor:pointer" onClick="pay_slip_view('.$EmpPayStructure_row['e_id'].')">Pay Slip</a></td>';
			}
			
			
			if($paymentStatus=='Paid')
			{
			$table_row.='<td class="pay_status'.$EmpPayStructure_row['e_id'].'" ><font color="#138bca">'.$paymentStatus.'</td>';
			}
			else
			{
			$table_row.='<td class="pay_status'.$EmpPayStructure_row['e_id'].'">'.$paymentStatus.'</td>';	
			}
		$table_row.='</tr>';
		
		/*<td><a class="payslip showPaySlip" style="cursor:pointer" data-id="'.$row['e_id'].'">Pay Slip</a></td>*/
	}
	echo $table_row;
}
elseif($action == 'payslipview')
{
	$EmpDetails_array= $db->fetchQuery("SELECT A.e_id,A.employee_id,B.desig_id,A.e_fname,desig_name,branch_name,emp_basic_pay,depart_name,date_join FROM employee A join designation B on A.e_post=B.desig_id join branches C on A.branchid=C.branch_id left join department D on A.departid=D.depart_id where A.e_id=".$_POST['employee_id']." ");
	if($_POST['year'])
	{
		$year=$_POST['year'];
	}
	else
	{
		$year=date('Y');
	}
	if($_POST['month'])
	{
		$month=$_POST['month'];
	}
	else
	{
		$month=date('m');
	}
	
	/////////// LOP Calculation ////////////////////
		$explode_date_of_join=explode('-',$EmpDetails_array[0]['date_join']);
		if($year==date('Y') && $month==date('m'))
		{
			// To find no of days between date ranges
			//$now = time();
			$yesterday_to_time=strtotime(date('Y-m-d',strtotime("-1 days")));
     		$first_date = strtotime(''.$year.'-'.$month.'-01');

     		$datediff = $yesterday_to_time - $first_date;
     		$last_day =floor($datediff/(60*60*24));
			$endOfLastmth=date('Y-m-d',strtotime("-1 days"));
		}
		else
		{
			$last_day = cal_days_in_month(CAL_GREGORIAN, $month, $year);
			$endOfLastmth=$year.'-'.$month.'-'.$last_day;
		}
		
		if($explode_date_of_join[2]==$year && $explode_date_of_join[1]==$month)
		{
			$firstOfLastmth=$year.'-'.$month.'-'.$explode_date_of_join[0].'';
		}
		else
		{
			$firstOfLastmth=$year.'-'.$month.'-01';
		}
		
		
		
		$availedleaves=0;
			
			
		//$endOfLastmth=date('Y-m-d');
		$lastMtnHolidays = $db->fetchQuery("SELECT * FROM payroll_holiday_calendar WHERE date between '".$firstOfLastmth."' and '".$endOfLastmth."' and is_blocked='0' ");
		$holidays=array();
		foreach($lastMtnHolidays as $lastMtnHolidays){
			  $holidays[]=$lastMtnHolidays['date'];
		}
			
		$noofholidays=count($holidays);
		//$q="SELECT * FROM payroll_holiday_calendar WHERE date between '".$firstOfLastmth."' and '".$endOfLastmth."' and is_blocked='0' ";
		//$q=$firstOfLastmth."=====".$endOfLastmth;
		$workingDays=  $db->getWorkingDays($firstOfLastmth,$endOfLastmth,$holidays);
		
		$lastyrattendance = $db->fetchQuery("SELECT count(distinct(e_date)) FROM time WHERE e_date>='".$firstOfLastmth."' and e_date<='".$endOfLastmth."' and e_id='".$EmpDetails_array[0]['e_id']."'");
		$yrattendance=$lastyrattendance[0]['count(distinct(e_date))'];
		
		$approved_leaves_array =array();
		$approved_leaves_array = $db->fetchQuery("Select day_from from payroll_user_leave_requests where employee_id='".$EmpDetails_array[0]['e_id']."' and is_cancelled=0 and imd_status=1 and is_blocked=0 and day_from>='".$firstOfLastmth."' and day_from<='".$endOfLastmth."' ");
			
		$approved_leaves_count=count($approved_leaves_array);
		$approved_leaves_present=0;
		//echo $approved_leaves_count.'<br>';	
		if(!empty($approved_leaves_array))
		{
			//$leave_date_array = array_keys($approved_leaves_array);
			//$leave_day_concept_array = array_values($approved_leaves_array);
			foreach($approved_leaves_array as $approved_leaves_array){
			  $approved_leaves_date_array[]=$approved_leaves_array['day_from'];
			}	
			$leave_date_clause = join(',',$approved_leaves_date_array); 
			$approved_leaves_query=$db->fetchQuery("SELECT count(distinct(e_date)) as leave_count FROM time WHERE e_date in (".$leave_date_clause.") and e_id='".$EmpDetails_array[0]['e_id']."' ");
			//echo "SELECT count(distinct(e_date)) as leave_count FROM time WHERE e_date in (".$leave_date_clause.") and e_id='".$EmpDetails_array[0]['e_id']."' ";	
			//echo $approved_leaves_query[0]['leave_count'];
			$approved_leaves_present=$approved_leaves_query[0]['leave_count']; 
			$approved_leaves_count=$approved_leaves_count-$approved_leaves_present; 
		}
		
		
		$availedleaves=$workingDays-($yrattendance+$approved_leaves_count);
		//echo 'Working Days='.$workingDays.'<br>Present='.$yrattendance.'<br>Approved Leaves='.$approved_leaves_count;
		/////////// End LOP Calculation ////////////////////
		
		/////////// Check for Payment ////////////////////
		$paymentDetails= $db->fetchQuery("SELECT * FROM payroll_salary_pay WHERE pay_period ='".$year."-".$month."-01' and userid='".$EmpDetails_array[0]['e_id']."'");
		//print_r($paymentDetails);
		$salRows = count($paymentDetails);
		if($salRows > 0){
			$details_of_payment=$db->fetchQuery("SELECT * FROM payroll_salary_pay_details where payment_id = ".$paymentDetails[0]['id']." ");
			$expandable_earning_rows='';
			$expandable_deduction_rows='';
			$total_addition=0;
			$total_deduction=0;
			$net_salary=0;
			foreach($details_of_payment as $payment_row):
				if($payment_row['type']==1)
				{
					$expandable_earning_rows.='<tr style="background-color:#eee;color:#000" >
						<td>'.$payment_row['name'].'</td>
						<td class="earning-deduction-mth" style="text-align:right">'.round($payment_row['amount'],2) .'</td>
					</tr>';
					$total_addition=$total_addition+$payment_row['amount'];
				}
				else
				{
					$expandable_deduction_rows.='<tr style="background-color:#eee;color:#000">
						<td>'.$payment_row['name'].'</td>
						<td class="earning-deduction-mth" style="text-align:right">'.round($payment_row['amount'],2) .'</td>
					</tr>';
					$total_deduction=$total_deduction+$payment_row['amount'];
				}
				//$total_monthly_earning_amount +=$earnings['calculateAmt'];
				//$total_yearly_earning_amount +=round($earnings['calculateAmt']/12 ,2);
										
			endforeach;
			
			//$total_yearly_earning_amount=$paymentDetails[0]['total_earnings'];
			//$total_yearly_deduction_amount=$paymentDetails[0]['total_deduction'];
			//$netpay_total_amount=$paymentDetails[0]['total_payable'];
			
			/*$earning_total_amount= $total_monthly_earning_amount;
			$deduction_total_amount= $total_monthly_deduction_amount;
			$lop_total_amount= ($salary_calculated_array['earnings'][0]['calculateAmt']/(12*(cal_days_in_month(CAL_GREGORIAN, $month, $year))))*$availedleaves;
			$netpay_total_amount = ($total_monthly_earning_amount/12) - ($total_monthly_deduction_amount/12) - $lop_total_amount;*/
			
			$companyDetails= $db->fetchQuery("SELECT * FROM addhrm_company_master ");	
			$paymentMethods= $db->fetchQuery("SELECT * FROM payroll_payment_methods ");	
			$payment_combo='<select name="paymentThrough" class="paymentThrough form-control">';
			foreach($paymentMethods as $payment_row)
			{
				if($payment_row['id']==$paymentDetails[0]['payment_method'])
				{
					$payment_combo.='<option value="'.$payment_row['id'].'" selected>'.$payment_row['title'].'</option>';	
				}
				else
				{
					$payment_combo.='<option value="'.$payment_row['id'].'">'.$payment_row['title'].'</option>';
				}
			}
			$payment_combo.='</select>';
	echo '<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
        		<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
        		<h4 class="modal-title" id="myModalLabel">Salary Slip</h4>
      		</div>
      		<div class="modal-body">
			<form id="PaySalaryForm">
        		<input type="hidden" name="act" id="act" value="paySal">
				<div class="row">
					<div class="col-md-8">
						<address>
							<strong>'.$companyDetails[0]['company_name'].'</strong><br>
							'.$companyDetails[0]['company_address'].'<br>
							<abbr title="Phone">P:</abbr> '.$companyDetails[0]['company_phone'].'<br>
							<abbr title="Mobile">M:</abbr> '.$companyDetails[0]['company_mobile'].'<br>
							<abbr title="Email">E:</abbr> '.$companyDetails[0]['company_email'].'
						</address>
					</div>
					<div class="col-md-4"><img src="images/mc_logo.png" width="150" class="img-responsive"></div>
				<table class="table">
					<tr>
						<td><b>Branch:</b> '.$EmpDetails_array[0]['branch_name'].'</td>
						<td colspan="2"><b>Month & Year:</b> '.date('F', mktime(0, 0, 0, $month)).' '.$year.'</td>
					</tr>
					<tr>
						<td><b>Employee Name :</b> '.$EmpDetails_array[0]['e_fname'].'</td>
						<td><b>Department :</b> '.$EmpDetails_array[0]['depart_name'].'</td>
						<td><b>Designation :</b> '.$EmpDetails_array[0]['desig_name'].'</td>
					</tr>
					<tr>
						<td><b>Working Days :</b> '.$workingDays.'<input type="hidden" name="working_days" id="working_days" value="'.$workingDays.'"></td>
						<td><b>Present Days :</b> '.$yrattendance.'<input type="hidden" name="present_days" id="present_days" value="'.$yrattendance.'"></td>
						<td></td><input type="hidden" name="earned_leaves" id="earned_leaves" value="'.$approved_leaves_count.'">
					</tr>
					<tr>
						<td colspan="2">Payment Mode :'.$payment_combo.'
						</td>
						<td>Reference :<input type="text" name="referance" id="referance" class="referance form-control" value="'.$paymentDetails[0]['payment_referance'].'"></td>
					</tr>
				</table>
				<table class="table table-bordered" border="2">
					<thead>
						<tr style="background-color:#eee;color:#000">
							<th style="width:50%;"><translate>Earnings</translate></th>
							<th style="width:50%;"><translate>Deductions</translate></th>
						</tr>
					</thead>
					<tbody>
						<tr style="background-color:#eee;color:#000">
							<td>
								<table class="table">
									<tbody>'.$expandable_earning_rows.'</tbody>
									<tfoot>
										<tr style="background-color:#eee;color:#000">
											<td>Total Addition</td>
											<td style="text-align:right"><b>'.$total_addition.'</b></td>
										</tr>
									</tfoot>
								</table>
							</td>
							<td>
								<table class="table">
									<tbody>
										'.$expandable_deduction_rows.'
										
									</tbody>
									<tfoot>
										<tr style="background-color:#eee;color:#000">
											<td>Total Deduction</td>
											<td style="text-align:right"><b>'.number_format($total_deduction,2, '.', '').'</b></td>
										</tr>
									</tfoot>
								</table>
							</td>
						</tr>
					</tbody>
					<tfoot>
						<tr style="background-color:#eee;color:#000;">
							<td></td>
							<td>Net Salary : <b>'.number_format(round($total_addition-$total_deduction),2, '.', '').'</b><input type="hidden" name="total_payable_amt" value="'.$netpay_total_amount.'"></td>
							<input type="hidden" name="leave_deduction" id="leave_deduction" value="'.$lop_total_amount.'">
							<input type="hidden" name="total_earnings" id="total_earnings" value="'.$total_yearly_earning_amount.'">
							<input type="hidden" name="total_deduction" id="total_deduction" value="'.$total_yearly_deduction_amount.'">
						</tr>
						<tr>
							<td colspan="2"><b>Amount in words: '.ucwords(convert_number_to_words(round($total_addition-$total_deduction))).'</b><input type="hidden" id="total_payable_words" name="total_payable_words" value="'.ucwords(convert_number_to_words(round($total_addition-$total_deduction))).'" ></td>
						</tr>
					</tfoot>
				</table>
				<table class="table">
					<tr >
						<td style="border-top:none;">Director Sign:</td>
						<td style="border-top:none;">Employee Sign:</td>
					</tr>
				</table>
				<input type="hidden" name="userid" value="'.$_POST['employee_id'].'" id="userid" >
				<input type="hidden" name="year" value="'.$year.'" >
				<input type="hidden" name="month" value="'.$month.'" >
			</form>
      		</div>
      		<div class="modal-footer">
        		<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        		<button type="button" class="btn btn-primary" onClick="print_pay_slip()">Print</button>';
				if($salRows == 0){
					echo '<button type="button" class="btn btn-primary" onClick="submitSalary()" >Pay Salary</button>';
				}
      		echo '</div>
    	</div>
	</div>';
			
		}
		else
		{
			$earning_total_amount=0;
			$deduction_total_amount=0;
			$netpay_total_amount=0;
			$lop_total_amount=0;
			
			/*$basic_salary=$EmpDetails_array[0]['emp_basic_pay'];
			if($year==$explode_date_of_join[2])
			{
				if($month<$explode_date_of_join[1])
				{
					$basic_salary=0;
				}
			}*/
	
			$basic_salary=$EmpDetails_array[0]['emp_basic_pay'];
			 $condition_structure['employee_id'] = $EmpDetails_array[0]['e_id'];
			$emp_str_count = $db->CountRows('salary_structure_employee',$condition_structure);
			
			if($emp_str_count == 0){
				$str_type=1;
				$collectid = $EmpDetails_array[0]['desig_id'];
			}else{
				 $str_type=2;
				$collectid = $EmpDetails_array[0]['e_id'];
			}
			
			$salary_calculated_array=salaryCalculation($collectid,0,$str_type);
			//print_r($salary_calculated_array);
			
			////////////////////////////////////////////////// EARNINGS//////////////////////////////////
			$earnings = $salary_calculated_array['earnings'];
			
			
			$total_monthly_earning_amount=0;
			$total_yearly_earning_amount = 0;
			if(empty($earnings))
			{
				$expandable_earning_rows='<tr style="background-color:#eee;color:#000">
					<td colspan="3">No Earnings</td>
				</tr>';
			}
			foreach($earnings as $earnings):
	
				$expandable_earning_rows.='<tr style="background-color:#eee;color:#000"  class="childrow-'.$earnings['parentid'].'">
											<td>'.$earnings['name'].'<input type="hidden" name="e_d_name[]" value="'.$earnings['name'].'"><input type="hidden" name="e_d_type[]" value="1"></td>
											<td class="earning-deduction-mth" style="text-align:right">'.round($earnings['calculateAmt']/12 ,2) .'<input type="hidden" name="e_d_amount[]" value="'.round($earnings['calculateAmt']/12 ,2).'"></td>
										</tr>';
				$total_monthly_earning_amount +=$earnings['calculateAmt'];
				$total_yearly_earning_amount +=round($earnings['calculateAmt']/12 ,2);
										
			endforeach;
			
			
			
			////////////////////////////////////////////////// DEDUCTION//////////////////////////////////
			$deduction = $salary_calculated_array['deduction'];
			
			$total_monthly_deduction_amount=0;
			$total_yearly_deduction_amount = 0;
			
			if(empty($deduction))
			{
				$expandable_deduction_rows='<tr style="background-color:#eee;color:#000">
					<td colspan="3">No Deductions</td>
				</tr>';
			}
				
			foreach($deduction as $deduction):
	
				$expandable_deduction_rows.='<tr style="background-color:#eee;color:#000" class="childrow-'.$deduction['parentid'].'">
								<td>'.$deduction['name'].'<input type="hidden" name="e_d_name[]" value="'.$deduction['name'].'"><input type="hidden" name="e_d_type[]" value="2"></td>
								<td class="earning-deduction-mth" style="text-align:right">'.round($deduction['calculateAmt']/12 ,2) .'<input type="hidden" name="e_d_amount[]" value="'.round($deduction['calculateAmt']/12 ,2).'"></td>
								</tr>';
				$total_monthly_deduction_amount +=$deduction['calculateAmt'];
				$total_yearly_deduction_amount +=round($deduction['calculateAmt']/12 ,2);						
										
			endforeach;
			
			//$earning_total_amount= $total_monthly_earning_amount;
			//$deduction_total_amount= $total_monthly_deduction_amount;
			
			//$netpay_total_amount1 = $basic_salary + $total_monthly_earning_amount - $total_monthly_deduction_amount ;
			//$lop_total_amount= (($total_yearly_earning_amount - $total_yearly_deduction_amount)/$last_day)*$availedleaves;
			//$netpay_total_amount = $total_yearly_earning_amount - $total_yearly_deduction_amount - $lop_total_amount;
		//	print_r($salary_calculated_array);
			$earning_total_amount= $total_monthly_earning_amount;
			$deduction_total_amount= $total_monthly_deduction_amount;
			$lop_total_amount= ($salary_calculated_array['earnings'][0]['calculateAmt']/(12*(cal_days_in_month(CAL_GREGORIAN, $month, $year))))*$availedleaves;
			$netpay_total_amount = ($total_monthly_earning_amount/12) - ($total_monthly_deduction_amount/12) - $lop_total_amount;
			
			$companyDetails= $db->fetchQuery("SELECT * FROM addhrm_company_master ");	
			$paymentMethods= $db->fetchQuery("SELECT * FROM payroll_payment_methods ");	
			$payment_combo='<select name="paymentThrough" class="paymentThrough form-control">';
			foreach($paymentMethods as $payment_row)
			{
				$payment_combo.='<option value="'.$payment_row['id'].'">'.$payment_row['title'].'</option>';
			}
			$payment_combo.='</select>';
	echo '<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
        		<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
        		<h4 class="modal-title" id="myModalLabel">Salary Slip</h4>
      		</div>
      		<div class="modal-body">
			<form id="PaySalaryForm">
        		<input type="hidden" name="act" id="act" value="paySal">
				<div class="row">
					<div class="col-md-8">
						<address>
							<strong>'.$companyDetails[0]['company_name'].'</strong><br>
							'.$companyDetails[0]['company_address'].'<br>
							<abbr title="Phone">P:</abbr> '.$companyDetails[0]['company_phone'].'<br>
							<abbr title="Mobile">M:</abbr> '.$companyDetails[0]['company_mobile'].'<br>
							<abbr title="Email">E:</abbr> '.$companyDetails[0]['company_email'].'
						</address>
					</div>
					<div class="col-md-4"><img src="images/mc_logo.png" width="150" class="img-responsive"></div>
				<table class="table">
					<tr>
						<td><b>Branch:</b> '.$EmpDetails_array[0]['branch_name'].'</td>
						<td colspan="2"><b>Month & Year:</b> '.date('F', mktime(0, 0, 0, $month)).' '.$year.'</td>
					</tr>
					<tr>
						<td><b>Employee Name :</b> '.$EmpDetails_array[0]['e_fname'].'</td>
						<td><b>Department :</b> '.$EmpDetails_array[0]['depart_name'].'</td>
						<td><b>Designation :</b> '.$EmpDetails_array[0]['desig_name'].'</td>
					</tr>
					<tr>
						<td><b>Working Days :</b> '.$workingDays.'<input type="hidden" name="working_days" id="working_days" value="'.$workingDays.'"></td>
						<td><b>Present Days :</b> '.$yrattendance.'<input type="hidden" name="present_days" id="present_days" value="'.$yrattendance.'"></td>
						<td></td><input type="hidden" name="earned_leaves" id="earned_leaves" value="'.$approved_leaves_count.'">
					</tr>
					<tr>
						<td colspan="2">Payment Mode :'.$payment_combo.'
						</td>
						<td>Reference :<input type="text" name="referance" id="referance" class="referance form-control"></td>
					</tr>
				</table>
				<table class="table table-bordered" border="2">
					<thead>
						<tr style="background-color:#eee;color:#000">
							<th style="width:50%;"><translate>Earnings</translate></th>
							<th style="width:50%;"><translate>Deductions</translate></th>
						</tr>
					</thead>
					<tbody>
						<tr style="background-color:#eee;color:#000">
							<td>
								<table class="table">
									<tbody>'.$expandable_earning_rows.'</tbody>
									<tfoot>
										<tr style="background-color:#eee;color:#000">
											<td>Total Addition</td>
											<td style="text-align:right"><b>'.$total_yearly_earning_amount.'</b></td>
										</tr>
									</tfoot>
								</table>
							</td>
							<td>
								<table class="table">
									<tbody>
										'.$expandable_deduction_rows.'
										<tr style="background-color:#eee;color:#000">
											<td>LOP<input type="hidden" name="e_d_name[]" value="LOP"><input type="hidden" name="e_d_type[]" value="2"></td>
											<td style="text-align:right">'.number_format($lop_total_amount,2, '.', '').'<input type="hidden" name="e_d_amount[]" value="'.number_format($lop_total_amount,2, '.', '').'"></td>
										</tr>
									</tbody>
									<tfoot>
										<tr style="background-color:#eee;color:#000">
											<td>Total Deduction</td>
											<td style="text-align:right"><b>'.number_format(($total_yearly_deduction_amount+$lop_total_amount),2, '.', '').'</b></td>
										</tr>
									</tfoot>
								</table>
							</td>
						</tr>
					</tbody>
					<tfoot>
						<tr style="background-color:#eee;color:#000;">
							<td></td>
							<td>Net Salary : <b>'.number_format(round($netpay_total_amount),2, '.', '').'</b><input type="hidden" name="total_payable_amt" value="'.$netpay_total_amount.'"></td>
							<input type="hidden" name="leave_deduction" id="leave_deduction" value="'.$lop_total_amount.'">
							<input type="hidden" name="total_earnings" id="total_earnings" value="'.$total_yearly_earning_amount.'">
							<input type="hidden" name="total_deduction" id="total_deduction" value="'.$total_yearly_deduction_amount.'">
						</tr>
						<tr>
							<td colspan="2"><b>Amount in words: '.ucwords(convert_number_to_words(round($netpay_total_amount))).'</b><input type="hidden" id="total_payable_words" name="total_payable_words" value="'.ucwords(convert_number_to_words(round($netpay_total_amount))).'" ></td>
						</tr>
					</tfoot>
				</table>
				<table class="table">
					<tr >
						<td style="border-top:none;">Director Sign:</td>
						<td style="border-top:none;">Employee Sign:</td>
					</tr>
				</table>
				<input type="hidden" name="userid" value="'.$_POST['employee_id'].'" id="userid" >
				<input type="hidden" name="year" value="'.$year.'" >
				<input type="hidden" name="month" value="'.$month.'" >
			</form>
      		</div>
      		<div class="modal-footer">
        		<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        		<button type="button" class="btn btn-primary" onClick="print_pay_slip()">Print</button>';
				if($salRows == 0){
					echo '<button type="button" class="btn btn-primary" onClick="submitSalary()" >Pay Salary</button>';
				}
      		echo '</div>
    	</div>
	</div>';
		}
}
elseif($action == 'paySal')
{
	if($_POST['year'])
	{
		$year=$_POST['year'];
	}
	else
	{
		$year=date('Y');
	}
	if($_POST['month'])
	{
		$month=$_POST['month'];
	}
	else
	{
		$month=date('m');
	}
	
	$vars['userid']			= $_POST['userid'];
	$vars['pay_period'] = $year.'-'.$month.'-01';
	$vars['basic_pay'] = $_POST['basic_pay'];
	$vars['total_payable'] = $_POST['total_payable_amt'];
	$vars['payment_date'] = date('Y-m-d H:i:s');
	$vars['total_paid'] = $_POST['total_payable_amt'];
	$vars['payment_method'] = $_POST['paymentThrough'];
	$vars['payment_referance'] = $_POST['referance'];
	$vars['lossofpay_leaves'] = $_POST['working_days'] - $_POST['present_days'] - $_POST['earned_leaves'];
	$vars['earned_leaves'] = $_POST['earned_leaves'];
	$vars['leave_deduction'] = $_POST['leave_deduction'];
	$vars['total_earnings'] = $_POST['total_earnings'];
	$vars['total_deduction'] = $_POST['total_deduction'];
	$vars['total_payable_words'] = $_POST['total_payable_words'];
	$vars['worked_days'] = $_POST['working_days'];
	$vars['is_blocked'] = 0;
	
	$db->Insert($vars,'payroll_salary_pay');
	$paymentid = $db->LastInsertID();
	
	// Payment Details
	
	$data=array();
	$data['name'] = $_POST['e_d_name'];
	$data['amount'] = $_POST['e_d_amount'];
	$data['type'] = $_POST['e_d_type'];
	if(!empty($data['type'])){
		$count = count($data['type']);
		for($i=0;$i<$count;$i++){
			//echo "INSERT INTO payroll_salary_pay_details (payment_id, name, type,amount) VALUES(".$paymentid.",'".$data['name'][$i]."', '".$data['type'][$i]."', '".$data['amount'][$i]."')"."<br>";
			mysql_query("INSERT INTO payroll_salary_pay_details (payment_id, name, type,amount) VALUES(".$paymentid.",'".$data['name'][$i]."', '".$data['type'][$i]."', '".$data['amount'][$i]."')");
		}
	}
}

function salaryCalculation($designation,$basicPay,$type=1) {

		if($type == 1){
		
	$earningsDeduction = $GLOBALS[db]->fetchQuery("SELECT * FROM salary_designation A 
											   LEFT JOIN salary_structure B ON A.salary_structure_id = B.structure_id 
											   LEFT JOIN earning_deduction C ON B.earning_deduction_id	= C.id
											   WHERE A.designation_id='$designation' ORDER BY B.id ASC");
		}else{
		
		
	$earningsDeduction = $GLOBALS[db]->fetchQuery("SELECT * FROM salary_structure_employee A 
											   LEFT JOIN salary_structure B ON A.salary_structure_id = B.structure_id 
											   LEFT JOIN earning_deduction C ON B.earning_deduction_id	= C.id
											   WHERE A.employee_id='$designation' ORDER BY B.id ASC");	
		
		
		
		}								   
											   
											   
											   
	if($basicPay == 0){
			$basicPay = $earningsDeduction[0]['amount'];
	}										   
								   
	$eacalculation = array();
	$c=0;
	foreach($earningsDeduction as $eacalculation){
		// Get All earnings
		if($eacalculation['type'] == 1){
			$calculation['earnings'][$c]['name'] 		= $eacalculation['name'];
			$calculation['earnings'][$c]['parentid'] 		= $eacalculation['parent_id'];
			$calculation['earnings'][$c]['percentage'] 	= $eacalculation['percentage'];
			$calculation['earnings'][$c]['maxamount']	= $eacalculation['amount'];
			$calculation['earnings'][$c]['id']			= $eacalculation['id'];
			$maxamount = $eacalculation['amount'];
			if($eacalculation['parent_id'] == 0 ){
				$parentAmount = $basicPay;
			}else{
				$parentAmount =searchForId($eacalculation['parent_id'], $calculation['earnings']);  
			}
			
			$calculation['earnings'][$c]['calculateAmt']= calculatePercent($eacalculation,$parentAmount,$maxamount);
			
			
		}
		
		// Get all deduction
		if($eacalculation['type'] ==2){
			$calculation['deduction'][$c]['name'] 		= $eacalculation['name'];
			$calculation['deduction'][$c]['parentid'] 		= $eacalculation['parent_id'];
			$calculation['deduction'][$c]['percentage'] = $eacalculation['percentage'];
			$calculation['deduction'][$c]['maxamount']	= $eacalculation['amount'];
			$calculation['deduction'][$c]['id']			= $eacalculation['id'];
			$maxamount = $eacalculation['amount'];
			
			if($eacalculation['parent_id'] == 0 ){
			
				$parentAmount = $basicPay;
				
			}elseif($eacalculation['parent_id'] == 2){
			
				$parentAmount = getGrossPay($calculation['earnings'],$basicPay);
			
			}else{
				$parentAmount =searchForId($eacalculation['parent_id'], $calculation['earnings']);  
			}
			
			$calculation['deduction'][$c]['calculateAmt']= calculatePercent($eacalculation,$parentAmount,$maxamount);
			
		}
		
		$c++;	
	}
	
	//print_r($calculation);
	return $calculation;
}

function calculatePercent($eacalculation,$parentAmount,$maxamount){
	$basicpay = $parentAmount;
	$percent  = $eacalculation['percentage'];
	$amount = $basicpay*($percent/100);
	if(round($basicpay))
	{
		if($amount && round($maxamount))
		{
			$amount = ($amount < $maxamount)?$amount:$maxamount;
		}
		elseif($amount)
		{
			$amount =$amount;
		}
		else
		{
			$amount = $maxamount;
		}
	}
	else
	{
		$amount=0;
	}
	
	return $amount;
}

function searchForId($id, $array) {
   foreach ($array as $key => $val) {
       if ($val['id'] === $id) {
           return $val['calculateAmt'];
       }
   }
   return null;
}

function getGrossPay($earnings,$basicPay){
//print_r($earnings);
	$grossPay  = 0;
	foreach($earnings as $earnings){
		 $grossPay +=$earnings['calculateAmt'];
	}
	return $grossPay;
}

function convert_number_to_words($number) {
    
    $hyphen      = '-';
    $conjunction = ' and ';
    $separator   = ', ';
    $negative    = 'negative ';
    $decimal     = ' point ';
    $dictionary  = array(
        0                   => 'zero',
        1                   => 'one',
        2                   => 'two',
        3                   => 'three',
        4                   => 'four',
        5                   => 'five',
        6                   => 'six',
        7                   => 'seven',
        8                   => 'eight',
        9                   => 'nine',
        10                  => 'ten',
        11                  => 'eleven',
        12                  => 'twelve',
        13                  => 'thirteen',
        14                  => 'fourteen',
        15                  => 'fifteen',
        16                  => 'sixteen',
        17                  => 'seventeen',
        18                  => 'eighteen',
        19                  => 'nineteen',
        20                  => 'twenty',
        30                  => 'thirty',
        40                  => 'fourty',
        50                  => 'fifty',
        60                  => 'sixty',
        70                  => 'seventy',
        80                  => 'eighty',
        90                  => 'ninety',
        100                 => 'hundred',
        1000                => 'thousand',
        1000000             => 'million',
        1000000000          => 'billion',
        1000000000000       => 'trillion',
        1000000000000000    => 'quadrillion',
        1000000000000000000 => 'quintillion'
    );
    
    if (!is_numeric($number)) {
        return false;
    }
    
    if (($number >= 0 && (int) $number < 0) || (int) $number < 0 - PHP_INT_MAX) {
        // overflow
        trigger_error(
            'convert_number_to_words only accepts numbers between -' . PHP_INT_MAX . ' and ' . PHP_INT_MAX,
            E_USER_WARNING
        );
        return false;
    }

    if ($number < 0) {
        return $negative . convert_number_to_words(abs($number));
    }
    
    $string = $fraction = null;
    
    if (strpos($number, '.') !== false) {
        list($number, $fraction) = explode('.', $number);
    }
    
    switch (true) {
        case $number < 21:
            $string = $dictionary[$number];
            break;
        case $number < 100:
            $tens   = ((int) ($number / 10)) * 10;
            $units  = $number % 10;
            $string = $dictionary[$tens];
            if ($units) {
                $string .= $hyphen . $dictionary[$units];
            }
            break;
        case $number < 1000:
            $hundreds  = $number / 100;
            $remainder = $number % 100;
            $string = $dictionary[$hundreds] . ' ' . $dictionary[100];
            if ($remainder) {
                $string .= $conjunction . convert_number_to_words($remainder);
            }
            break;
        default:
            $baseUnit = pow(1000, floor(log($number, 1000)));
            $numBaseUnits = (int) ($number / $baseUnit);
            $remainder = $number % $baseUnit;
            $string = convert_number_to_words($numBaseUnits) . ' ' . $dictionary[$baseUnit];
            if ($remainder) {
                $string .= $remainder < 100 ? $conjunction : $separator;
                $string .= convert_number_to_words($remainder);
            }
            break;
    }
    
    if (null !== $fraction && is_numeric($fraction)) {
        $string .= $decimal;
        $words = array();
        foreach (str_split((string) $fraction) as $number) {
            $words[] = $dictionary[$number];
        }
        $string .= implode(' ', $words);
    }
    
    return $string;
}

?>