<?php
include_once("../class/class.MySQL.php");
$db	=new MySQL();
session_start();
error_reporting(0);

$action = $_GET['act'];
//echo "<pre>";

if($action == "lastms"){


			$cond='';$memberid='';$add_date1='';$from_date1 = '';$to_date1 = '';$branch = '';
				$userid=$_GET['userid'];
				$depart_id=$_GET['depart_id'];
		
		if(!empty($_REQUEST['add_date'])){
		$add_date=$_REQUEST['add_date'];
		$add_date1 = date('Y-m-d', strtotime($add_date));
		}
		
		if(!empty($_REQUEST['from_date'])){
		$from_date=$_REQUEST['from_date'];
		$from_date1 = date('Y-m-d', strtotime($from_date));
		}
		
		if(!empty($_REQUEST['to_date'])){
		$to_date=$_REQUEST['to_date'];
		$to_date1 = date('Y-m-d', strtotime($to_date));
		}
		
		if(!empty($_REQUEST['memberid'])){
		$memberid=$_REQUEST['memberid'];
		}
		if(!empty($_REQUEST['branch'])){
		$branch=$_REQUEST['branch'];
		}
			
		if($_SESSION['usertype'] != 'Subadmin')
		{	
			if(!empty($memberid))
			{
				$cond.='and A.e_id="'.$memberid.'"';
			}
		}
		else
		{
			$adminids = $_SESSION['admin_id'];
			$cond.='and A.e_id="'.$adminids.'"';
		}	
		if(!empty($branch))
		{
		$cond.='and A.branchid="'.$branch.'"';
		}
			
		 $query="SELECT * from employee A LEFT JOIN branches B ON A.branchid = B.branch_id WHERE 1 $cond";	
			
include "pagingserch_payroll.php";

$cond.=" LIMIT $start, $limit";
			

if(isset($_REQUEST['page'])){
$page=$_REQUEST['page'];
}else{
$page=25;
}

$pagecnt=$start;

	//$salaryAllusers  = $db->fetchAll("employee");
	$salaryAllusers= $db->fetchQuery("SELECT * from employee A LEFT JOIN branches B ON A.branchid = B.branch_id WHERE 1 $cond");
	//print_r($salary);
	//echo "SELECT * from employee A LEFT JOIN branches B ON A.branchid = B.branch_id WHERE 1 $cond";
	
	$salaryList = array();
	
		$requestedMonth	 =$_GET['salmonth'];
		$requestedYear	 =$_GET['salyear'];
		
		if(!$requestedMonth){
			$requestedMonth	 	= date("m",strtotime(" -1 months"));
			 $requestedYear		=date("Y",strtotime(" -1 months"));
		}
		
		$b=0;
		//print_r($salaryAllusers);
		
			
	
		foreach($salaryAllusers as $list){
		$over_time=0; $over_time_sal=0;
		$employeeid	=$list['e_id'];
		$branch_name	=$list['branch_name'];
		$brch_half	=$list['brch_half'];
		$over_time_cal	=$list['over_time'];
		$emp_basic_pay_cal	=$list['emp_basic_pay'];
		$overtime_status	=$list['overtime_status'];
		
		$perhoursal=($emp_basic_pay_cal*12)/(365*8);


	
			$totalDeductionAmt		=0;
			$totalBenefitAmt		=0;
			$totalContributionAmt	=0;
	

	
		
	 $givendate = "01-".$requestedMonth ."-". $requestedYear;
	 $endmonthdate = "31-".$requestedMonth ."-". $requestedYear;
	 
	 $startgivendate=$requestedYear."-".$requestedMonth."-"."01";
	 
	 $startenddate=$requestedYear."-".$requestedMonth."-"."31";
	 
	 
	 $reporttimeAllusers= $db->fetchQuery("SELECT late_time from report_time  WHERE brch_id=$branch");
	 
	  $report_time=$reporttimeAllusers[0]['late_time'];
	 
	
	 //$fulldaydetails = $db->fetchQuery("Select count(*) as fullday from time where e_id=$employeeid and e_in<='$report_time' and e_date>='$startgivendate' and e_date<='$startenddate' and total_worked_hours > '06:00:00'");
	$fulldaydetails = $db->fetchQuery("Select e_date,total_worked_hours from time as A where e_id=$employeeid and (select e_in from time as B where B.e_id=A.e_id and B.e_date=A.e_date order by id asc limit 1)<='$report_time' and e_date>='$startgivendate' and e_date<='$startenddate' and (select total_worked_hours from time as B where B.e_id=A.e_id and B.e_date = A.e_date order by B.id desc limit 1) > '06:00:00' group by e_date");
	 if(!empty($fulldaydetails))
	 $fulldays=count($fulldaydetails);
	else
	$fulldays=0;
	foreach($fulldaydetails as $fulldaydate)
	{
	$full_date=$fulldaydate['e_date'];
	if($brch_half=='1')
	{
			if(date('w', strtotime($full_date)) == 6) 
				{
				   $worked_hours=$fulldaydate['total_worked_hours'];
				//	$strwork=strtotime('09:00:00')-strtotime($worked_hours);
					//echo date('H:i:s',$strwork);
					//echo "<br/>";		
					if($overtime_status=='1')
					{
					$from_time = strtotime($worked_hours);
					$to_time = strtotime("04:00:00");
					$over_time=$over_time + intval(abs(($to_time - $from_time) / 3600));
					}
				} 
	}
	}
	
	 //$latetimedetails = $db->fetchQuery("Select count(*) as lateday from time where e_id= and (time_in>'$report_time' or time_inloc='PM') and e_date>='$startgivendate' and e_date<='$startenddate' ");
	
	  $latetimedetails = $db->fetchQuery("Select e_date,total_worked_hours from time as A where e_id=$employeeid and ((select e_in from time as B where B.e_id=A.e_id and B.e_date=A.e_date order by id asc limit 1)>'$report_time' ) and e_date>='$startgivendate' and e_date<='$startenddate' and (select total_worked_hours from time as B where B.e_id=A.e_id and B.e_date = A.e_date order by A.id desc limit 1) > '06:00:00' group by e_date");
	 
	 if(!empty($latetimedetails))
	 $latedays=count($latetimedetails);
	 else
	$latedays=0;
	foreach($latetimedetails as $latetimedate)
	{
	$late_date=$latetimedate['e_date'];
	if($brch_half=='1')
	{
			if(date('w', strtotime($late_date)) == 6) 
				{
				   $worked_hours=$latetimedate['total_worked_hours'];
				//	$strwork=strtotime('09:00:00')-strtotime($worked_hours);
					//echo date('H:i:s',$strwork);
					//echo "<br/>";		
					if($overtime_status=='1')
					{
					$from_time = strtotime($worked_hours);
					$to_time = strtotime("04:00:00");
					$over_time=$over_time + intval(abs(($to_time - $from_time) / 3600));
				     }
				} 
	}
	}
	  
	 // $halfdaysapplied = $db->fetchQuery("Select count(*) as halfday from payroll_user_leave_requests where employee_id=$employeeid and half_full_day='1' and is_cancelled=0 and imd_status=1 and day_from>='$startgivendate' and day_from<='$startenddate' ");
	 
	  
	  
	  $halfdaysapplied = $db->fetchQuery("Select e_date,total_worked_hours from time as A where e_id=$employeeid and e_date>='$startgivendate' and e_date<='$startenddate' and (select total_worked_hours from time as B where B.e_id=A.e_id and B.e_date = A.e_date order by B.id desc limit 1) < '06:00:00' and (select total_worked_hours from time as B where B.e_id=A.e_id and B.e_date = A.e_date order by B.id desc limit 1) > '03:00:00' group by e_date");
	  
	 //$latetimedetails = $db->fetchQuery("Select count(*) as lateday from time where e_id=$employeeid and (time_in>'$report_time' or time_inloc='PM') and e_date>='$startgivendate' and e_date<='$startenddate' ");
	 if(!empty($halfdaysapplied)) 
	 $halfdays=count($halfdaysapplied);
	else
	$halfdays=0;
	
	foreach($halfdaysapplied as $halfdaydate)
	{
	$half_date=$halfdaydate['e_date'];
	if($brch_half=='1')
	{
			if(date('w', strtotime($half_date)) == 6) 
				{
				
				   $worked_hours=$halfdaydate['total_worked_hours'];
				   if($halfdaydate['time_in']<=$report_time)
				   {
				   $halfdays=$halfdays-1;
				   $fulldays=$fulldays+1;
				   }
				   else
				   {
				   $halfdays=$halfdays-1;
				   $latedays=$latedays+1;
				   
				   }
				//	$strwork=strtotime('09:00:00')-strtotime($worked_hours);
					//echo date('H:i:s',$strwork);
					//echo "<br/>";		
					if($overtime_status=='1')
					{
					$from_time = strtotime($worked_hours);
					$to_time = strtotime("04:00:00");
					$over_time=$over_time + intval(abs(($to_time - $from_time) / 3600));
					}
				} 
	}
	
	}
	
	
	 $nolossleaveapplied = $db->fetchQuery("Select count(*) as nolossleave from payroll_user_leave_requests where employee_id=$employeeid and is_cancelled=0 and imd_status=1 and day_from>='$startgivendate' and day_from<='$startenddate' and (leave_id='20' or leave_id='21' or leave_id='22') ");
	 
	   $nolossleave=$nolossleaveapplied[0]['nolossleave'];
	
	  
	  $totalattendance = ($fulldays)+($halfdays*0.5)+($latedays);
	
	$totalattendance =$totalattendance - ((intval($latedays/3))*0.5);
	
	 if($overtime_status=='1')
	  {
	  $overworkdetails = $db->fetchQuery("Select * from time as A where e_id=$employeeid and  e_date>='$startgivendate' and e_date<='$startenddate' and (select total_worked_hours from time as B where B.e_id=A.e_id and B.e_date = A.e_date order by B.id desc limit 1) > '10:00:00'");
	  
	 	foreach($overworkdetails as $overwork)
		{
		$check_sat_date=$overwork['e_date'];
		 $worked_hours=$overwork['total_worked_hours'];
	//	$strwork=strtotime('09:00:00')-strtotime($worked_hours);
		//echo date('H:i:s',$strwork);
		//echo "<br/>";	
		if(date('w', strtotime($check_sat_date)) != 6) 
				{	
		$from_time = strtotime($worked_hours);
		$to_time = strtotime("09:00:00");
         $over_time=$over_time + intval(abs(($to_time - $from_time) / 3600));
		 }
		}

	}	 
	 //////////////////////////////////////////////// Check Payment Status //////////////////////////////////////////////////////////////////////
		
		$requestedDate = date('Y-m',strtotime($givendate)).'-01';
		
		$paymentDetails= $db->fetchQuery("SELECT A.userid,A.leave_deduction,B.deduction_total_amount as totalamount,B.deduction_id,
												C.*,D.*,A.earned_leaves as earnesLeaves ,A.lossofpay_leaves,
												A.basic_pay as emp_basic_pay,A.allowance_amt as allowance_amt,A.incentive_amt as incentive_amt,A.worked_days as worked_days
												FROM payroll_salary_pay A 
												
												LEFT JOIN payroll_payment_details B ON A.id = B.payment_id 
												LEFT JOIN payroll_benifits_deductions C ON B.deduction_id = C.id 
												LEFT JOIN employee D ON A.userid= D.e_id  WHERE pay_period ='$requestedDate' and userid='$employeeid'");
		
		
	
		
	
		$salRows = count($paymentDetails);
		
		if($salRows > 0){	
		$totalleavededuction=$paymentDetails[0]['leave_deduction'];
		$allowance_amt=$paymentDetails[0]['allowance_amt'];
		$incentive_amt=$paymentDetails[0]['incentive_amt'];
		$worked_days=$paymentDetails[0]['worked_days'];
			$paymentStatus = 1;
		}else{
			$totalleavededuction='';$allowance_amt=0;$incentive_amt=0;
			$paymentStatus = 0;$worked_days = 0;
		}
	 
		//echo $givendate;
		$last_month = date('F',strtotime($givendate));
		$lastmonth = date('m',strtotime($givendate));
		$daysLastMth = date('t',strtotime($givendate));
		$yearofLastMth = date('Y',strtotime($givendate));
		 
		$date = $yearofLastMth."-".$lastmonth."-01";


		$firstOfLastmth= date('Y-m-01', strtotime($date));
		$endOfLastmth= date('Y-m-t', strtotime($date));
		 

		 
		 $lastMtnHolidays = $db->fetchQuery("SELECT * FROM payroll_holiday_calendar WHERE MONTH(date)='$lastmonth' and YEAR(date)='$yearofLastMth' and is_blocked='0'");
		 $holidays=array();
		 foreach($lastMtnHolidays as $lastMtnHolidays){
			$holidays[]=$lastMtnHolidays['date'];
		 }
		$workingDays=  $db->getWorkingDays($firstOfLastmth,$endOfLastmth,$holidays);
		$inquery='';
		
		if($overtime_status=='1')
	  {
		foreach($holidays as $holidaydate)
		{
		 $inquery.="'".$holidaydate."',";
		
		}
		
		 $inquery=substr($inquery, 0,-1);
	 $over_holiday_work=$db->fetchQuery("SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(total_worked_hours))) as over_work FROM `time` WHERE e_id=15 and e_date IN ($inquery)");
		 if(!empty($over_holiday_work) && $over_holiday_work[0]['over_work']>0)
		 {
		   $over_holiday_hours=date('H',strtotime($over_holiday_work[0]['over_work']));
		 }
		 else
		 {
		 $over_holiday_hours=0;
		 }
	 }
	  $over_time_sal=($over_time_cal*$perhoursal*($over_time + $over_holiday_hours))/100;
	 
	 $over_time=$over_time + $over_holiday_hours;
		//////////////////////////////////////////////// Check Payment Status //////////////////////////////////////////////////////////////////////
		
		
		
		///////////////////////////////////////////////// Start Payslip details collection /////////////////////////////////////////////////////////
		
		
		 /// Monthly requested leaves;
		 //find allowed leaves and leave tyes
		 		 
		 $leaves = $db->fetchQuery("SELECT * FROM payroll_user_leave_requests WHERE employee_id='$employeeid' AND (MONTH(day_from) ='$lastmonth' OR MONTH(day_to) ='$lastmonth') ");
		  $a=0;
		//  echo "SELECT * FROM payroll_user_leave_requests WHERE employee_id='$employeeid' AND (MONTH(day_from) ='$lastmonth' OR MONTH(day_to) ='$lastmonth') ";
		$totalleaves = 0;
		 foreach($leaves as $leaves){
		 	$day_from 	= $leaves['day_from'];
			$day_to		= $leaves['day_to'];
			
			if($endOfLastmth > $day_from &&  $endOfLastmth < $day_to){
				$totalleaves += $db->getWorkingDays( $day_from,$endOfLastmth ,$holidays);
				
			}elseif($firstOfLastmth > $day_from &&  $endOfLastmth > $day_to){
				$totalleaves += $db->getWorkingDays( $firstOfLastmth,$day_to ,$holidays);
				
			}elseif($day_to > $firstOfLastmth &&  $day_from > $firstOfLastmth && $day_to < $endOfLastmth &&  $day_from < $endOfLastmth){
				$totalleaves += $db->getWorkingDays( $day_from,$day_to ,$holidays);
			}
			
			$a++;
		 }
		$totalleaves_final =  0;
	$totallossleaves_final = $workingDays - $totalattendance - $nolossleave;
	
	
			// Mthly allowed leaves
			$mthlyAllowedLeaves = $db->fetchQuery("SELECT * FROM payroll_user_leave A
														LEFT JOIN payroll_leave B ON A.leave_id=B.lid WHERE A.employee_id='$employeeid' and B.based_on='1'");
			$totalAllowedLeavesPerMth=0;
			$totallossofpay=0;												
			foreach($mthlyAllowedLeaves as $mthlyAllowedLeaves){
				if($mthlyAllowedLeaves['earned'] == 1){
					$totalAllowedLeavesPerMth += $mthlyAllowedLeaves['number_of_days'];
				}else{
					$totallossofpay +=$mthlyAllowedLeaves['number_of_days'];
				}
				
			}											
			
								

			
			
			// Yearly allowed leaves
			$yearlyAllowedLeaves = $db->fetchQuery("SELECT * FROM payroll_user_leave A
														LEFT JOIN payroll_leave B ON A.leave_id=B.lid WHERE A.employee_id='$employeeid' and B.based_on='2'");
			$totalAllowedLeavesPeryearly=0;
										
			foreach($yearlyAllowedLeaves as $yearlyAllowedLeaves){
			
				if($yearlyAllowedLeaves['earned'] == 1){
					$totalAllowedLeavesPeryearly += $yearlyAllowedLeaves['number_of_days'];
				}else{
					$totallossofpay +=$yearlyAllowedLeaves['number_of_days'];
				}
			}											
			
			// Yearly requested leaves
			$yearlyRequestedLeaves = $db->fetchQuery("SELECT * FROM payroll_user_leave_requests A 
														LEFT JOIN payroll_leave B ON A.leave_id = B.lid 
														WHERE A.employee_id='$employeeid' AND A.half_full_day='2' 
														AND B.based_on='2' and (YEAR(day_from) ='$yearofLastMth' or YEAR(day_to)='$yearofLastMth')");
			$yearlyRequestedLeave=0;
														
			foreach($yearlyRequestedLeaves as $yearlyRequestedLeaves){
					$yearlyRequestedLeave += $yearlyRequestedLeaves['no_of_days'];
			}										
			//fecho $yearlyRequestedLeave;	
			
			/////// Balance leaves in this year (earned);
			$balanceLeavesInThisYear =  $totalAllowedLeavesPeryearly-$yearlyRequestedLeave;	
			
			/////// Balance leaves in this Mth (earned);
			$leavesInthisMth =$totalAllowedLeavesPerMth-$totalleaves;
			
			
			/////// Leave calculation based on month.
			if($totalAllowedLeavesPerMth < $totalleaves){
				$lossofpayleaves = $totalleaves-$totalAllowedLeavesPerMth;
				$earnedLeaves	 = $totalAllowedLeavesPerMth;
			}else{
				$lossofpayleaves = 0;
				$earnedLeaves	 = $totalleaves;
			}	
			
			if($lossofpayleaves > 0 ){
				
			/////// Check Requested Leave from yearly based;
				if($yearlyRequestedLeave > 0 && $lossofpayleaves  > $yearlyRequestedLeave){
				
					$lossofpayleaves = $lossofpayleaves-$yearlyRequestedLeave;
					$earnedLeaves	 = $earnedLeaves + $yearlyRequestedLeave;
					
				}elseif($yearlyRequestedLeave > 0 && $lossofpayleaves  < $yearlyRequestedLeave){
				
					$lossofpayleaves = $yearlyRequestedLeave-$lossofpayleaves;
					$earnedLeaves	 = $earnedLeaves + ($yearlyRequestedLeave-$lossofpayleaves);
					
				}
				
			}
			
			
											
		 
		
		
		 
			$totalWorkingdays = $db->fetchQuery("SELECT count(e_id) as totalDays FROM time WHERE e_id='$employeeid' and MONTH(e_date)='$lastmonth' GROUP BY DAY(e_date)");
			$count =count($totalWorkingdays);
			
			if($lossofpayleaves > 0){
				$basicSal = " (A.emp_basic_pay - (A.emp_basic_pay/'$daysLastMth') * $lossofpayleaves)";
			}else{
				$basicSal = "  A.emp_basic_pay";
			}
			
			
			
		 $salary  = $db->fetchQuery("SELECT *, IF(C.unit = 2, $basicSal*C.amount/100,amount) as totalamount
			FROM employee A LEFT JOIN payroll_user_deductions B ON A.e_id = B.employee_id LEFT JOIN payroll_benifits_deductions C ON B.deduction_id= C.id WHERE A.e_id='$employeeid' order by c.name desc");


			$salRows = count($salary);
			
			
			for($k=0;$k<$salRows;$k++)
			{
			 $name_ded=$salary[$k]['name'];
			 $emp_basic_pay=$salary[$k]['emp_basic_pay'];
			
			 $amount_ded=$salary[$k]['amount'];
			$salary_DA  = $db->fetchQuery("SELECT amount from payroll_benifits_deductions where emp_id ='$employeeid' and name='DA'");
			if(!empty($salary_DA))
			 $DA=$salary_DA[0]['amount'];
			else
			 $DA=0;
			 
			 $salary_ALLOWANCE  = $db->fetchQuery("SELECT amount from payroll_benifits_deductions where emp_id ='$employeeid' and name='ALLOWANCE'");
			if(!empty($salary_ALLOWANCE))
			 $ALLOWANCE=$salary_ALLOWANCE[0]['amount'];
			else
			 $ALLOWANCE=0;
			 
			if($name_ded=='PF')
			{
			
			
				if(($emp_basic_pay+$DA) <= 6500)
				{
				 $totalamount_PF=($amount_ded*($emp_basic_pay+$DA))/100;
				$salary[$k]['totalamount']=$totalamount_PF;
				}
				else
				{
				$salary[$k]['totalamount']=$totalamount_PF=0;
				}
				
			
			
			}
			
			/*if($name_ded=='ESI')
			{
			$ded_amount=0;$earn_amount=0;
			$salary_ESI_earn  = $db->fetchQuery("SELECT * from payroll_benifits_deductions where emp_id ='$employeeid' and is_blocked=0 and name!='PF' and name!='ESI'");
			
			if(!empty($salary_ESI_earn))
			{	
			foreach($salary_ESI_earn as $salary_ESI_earns)
			{
				$ded_earn=$salary_ESI_earns['deduction_benefit'];
				$ded_earn_unit=$salary_ESI_earns['unit'];
				 $ded_earn_rp=$salary_ESI_earns['amount'];
				
				if($ded_earn_unit==2)
				{
				$ded_earn_amount=($ded_earn_rp*$emp_basic_pay)/100;
				}
				else
				{
				$ded_earn_amount=$ded_earn_rp;
				}
				
				if($ded_earn==1)
				{
				$ded_amount=$ded_amount+$ded_earn_amount;
				}
				elseif($ded_earn==2)
				{
				$earn_amount=$earn_amount+$ded_earn_amount;
				}
				
			}
			$earn_amount=$earn_amount+$emp_basic_pay;
			}		
			
			if(($earn_amount-($ded_amount+$totalamount_PF)) < 15000)
			{
			$salary[$k]['totalamount']=$totalamount_ESI=($amount_ded*($earn_amount-($ded_amount+$totalamount_PF)))/100;
			}
			else
			{$salary[$k]['totalamount']=$totalamount_ESI=0;
			}
			}*/
			
			if($name_ded=='ESI')
			{
				if(($emp_basic_pay+$ALLOWANCE) <= 15000)
				{
				 $totalamount_ALLOWANCE=($amount_ded*($emp_basic_pay+$ALLOWANCE))/100;
				$salary[$k]['totalamount']=$totalamount_ALLOWANCE;
				}
				else
				{
				$salary[$k]['totalamount']=$totalamount_ALLOWANCE=0;
				}
				
			}
			
			}
			
			
			//if($lossofpayleaves > 0){
			//	$salary[$salRows-1]['emp_basic_pay'] = $salary[$salRows-1]['emp_basic_pay']-(($salary[$salRows-1]['emp_basic_pay']/$daysLastMth)*$lossofpayleaves);
			//}
			$salary[$salRows-1]['totalDays'] = $count;
			$salary[$salRows-1]['lastMonthDays'] =  $workingDays-$earnedLeaves-$lossofpayleaves;
			$salary[$salRows-1]['totalDays'] =$daysLastMth;
			$salary[$salRows-1]['over_time'] =  $over_time;
			$salary[$salRows-1]['earnesLeaves'] =  $earnedLeaves;
			$salary[$salRows-1]['lossofpay'] =  $lossofpayleaves;
			$salary[$salRows-1]['status'] 	 = "notpaid";
			
			$lossofpayattendance=0;
			
			$lossofpayattendance=0;
			
			//$paymentperDay = ($list['emp_basic_pay']/$daysLastMth)*$lossofpayleaves;
			$paymentperDay = ($list['emp_basic_pay']/$daysLastMth)*$totallossleaves_final;
			
			if($totalleavededuction=='')
			{
			$totalleavededuction=$paymentperDay;
			}
			else
			{
			$paymentperDay=$totalleavededuction;
			}
			
		
			foreach($salary as $key){
			
				if($key['deduction_benefit'] == '1'){
				
					 $totalDeductionAmt += $key['totalamount'];
					 
				}elseif($key['deduction_benefit'] == '2'){
				
					 $totalBenefitAmt	+= $key['totalamount'];
					 
				}else{
				
					 $totalContributionAmt	+= $key['totalamount'];
					 
				}
				//print_r($deductions);
			}
			
		
			$a++;
			$salaryList[$b]['over_time_sal'] 	= $over_time_sal;
			$salaryList[$b]['over_time'] 	= $over_time;
			$salaryList[$b]['worked_days'] 	= $worked_days;
			$salaryList[$b]['incentive_amt'] 	= $incentive_amt;
			$salaryList[$b]['allowance_amt'] 	= $allowance_amt;
			$salaryList[$b]['paymentStatus'] 	= $paymentStatus;
			$salaryList[$b]['employee_id'] 	= $employeeid;
			$salaryList[$b]['name'] 		= $list['e_fname'];
			$salaryList[$b]['basic_pay'] 	= $list['emp_basic_pay'];
			$salaryList[$b]['deduction'] 	= $totalDeductionAmt+$paymentperDay;
			$salaryList[$b]['benefit'] 	= $totalBenefitAmt;
			$salaryList[$b]['contribution'] = $totalContributionAmt;
			$salaryList[$b]['branch_name'] = $branch_name;
			$salaryList[$b]['totalleavededuction'] = $totalleavededuction;
		$b++;
	}
	
	
	$count = count($salaryList);
	$salaryList[$count-1]['totalrows'] = $total_pages;
	
	$tablehtml='';
	
	$tablehtml.='<table width="100%" border="1" cellspacing="0" style="display:none" cellpadding="0" class="list-employees"> 
								<tr>
								<td width="20%" height="17" colspan="13" align="center">Salary List for the period '.$last_month.'</td>								
								</tr>
								<tr>
								<td width="20%" height="17">Name</td>
								<td width="10%">Branch</td>
								<td width="12%">Basic Pay</td>
								<td width="11%">Deductions</td>
								<td width="11%">Loss of Pay</td>
								<td width="11%">Worked Days</td>
								<td width="11%">Earnings</td>
								<td width="11%">Allowance</td>
								<td width="11%">Incentive</td>
								<td width="11%">PF</td>
								<td width="11%">ESI</td>
								<td width="16%">Employer Contributions</td>
								<td width="11%">Total Payable</td>
								
								</tr>
							';
							
							
							foreach($salaryList as $listsalary)
							{
							if($listsalary['paymentStatus']=='1')
							{
							$employee_id=$listsalary['employee_id'];
							
							$pf_esi_details  = $db->fetchQuery("SELECT * from pf_esi_details where emp_id ='$employee_id' and pay_period='$requestedDate'");
							if(!empty($pf_esi_details))
							{
							$pf=$pf_esi_details[0]['emp_pf'];
							$esi=$pf_esi_details[0]['emp_esi'];
							}
							else
							{
							$pf=0;$esi=0;
							}
							$tablehtml.= '<tr>
							<td width="20%" height="17">'.$listsalary['name'].'</td>
							
							<td width="10%" height="17">'.$listsalary['branch_name'].'</td>
											<td width="12%">'.round($listsalary['basic_pay'],2).'</td>
											<td width="11%">'.round($listsalary['deduction'],2).'</td>
											<td width="11%">'.round($listsalary['totalleavededuction'],2).'</td>
											<td width="11%">'.round($listsalary['worked_days'],2).'</td>
											<td width="11%">'.round($listsalary['benefit'],2).'</td>
											
											<td width="16%">'.round($listsalary['allowance_amt'],2).'</td>
											<td width="16%">'.round($listsalary['incentive_amt'],2).'</td>
											<td width="16%">'.round($pf,2).'</td>
											<td width="16%">'.round($esi,2).'</td>
											<td width="16%">'.round(($pf+$esi),2).'</td>
											<td width="11%">'.round(($listsalary['basic_pay']-$listsalary['deduction']+$listsalary['benefit']),2).'</td>
											
											</tr>';
							}
							}
							$tablehtml.= '</table>';
							$_SESSION['tablehtml']=$tablehtml;
	echo '{"salaryDetails":'.json_encode($salaryList).'}';
	
}

elseif($action == "getwages"){


			$cond='';$memberid='';$add_date1='';$from_date1 = '';$to_date1 = '';$branch = '';
				$userid=$_GET['userid'];
				$depart_id=$_GET['depart_id'];
		
		if(!empty($_REQUEST['add_date'])){
		$add_date=$_REQUEST['add_date'];
		$add_date1 = date('Y-m-d', strtotime($add_date));
		}
		
		if(!empty($_REQUEST['from_date'])){
		$from_date=$_REQUEST['from_date'];
		$from_date1 = date('Y-m-d', strtotime($from_date));
		}
		
		if(!empty($_REQUEST['to_date'])){
		$to_date=$_REQUEST['to_date'];
		$to_date1 = date('Y-m-d', strtotime($to_date));
		}
		
		if(!empty($_REQUEST['memberid'])){
		$memberid=$_REQUEST['memberid'];
		}
		if(!empty($_REQUEST['branch'])){
		$branch=$_REQUEST['branch'];
		}
			
			
			if(!empty($memberid))
		{
		$cond.='and A.e_id="'.$memberid.'"';
		}
		if(!empty($branch))
		{
		$cond.='and A.branchid="'.$branch.'"';
		}
			
		 $query="SELECT * from employee A LEFT JOIN branches B ON A.branchid = B.branch_id WHERE 1 $cond";	
			
include "pagingserch_payroll.php";

$cond.=" LIMIT $start, $limit";
			

if(isset($_REQUEST['page'])){
$page=$_REQUEST['page'];
}else{
$page=25;
}

$pagecnt=$start;

	//$salaryAllusers  = $db->fetchAll("employee");
	$salaryAllusers= $db->fetchQuery("SELECT * from employee A LEFT JOIN branches B ON A.branchid = B.branch_id WHERE 1 $cond");
	//print_r($salary);
	
	
	$salaryList = array();
	
		$requestedMonth	 =$_GET['salmonth'];
		$requestedYear	 =$_GET['salyear'];
		
		if(!$requestedMonth){
			$requestedMonth	 	= date("m",strtotime(" -1 months"));
			 $requestedYear		=date("Y",strtotime(" -1 months"));
		}
		
		$b=0;
		//print_r($salaryAllusers);
		
			
	
		foreach($salaryAllusers as $list){
		
		$employeeid	=$list['e_id'];
		$branch_name	=$list['branch_name'];
		
		//echo $employeeid;
	/*
	
	
	$sal=array();
	$a=0;
	foreach($salary as $salary){
		$sal[$a]['employee_id']	=$salary['e_id'];
		$sal[$a]['name']		=$salary['e_fname'];
		$sal[$a]['basic_pay']	=$salary['emp_basic_pay'];
		$basicpay = $salary['emp_basic_pay'];
		
		
		$deductions = $db->fetchQuery("SELECT 	sum( IF(C.unit = 2, $basicpay*C.amount/100,amount)) as benefits ,deduction_benefit
		FROM payroll_user_deductions B  
		LEFT JOIN payroll_benifits_deductions C 
		ON B.deduction_id= C.id WHERE B.employee_id=".$salary['e_id']." GROUP BY C.deduction_benefit");
		//print_r($ded);
	
		$sal[$a]['deduction']=0;
		$sal[$a]['benefit']=0;
		$sal[$a]['contribution']=0;
	//print_r($ded);
		foreach($deductions as $value){
		
			if($value['deduction_benefit'] == '1'){
			
				$sal[$a]['deduction'] += $value['benefits'];
			}elseif($value['deduction_benefit'] == '2'){
				$sal[$a]['benefit']	+= $value['benefits'];
			}else{
				$sal[$a]['contribution']	+= $value['benefits'];
			}
			//print_r($deductions);
		}
		
		$a++;
	}*/
	//print_r($sal);
	
			$totalDeductionAmt		=0;
			$totalBenefitAmt		=0;
			$totalContributionAmt	=0;
	

	
		
	 $givendate = "01-".$requestedMonth ."-". $requestedYear;
	 $endmonthdate = "31-".$requestedMonth ."-". $requestedYear;
	 
	 $startgivendate=$requestedYear."-".$requestedMonth."-"."01";
	 
	 $startenddate=$requestedYear."-".$requestedMonth."-"."31";

	 
	 $reporttimeAllusers= $db->fetchQuery("SELECT late_time from report_time  WHERE brch_id=$branch");
	 
	   $report_time=$reporttimeAllusers[0]['late_time'];
	 
	
	 //$fulldaydetails = $db->fetchQuery("Select count(*) as fullday from time where e_id=$employeeid and e_in<='$report_time' and e_date>='$startgivendate' and e_date<='$startenddate' and total_worked_hours > '06:00:00'");
	
	 
	$fulldaydetails = $db->fetchQuery("Select count(distinct(e_date)) as fullday from time as A where e_id=$employeeid and (select e_in from time as B where B.e_id=A.e_id and B.e_date=A.e_date order by id asc limit 1)<='$report_time' and e_date>='$startgivendate' and e_date<='$startenddate' and (select total_worked_hours from time as B where B.e_id=A.e_id and B.e_date = A.e_date order by B.id desc limit 1) > '06:00:00'");
	 
	$fulldays=$fulldaydetails[0]['fullday'];
	
	
	 //$latetimedetails = $db->fetchQuery("Select count(*) as lateday from time where e_id= and (time_in>'$report_time' or time_inloc='PM') and e_date>='$startgivendate' and e_date<='$startenddate' ");
	
	  $latetimedetails = $db->fetchQuery("Select count(distinct(e_date)) as lateday from time as A where e_id=$employeeid and ((select e_in from time as B where B.e_id=A.e_id and B.e_date=A.e_date order by id asc limit 1)>'11:00:00' ) and e_date>='$startgivendate' and e_date<='$startenddate' and (select total_worked_hours from time as B where B.e_id=A.e_id and B.e_date = A.e_date order by A.id desc limit 1) > '06:00:00'");
	 
	$latedays=$latetimedetails[0]['lateday'];
	 

	  
	 // $halfdaysapplied = $db->fetchQuery("Select count(*) as halfday from payroll_user_leave_requests where employee_id=$employeeid and half_full_day='1' and is_cancelled=0 and imd_status=1 and day_from>='$startgivendate' and day_from<='$startenddate' ");
	 
	  
	  
	  $halfdaysapplied = $db->fetchQuery("Select count(distinct(e_date)) as halfday from time as A where e_id=$employeeid and e_date>='$startgivendate' and e_date<='$startenddate' and (select total_worked_hours from time as B where B.e_id=A.e_id and B.e_date = A.e_date order by B.id desc limit 1) < '06:00:00' and (select total_worked_hours from time as B where B.e_id=A.e_id and B.e_date = A.e_date order by B.id desc limit 1) > '03:00:00'");
	 //$latetimedetails = $db->fetchQuery("Select count(*) as lateday from time where e_id=$employeeid and (time_in>'$report_time' or time_inloc='PM') and e_date>='$startgivendate' and e_date<='$startenddate' ");
	  
	$halfdays=$halfdaysapplied[0]['halfday'];
	
	 $nolossleaveapplied = $db->fetchQuery("Select count(*) as nolossleave from payroll_user_leave_requests where employee_id=$employeeid and is_cancelled=0 and imd_status=1 and day_from>='$startgivendate' and day_from<='$startenddate' and (leave_id='20' or leave_id='21' or leave_id='22') ");
	 
	   $nolossleave=$nolossleaveapplied[0]['nolossleave'];
	
	  
	  $totalattendance = ($fulldays)+($halfdays*0.5)+($latedays);
	
	$totalattendance =$totalattendance - ((round($latedays/3))*0.5);
	  
	 

	 //////////////////////////////////////////////// Check Payment Status //////////////////////////////////////////////////////////////////////
		
		$requestedDate = date('m-Y',strtotime($givendate));
		$paymentDetails= $db->fetchQuery("SELECT A.userid,B.deduction_total_amount as totalamount,B.deduction_id,
												C.*,D.*,A.earned_leaves as earnesLeaves ,A.lossofpay_leaves,
												A.basic_pay as emp_basic_pay
												FROM payroll_salary_pay A 
												
												LEFT JOIN payroll_payment_details B ON A.id = B.payment_id 
												LEFT JOIN payroll_benifits_deductions C ON B.deduction_id = C.id 
												LEFT JOIN employee D ON A.userid= D.e_id  WHERE pay_period ='$requestedDate' and userid='$employeeid'");
		
		
		
		
	
		//print_r($paymentDetails);
		$salRows = count($paymentDetails);
		if($salRows > 0){	
			$paymentStatus = 1;
		}else{
			$paymentStatus = 0;
		}
	 
		//echo $givendate;
		$lastmonth = date('m',strtotime($givendate));
		$daysLastMth = date('t',strtotime($givendate));
		$yearofLastMth = date('Y',strtotime($givendate));
		 
		$date = $yearofLastMth."-".$lastmonth."-01";


		$firstOfLastmth= date('Y-m-01', strtotime($date));
		$endOfLastmth= date('Y-m-t', strtotime($date));
		 

		 
		 $lastMtnHolidays = $db->fetchQuery("SELECT * FROM payroll_holiday_calendar WHERE MONTH(date)='$lastmonth' and YEAR(date)='$yearofLastMth' and is_blocked='0'");
		 $holidays=array();
		 foreach($lastMtnHolidays as $lastMtnHolidays){
			$holidays[]=$lastMtnHolidays['date'];
		 }
		$workingDays=  $db->getWorkingDays($firstOfLastmth,$endOfLastmth,$holidays);
		
		
		
		//////////////////////////////////////////////// Check Payment Status //////////////////////////////////////////////////////////////////////
		
		
		
		///////////////////////////////////////////////// Start Payslip details collection /////////////////////////////////////////////////////////
		
		
		 /// Monthly requested leaves;
		 //find allowed leaves and leave tyes
		 		 
		 $leaves = $db->fetchQuery("SELECT * FROM payroll_user_leave_requests WHERE employee_id='$employeeid' AND (MONTH(day_from) ='$lastmonth' OR MONTH(day_to) ='$lastmonth') ");
		  $a=0;
		//  echo "SELECT * FROM payroll_user_leave_requests WHERE employee_id='$employeeid' AND (MONTH(day_from) ='$lastmonth' OR MONTH(day_to) ='$lastmonth') ";
		$totalleaves = 0;
		 foreach($leaves as $leaves){
		 	$day_from 	= $leaves['day_from'];
			$day_to		= $leaves['day_to'];
			
			if($endOfLastmth > $day_from &&  $endOfLastmth < $day_to){
				$totalleaves += $db->getWorkingDays( $day_from,$endOfLastmth ,$holidays);
				
			}elseif($firstOfLastmth > $day_from &&  $endOfLastmth > $day_to){
				$totalleaves += $db->getWorkingDays( $firstOfLastmth,$day_to ,$holidays);
				
			}elseif($day_to > $firstOfLastmth &&  $day_from > $firstOfLastmth && $day_to < $endOfLastmth &&  $day_from < $endOfLastmth){
				$totalleaves += $db->getWorkingDays( $day_from,$day_to ,$holidays);
			}
			
			$a++;
		 }
		$totalleaves_final =  0;
	 $totallossleaves_final = $workingDays - $totalattendance - $nolossleave;
	
	
	 
			// Mthly allowed leaves
			$mthlyAllowedLeaves = $db->fetchQuery("SELECT * FROM payroll_user_leave A
														LEFT JOIN payroll_leave B ON A.leave_id=B.lid WHERE A.employee_id='$employeeid' and B.based_on='1'");
			$totalAllowedLeavesPerMth=0;
			$totallossofpay=0;												
			foreach($mthlyAllowedLeaves as $mthlyAllowedLeaves){
				if($mthlyAllowedLeaves['earned'] == 1){
					$totalAllowedLeavesPerMth += $mthlyAllowedLeaves['number_of_days'];
				}else{
					$totallossofpay +=$mthlyAllowedLeaves['number_of_days'];
				}
				
			}											
			
								

			
			
			// Yearly allowed leaves
			$yearlyAllowedLeaves = $db->fetchQuery("SELECT * FROM payroll_user_leave A
														LEFT JOIN payroll_leave B ON A.leave_id=B.lid WHERE A.employee_id='$employeeid' and B.based_on='2'");
			$totalAllowedLeavesPeryearly=0;
										
			foreach($yearlyAllowedLeaves as $yearlyAllowedLeaves){
			
				if($yearlyAllowedLeaves['earned'] == 1){
					$totalAllowedLeavesPeryearly += $yearlyAllowedLeaves['number_of_days'];
				}else{
					$totallossofpay +=$yearlyAllowedLeaves['number_of_days'];
				}
			}											
			
			// Yearly requested leaves
			$yearlyRequestedLeaves = $db->fetchQuery("SELECT * FROM payroll_user_leave_requests A 
														LEFT JOIN payroll_leave B ON A.leave_id = B.lid 
														WHERE A.employee_id='$employeeid' AND A.half_full_day='2' 
														AND B.based_on='2' and (YEAR(day_from) ='$yearofLastMth' or YEAR(day_to)='$yearofLastMth')");
			$yearlyRequestedLeave=0;
														
			foreach($yearlyRequestedLeaves as $yearlyRequestedLeaves){
					$yearlyRequestedLeave += $yearlyRequestedLeaves['no_of_days'];
			}										
			//fecho $yearlyRequestedLeave;	
			
			/////// Balance leaves in this year (earned);
			$balanceLeavesInThisYear =  $totalAllowedLeavesPeryearly-$yearlyRequestedLeave;	
			
			/////// Balance leaves in this Mth (earned);
			$leavesInthisMth =$totalAllowedLeavesPerMth-$totalleaves;
			
			
			/////// Leave calculation based on month.
			if($totalAllowedLeavesPerMth < $totalleaves){
				$lossofpayleaves = $totalleaves-$totalAllowedLeavesPerMth;
				$earnedLeaves	 = $totalAllowedLeavesPerMth;
			}else{
				$lossofpayleaves = 0;
				$earnedLeaves	 = $totalleaves;
			}	
			
			if($lossofpayleaves > 0 ){
				
			/////// Check Requested Leave from yearly based;
				if($yearlyRequestedLeave > 0 && $lossofpayleaves  > $yearlyRequestedLeave){
				
					$lossofpayleaves = $lossofpayleaves-$yearlyRequestedLeave;
					$earnedLeaves	 = $earnedLeaves + $yearlyRequestedLeave;
					
				}elseif($yearlyRequestedLeave > 0 && $lossofpayleaves  < $yearlyRequestedLeave){
				
					$lossofpayleaves = $yearlyRequestedLeave-$lossofpayleaves;
					$earnedLeaves	 = $earnedLeaves + ($yearlyRequestedLeave-$lossofpayleaves);
					
				}
				
			}
			
			
											
		 
		
		
		 
			$totalWorkingdays = $db->fetchQuery("SELECT count(e_id) as totalDays FROM time WHERE e_id='$employeeid' and MONTH(e_date)='$lastmonth' GROUP BY DAY(e_date)");
			$count =count($totalWorkingdays);
			
			if($lossofpayleaves > 0){
				$basicSal = " (A.emp_basic_pay - (A.emp_basic_pay/'$daysLastMth') * $lossofpayleaves)";
			}else{
				$basicSal = "  A.emp_basic_pay";
			}
			
		 $salary  = $db->fetchQuery("SELECT *, IF(C.unit = 2, $basicSal*C.amount/100,amount) as totalamount
			FROM employee A LEFT JOIN payroll_user_deductions B ON A.e_id = B.employee_id LEFT JOIN payroll_benifits_deductions C ON B.deduction_id= C.id WHERE A.e_id='$employeeid'");

			$salRows = count($salary);
			
			//if($lossofpayleaves > 0){
			//	$salary[$salRows-1]['emp_basic_pay'] = $salary[$salRows-1]['emp_basic_pay']-(($salary[$salRows-1]['emp_basic_pay']/$daysLastMth)*$lossofpayleaves);
			//}
			$salary[$salRows-1]['totalDays'] = $count;
			$salary[$salRows-1]['lastMonthDays'] =  $workingDays-$earnedLeaves-$lossofpayleaves;
			$salary[$salRows-1]['totalDays'] =$daysLastMth;
			
			$salary[$salRows-1]['earnesLeaves'] =  $earnedLeaves;
			$salary[$salRows-1]['lossofpay'] =  $lossofpayleaves;
			$salary[$salRows-1]['status'] 	 = "notpaid";
			
			$lossofpayattendance=0;
			
			$lossofpayattendance=0;
			
			//$paymentperDay = ($list['emp_basic_pay']/$daysLastMth)*$lossofpayleaves;
			$paymentperDay = ($list['emp_basic_pay']/$daysLastMth)*$totallossleaves_final;
			
			
		
			foreach($salary as $key){
			
				if($key['deduction_benefit'] == '1'){
				
					 $totalDeductionAmt += $key['totalamount'];
					 
				}elseif($key['deduction_benefit'] == '2'){
				
					 $totalBenefitAmt	+= $key['totalamount'];
					 
				}else{
				
					 $totalContributionAmt	+= $key['totalamount'];
					 
				}
				//print_r($deductions);
			}
			
			$a++;
		
			
			
			
			$salaryList[$b]['paymentStatus'] 	= $paymentStatus;
			$salaryList[$b]['employee_id'] 	= $employeeid;
			$salaryList[$b]['name'] 		= $list['e_fname'];
			$salaryList[$b]['basic_pay'] 	= $list['emp_basic_pay'];
			$salaryList[$b]['deduction'] 	= $totalDeductionAmt+$paymentperDay;
			$salaryList[$b]['benefit'] 	= $totalBenefitAmt;
			$salaryList[$b]['contribution'] = $totalContributionAmt;
			$salaryList[$b]['branch_name'] = $branch_name;
			
			
			
		$b++;
	}
	
	//print_r($salaryList);
	
	$count = count($salaryList);
	$salaryList[$count-1]['totalrows'] = $total_pages;
	
	echo '{"salaryDetails":'.json_encode($salaryList).'}';
	
}
elseif($action == "paysalary"){




	$cond='';$salyear='';$salmonth = '';

		
	
		if(!empty($_REQUEST['salmonth'])){
		$salmonth=$_REQUEST['salmonth'];
		}
		
		if(!empty($_REQUEST['salyear'])){
		$salyear=$_REQUEST['salyear'];
		}
		$branch = $_GET['branch'];
		
		
			
			
			
		if(!empty($branch))
		{
		$cond.='and A.branchid="'.$branch.'"';
		}
		
			
		



	//$salaryAllusers  = $db->fetchAll("employee");
	$salaryAllusers= $db->fetchQuery("SELECT * from employee A LEFT JOIN branches B ON A.branchid = B.branch_id WHERE 1 $cond");
	//print_r($salary);
	
	$salmonth	 =$_GET['salmonth'];
		$salyear	 =$_GET['salyear'];
	
	$pay_period=$salmonth.'-'.$salyear;
	
	$salaryList = array();
	
		$requestedMonth	 =$_GET['month'];
		$requestedYear	 =$_GET['year'];
		
	
		if(!$requestedMonth){
			$requestedMonth	 	= date("m",strtotime(" -1 months"));
			 $requestedYear		=date("Y",strtotime(" -1 months"));
		}
		
		$b=0;
		//print_r($salaryAllusers);
		
			
	
		foreach($salaryAllusers as $list){
		$employeeid	=$list['e_id'];
		$branch_name	=$list['branch_name'];
		
		//echo $employeeid;
	/*
	
	
	$sal=array();
	$a=0;
	foreach($salary as $salary){
		$sal[$a]['employee_id']	=$salary['e_id'];
		$sal[$a]['name']		=$salary['e_fname'];
		$sal[$a]['basic_pay']	=$salary['emp_basic_pay'];
		$basicpay = $salary['emp_basic_pay'];
		
		
		$deductions = $db->fetchQuery("SELECT 	sum( IF(C.unit = 2, $basicpay*C.amount/100,amount)) as benefits ,deduction_benefit
		FROM payroll_user_deductions B  
		LEFT JOIN payroll_benifits_deductions C 
		ON B.deduction_id= C.id WHERE B.employee_id=".$salary['e_id']." GROUP BY C.deduction_benefit");
		//print_r($ded);
	
		$sal[$a]['deduction']=0;
		$sal[$a]['benefit']=0;
		$sal[$a]['contribution']=0;
	//print_r($ded);
		foreach($deductions as $value){
		
			if($value['deduction_benefit'] == '1'){
			
				$sal[$a]['deduction'] += $value['benefits'];
			}elseif($value['deduction_benefit'] == '2'){
				$sal[$a]['benefit']	+= $value['benefits'];
			}else{
				$sal[$a]['contribution']	+= $value['benefits'];
			}
			//print_r($deductions);
		}
		
		$a++;
	}*/
	//print_r($sal);
	
			$totalDeductionAmt		=0;
			$totalBenefitAmt		=0;
			$totalContributionAmt	=0;
	

	
		
	 $givendate = "01-".$requestedMonth ."-". $requestedYear;
	 
	 
	 
	 
	 //////////////////////////////////////////////// Check Payment Status //////////////////////////////////////////////////////////////////////
		
		$requestedDate = date('m-Y',strtotime($givendate));
		$paymentDetails= $db->fetchQuery("SELECT A.userid,B.deduction_total_amount as totalamount,B.deduction_id,
												C.*,D.*,A.earned_leaves as earnesLeaves ,A.lossofpay_leaves,
												A.basic_pay as emp_basic_pay
												FROM payroll_salary_pay A 
												
												LEFT JOIN payroll_payment_details B ON A.id = B.payment_id 
												LEFT JOIN payroll_benifits_deductions C ON B.deduction_id = C.id 
												LEFT JOIN employee D ON A.userid= D.e_id  WHERE pay_period ='$requestedDate' and userid='$employeeid'");
		
		
		
		
	
		//print_r($paymentDetails);
		$salRows = count($paymentDetails);
		if($salRows > 0){	
			$paymentStatus = 1;
		}else{
			$paymentStatus = 0;
		}
	 
		//echo $givendate;
		$lastmonth = date('m',strtotime($givendate));
		$daysLastMth = date('t',strtotime($givendate));
		$yearofLastMth = date('Y',strtotime($givendate));
		 
		$date = $yearofLastMth."-".$lastmonth."-01";


		$firstOfLastmth= date('Y-m-01', strtotime($date));
		$endOfLastmth= date('Y-m-t', strtotime($date));
		 

		 
		 $lastMtnHolidays = $db->fetchQuery("SELECT * FROM payroll_holiday_calendar WHERE MONTH(date)='$lastmonth' and YEAR(date)='$yearofLastMth' and is_blocked='0'");
		 $holidays=array();
		 foreach($lastMtnHolidays as $lastMtnHolidays){
			$holidays[]=$lastMtnHolidays['date'];
		 }
		 $workingDays=  $db->getWorkingDays($firstOfLastmth,$endOfLastmth,$holidays);
		
		
		//////////////////////////////////////////////// Check Payment Status //////////////////////////////////////////////////////////////////////
		
		
		
		///////////////////////////////////////////////// Start Payslip details collection /////////////////////////////////////////////////////////
		
		
		 /// Monthly requested leaves;
		 //find allowed leaves and leave tyes
		 		 
		 $leaves = $db->fetchQuery("SELECT * FROM payroll_user_leave_requests WHERE employee_id='$employeeid' AND (MONTH(day_from) ='$lastmonth' OR MONTH(day_to) ='$lastmonth') ");
		  $a=0;
		//  echo "SELECT * FROM payroll_user_leave_requests WHERE employee_id='$employeeid' AND (MONTH(day_from) ='$lastmonth' OR MONTH(day_to) ='$lastmonth') ";
		$totalleaves = 0;
		 foreach($leaves as $leaves){
		 	$day_from 	= $leaves['day_from'];
			$day_to		= $leaves['day_to'];
			
			if($endOfLastmth > $day_from &&  $endOfLastmth < $day_to){
				$totalleaves += $db->getWorkingDays( $day_from,$endOfLastmth ,$holidays);
				
			}elseif($firstOfLastmth > $day_from &&  $endOfLastmth > $day_to){
				$totalleaves += $db->getWorkingDays( $firstOfLastmth,$day_to ,$holidays);
				
			}elseif($day_to > $firstOfLastmth &&  $day_from > $firstOfLastmth && $day_to < $endOfLastmth &&  $day_from < $endOfLastmth){
				$totalleaves += $db->getWorkingDays( $day_from,$day_to ,$holidays);
			}
			
			$a++;
		 }
		 

			// Mthly allowed leaves
			$mthlyAllowedLeaves = $db->fetchQuery("SELECT * FROM payroll_user_leave A
														LEFT JOIN payroll_leave B ON A.leave_id=B.lid WHERE A.employee_id='$employeeid' and B.based_on='1'");
			$totalAllowedLeavesPerMth=0;
			$totallossofpay=0;												
			foreach($mthlyAllowedLeaves as $mthlyAllowedLeaves){
				if($mthlyAllowedLeaves['earned'] == 1){
					$totalAllowedLeavesPerMth += $mthlyAllowedLeaves['number_of_days'];
				}else{
					$totallossofpay +=$mthlyAllowedLeaves['number_of_days'];
				}
				
			}											
			
								

			
			
			// Yearly allowed leaves
			$yearlyAllowedLeaves = $db->fetchQuery("SELECT * FROM payroll_user_leave A
														LEFT JOIN payroll_leave B ON A.leave_id=B.lid WHERE A.employee_id='$employeeid' and B.based_on='2'");
			$totalAllowedLeavesPeryearly=0;
										
			foreach($yearlyAllowedLeaves as $yearlyAllowedLeaves){
			
				if($yearlyAllowedLeaves['earned'] == 1){
					$totalAllowedLeavesPeryearly += $yearlyAllowedLeaves['number_of_days'];
				}else{
					$totallossofpay +=$yearlyAllowedLeaves['number_of_days'];
				}
			}											
			
			// Yearly requested leaves
			$yearlyRequestedLeaves = $db->fetchQuery("SELECT * FROM payroll_user_leave_requests A 
														LEFT JOIN payroll_leave B ON A.leave_id = B.lid 
														WHERE A.employee_id='$employeeid' 
														AND B.based_on='2' and (YEAR(day_from) ='$yearofLastMth' or YEAR(day_to)='$yearofLastMth')");
			$yearlyRequestedLeave=0;
														
			foreach($yearlyRequestedLeaves as $yearlyRequestedLeaves){
					$yearlyRequestedLeave += $yearlyRequestedLeaves['no_of_days'];
			}										
			//fecho $yearlyRequestedLeave;	
			
			/////// Balance leaves in this year (earned);
			$balanceLeavesInThisYear =  $totalAllowedLeavesPeryearly-$yearlyRequestedLeave;	
			
			/////// Balance leaves in this Mth (earned);
			$leavesInthisMth =$totalAllowedLeavesPerMth-$totalleaves;
			
			
			/////// Leave calculation based on month.
			if($totalAllowedLeavesPerMth < $totalleaves){
				$lossofpayleaves = $totalleaves-$totalAllowedLeavesPerMth;
				$earnedLeaves	 = $totalAllowedLeavesPerMth;
			}else{
				$lossofpayleaves = 0;
				$earnedLeaves	 = $totalleaves;
			}	
			
			if($lossofpayleaves > 0 ){
				
			/////// Check Requested Leave from yearly based;
				if($yearlyRequestedLeave > 0 && $lossofpayleaves  > $yearlyRequestedLeave){
				
					$lossofpayleaves = $lossofpayleaves-$yearlyRequestedLeave;
					$earnedLeaves	 = $earnedLeaves + $yearlyRequestedLeave;
					
				}elseif($yearlyRequestedLeave > 0 && $lossofpayleaves  < $yearlyRequestedLeave){
				
					$lossofpayleaves = $yearlyRequestedLeave-$lossofpayleaves;
					$earnedLeaves	 = $earnedLeaves + ($yearlyRequestedLeave-$lossofpayleaves);
					
				}
				
			}
			
			
											
		 
		
		
		 
			$totalWorkingdays = $db->fetchQuery("SELECT count(e_id) as totalDays FROM time WHERE e_id='$employeeid' and MONTH(e_date)='$lastmonth' GROUP BY DAY(e_date)");
			$count =count($totalWorkingdays);
			
			if($lossofpayleaves > 0){
				$basicSal = " (A.emp_basic_pay - (A.emp_basic_pay/'$daysLastMth') * $lossofpayleaves)";
			}else{
				$basicSal = "  A.emp_basic_pay";
			}
			
		 $salary  = $db->fetchQuery("SELECT *, IF(C.unit = 2, $basicSal*C.amount/100,amount) as totalamount
			FROM employee A LEFT JOIN payroll_user_deductions B ON A.e_id = B.employee_id LEFT JOIN payroll_benifits_deductions C ON B.deduction_id= C.id WHERE A.e_id='$employeeid'");

			$salRows = count($salary);
			
			//if($lossofpayleaves > 0){
			//	$salary[$salRows-1]['emp_basic_pay'] = $salary[$salRows-1]['emp_basic_pay']-(($salary[$salRows-1]['emp_basic_pay']/$daysLastMth)*$lossofpayleaves);
			//}
			$salary[$salRows-1]['totalDays'] = $count;
			$salary[$salRows-1]['lastMonthDays'] =  $workingDays-$earnedLeaves-$lossofpayleaves;
			$salary[$salRows-1]['totalDays'] =$daysLastMth;
			
			$salary[$salRows-1]['earnesLeaves'] =  $earnedLeaves;
			$salary[$salRows-1]['lossofpay'] =  $lossofpayleaves;
			$salary[$salRows-1]['status'] 	 = "notpaid";
			
			
			$paymentperDay = ($list['emp_basic_pay']/$daysLastMth)*$lossofpayleaves;
			
		
			foreach($salary as $key){
			
				if($key['deduction_benefit'] == '1'){
				
					 $totalDeductionAmt += $key['totalamount'];
					 
				}elseif($key['deduction_benefit'] == '2'){
				
					 $totalBenefitAmt	+= $key['totalamount'];
					 
				}else{
				
					 $totalContributionAmt	+= $key['totalamount'];
					 
				}
				//print_r($deductions);
			}
			
			$a++;
		
		
			
			
			$emp_basic_pay=$list['emp_basic_pay'];
			$totalpayable=$emp_basic_pay+$totalBenefitAmt-($totalDeductionAmt+$paymentperDay);
			$payment_date=date('Y-m-d,H:i:s');
			
			$salaryList[$b]['paymentStatus'] 	= $paymentStatus;
			$salaryList[$b]['employee_id'] 	= $employeeid;
			$salaryList[$b]['name'] 		= $list['e_fname'];
			$salaryList[$b]['basic_pay'] 	= $list['emp_basic_pay'];
			$salaryList[$b]['deduction'] 	= $totalDeductionAmt+$paymentperDay;
			$salaryList[$b]['benefit'] 	= $totalBenefitAmt;
			$salaryList[$b]['contribution'] = $totalContributionAmt;
			$salaryList[$b]['branch_name'] = $branch_name;
			
			
			$salarypayment = $db->fetchQuery("INSERT INTO payroll_salary_pay SET userid=$employeeid,pay_period='".$pay_period."',basic_pay=$emp_basic_pay,total_payable=$totalpayable,payment_date='".$payment_date."',total_paid=$totalpayable,lossofpay_leaves=$lossofpayleaves,earned_leaves=$earnedLeaves");
			
		$b++;
	}
	
	//print_r($salaryList);
	
	

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

		$over_time=0; $over_time_sal=0;

		$employeeid = $_GET['emp_id'];
		$payperiod  = $_GET['from'];
		$branch  = $_GET['branch'];
		$requestedMonth	 =$_GET['month'];
		$requestedYear	 =$_GET['year'];
		
		
		
			$list= $db->fetchQuery("SELECT employee.overtime_status,employee.over_time,employee.emp_basic_pay,branches.brch_half from employee LEFT JOIN branches  ON employee.branchid = branches.branch_id WHERE e_id=$employeeid");

		$over_time_cal	=$list[0]['over_time'];
		$emp_basic_pay_cal	=$list[0]['emp_basic_pay'];
		$overtime_status	=$list[0]['overtime_status'];
		$brch_half	=$list[0]['brch_half'];
		
		$perhoursal=($emp_basic_pay_cal*12)/(365*8);
		if(($requestedMonth<10) && (strlen($requestedMonth)==1))
		{
		$requestedMonth='0'.$requestedMonth;
		}
		
		if(!$requestedMonth){
			$requestedMonth	 	= date("m",strtotime(" -1 months"));
			 $requestedYear		=date("Y",strtotime(" -1 months"));
		}
		
		$earnedLeaves=0;
		$lossofpayleaves=0;
		
	 $givendate = "01-".$requestedMonth ."-". $requestedYear;
		//echo $givendate;
		$lastmonth = date('m',strtotime($givendate));
		$daysLastMth = date('t',strtotime($givendate));
		$yearofLastMth = date('Y',strtotime($givendate));
		 
		$date = $yearofLastMth."-".$lastmonth."-01";
	

		$firstOfLastmth= date('Y-m-01', strtotime($date));
		$endOfLastmth= date('Y-m-t', strtotime($date));
		 
		 $startgivendate=$requestedYear."-".$requestedMonth."-"."01";
	
		$startenddate=$requestedYear."-".$requestedMonth."-"."31";
	
	$reporttimeAllusers= $db->fetchQuery("SELECT late_time from report_time  WHERE brch_id=$branch");
	 
	 $report_time=$reporttimeAllusers[0]['late_time'];
		//echo "Select count(distinct(e_date)) as fullday from time as A where e_id=$employeeid and (select e_in from time as B where B.e_id=A.e_id and B.e_date=A.e_date order by id asc limit 1)<='$report_time' and e_date>='$startgivendate' and e_date<='$startenddate' and (select total_worked_hours from time as B where B.e_id=A.e_id and B.e_date = A.e_date order by B.id desc limit 1) > '06:00:00'";

$fulldaydetails = $db->fetchQuery("Select e_date,total_worked_hours from time as A where e_id=$employeeid and (select e_in from time as B where B.e_id=A.e_id and B.e_date=A.e_date order by id asc limit 1)<='$report_time' and e_date>='$startgivendate' and e_date<='$startenddate' and (select total_worked_hours from time as B where B.e_id=A.e_id and B.e_date = A.e_date order by B.id desc limit 1) > '06:00:00' group by e_date");
	 if(!empty($fulldaydetails))
	 $fulldays=count($fulldaydetails);
	else
	$fulldays=0;
	foreach($fulldaydetails as $fulldaydate)
	{
	  $full_date=$fulldaydate['e_date'];
	if($brch_half=='1')
	{
	
			if(date('w', strtotime($full_date)) == 6) 
				{ $full_date;
				
				    $worked_hours=$fulldaydate['total_worked_hours'];
				//	$strwork=strtotime('09:00:00')-strtotime($worked_hours);
					//echo date('H:i:s',$strwork);
					//echo "<br/>";		
					if($overtime_status=='1')
	  				{
					$from_time = strtotime($worked_hours);
					$to_time = strtotime("04:00:00");
					  $over_time=$over_time + intval(abs(($to_time - $from_time) / 3600));
					}
				} 
	}
	}
	
	 //$latetimedetails = $db->fetchQuery("Select count(*) as lateday from time where e_id= and (time_in>'$report_time' or time_inloc='PM') and e_date>='$startgivendate' and e_date<='$startenddate' ");
	
	  $latetimedetails = $db->fetchQuery("Select e_date,total_worked_hours from time as A where e_id=$employeeid and ((select e_in from time as B where B.e_id=A.e_id and B.e_date=A.e_date order by id asc limit 1)>'$report_time' ) and e_date>='$startgivendate' and e_date<='$startenddate' and (select total_worked_hours from time as B where B.e_id=A.e_id and B.e_date = A.e_date order by A.id desc limit 1) > '06:00:00' group by e_date");
	 
	 if(!empty($latetimedetails))
	 $latedays=count($latetimedetails);
	 else
	$latedays=0;
	foreach($latetimedetails as $latetimedate)
	{
	 $late_date=$latetimedate['e_date'];
		if($brch_half=='1')
	{	if(date('w', strtotime($late_date)) == 6) 
				{
				
				    $worked_hours=$latetimedate['total_worked_hours'];
				//	$strwork=strtotime('09:00:00')-strtotime($worked_hours);
					//echo date('H:i:s',$strwork);
					//echo "<br/>";	
					if($overtime_status=='1')
	  				{	
					$from_time = strtotime($worked_hours);
					$to_time = strtotime("04:00:00");
					 $over_time=$over_time + intval(abs(($to_time - $from_time) / 3600));
					 }
				} 
	}
	}
	  
	 // $halfdaysapplied = $db->fetchQuery("Select count(*) as halfday from payroll_user_leave_requests where employee_id=$employeeid and half_full_day='1' and is_cancelled=0 and imd_status=1 and day_from>='$startgivendate' and day_from<='$startenddate' ");
	 
	  
	  
	  $halfdaysapplied = $db->fetchQuery("Select e_date,total_worked_hours from time as A where e_id=$employeeid and e_date>='$startgivendate' and e_date<='$startenddate' and (select total_worked_hours from time as B where B.e_id=A.e_id and B.e_date = A.e_date order by B.id desc limit 1) < '06:00:00' and (select total_worked_hours from time as B where B.e_id=A.e_id and B.e_date = A.e_date order by B.id desc limit 1) > '03:00:00' group by e_date");
	  
	 //$latetimedetails = $db->fetchQuery("Select count(*) as lateday from time where e_id=$employeeid and (time_in>'$report_time' or time_inloc='PM') and e_date>='$startgivendate' and e_date<='$startenddate' ");
	 if(!empty($halfdaysapplied)) 
	  $halfdays=count($halfdaysapplied);
	else
	$halfdays=0;
	
	foreach($halfdaysapplied as $halfdaydate)
	{
	 $half_date=$halfdaydate['e_date'];
	if($brch_half=='1')
	{
			if(date('w', strtotime($half_date)) == 6) 
				{
				 
				    $worked_hours=$halfdaydate['total_worked_hours'];
				 
				   if($halfdaydate['time_in']<=$report_time)
				   {
				   $halfdays=$halfdays-1;
				   $fulldays=$fulldays+1;
				   }
				   else
				   {
				   $halfdays=$halfdays-1;
				   $latedays=$latedays+1;
				   
				   }
				//	$strwork=strtotime('09:00:00')-strtotime($worked_hours);
					//echo date('H:i:s',$strwork);
					//echo "<br/>";	
						if($overtime_status=='1')
	  					{
					 $from_time = strtotime($worked_hours);
					$to_time = strtotime("04:00:00");
					
					  $over_time=$over_time + intval(abs(($to_time - $from_time) / 3600));
					  }
				} 
	}
	}
	

	 $nolossleaveapplied = $db->fetchQuery("Select count(*) as nolossleave from payroll_user_leave_requests where employee_id=$employeeid and is_cancelled=0 and imd_status=1 and day_from>='$startgivendate' and day_from<='$startenddate' and (leave_id='20' or leave_id='21' or leave_id='22') ");
	 
	   $nolossleave=$nolossleaveapplied[0]['nolossleave'];
	
	  
	  $totalattendance = ($fulldays)+($halfdays*0.5)+($latedays);
	
	$totalattendance =$totalattendance - ((intval($latedays/3))*0.5);
	
	$totalpresentdays =$totalattendance;
	
	
	
	 if($overtime_status=='1')
	  {
	  
	  $overworkdetails = $db->fetchQuery("Select * from time as A where e_id=$employeeid and  e_date>='$startgivendate' and e_date<='$startenddate' and (select total_worked_hours from time as B where B.e_id=A.e_id and B.e_date = A.e_date order by B.id desc limit 1) > '10:00:00'");
	  
	 	foreach($overworkdetails as $overwork)
		{
		$check_sat_date=$overwork['e_date'];
		 $worked_hours=$overwork['total_worked_hours'];
	//	$strwork=strtotime('09:00:00')-strtotime($worked_hours);
		//echo date('H:i:s',$strwork);
		//echo "<br/>";	
		if(date('w', strtotime($check_sat_date)) != 6) 
				{	
		$from_time = strtotime($worked_hours);
		$to_time = strtotime("09:00:00");
         $over_time=$over_time + intval(abs(($to_time - $from_time) / 3600));
		 }
		}

	}	
	
		 
		 $lastMtnHolidays = $db->fetchQuery("SELECT * FROM payroll_holiday_calendar WHERE MONTH(date)='$lastmonth' and YEAR(date)='$yearofLastMth' and is_blocked='0'");
		 $holidays=array();
		 foreach($lastMtnHolidays as $lastMtnHolidays){
			$holidays[]=$lastMtnHolidays['date'];
		 }
		 
		  $workingDays=  $db->getWorkingDays($firstOfLastmth,$endOfLastmth,$holidays);
		
		$inquery='';
		
		if($overtime_status=='1')
	  {
		foreach($holidays as $holidaydate)
		{
		 $inquery.="'".$holidaydate."',";
		
		}
		
		 $inquery=substr($inquery, 0,-1);
		
	 $over_holiday_work=$db->fetchQuery("SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(total_worked_hours))) as over_work FROM `time` WHERE e_id=$employeeid and e_date IN ($inquery)");
	 
		 if(!empty($over_holiday_work) && $over_holiday_work[0]['over_work']>0)
		 {
		   $over_holiday_hours=date('H',strtotime($over_holiday_work[0]['over_work']));
		 }
		 else
		 {
		 $over_holiday_hours=0;
		 }
	 }
	 $over_time_sal=($over_time_cal*$perhoursal*($over_time + $over_holiday_hours))/100;
	 
	$over_time=$over_time + $over_holiday_hours;
	
		//////////////////////////////////////////////// Check Payment Status //////////////////////////////////////////////////////////////////////
		
		
		$totalleaves_final =  0;
		
		$totallossleaves_final = $workingDays - $totalattendance - $nolossleave;
	
	
		$requestedDate = date('Y-m',strtotime($givendate)).'-01';

		$paymentDetails= $db->fetchQuery("SELECT A.userid,A.payment_date,A.leave_deduction,B.deduction_total_amount as totalamount,B.deduction_id,
												C.*,D.*,H.branch_name,F.depart_name,G.desig_name,A.earned_leaves as earnesLeaves ,A.lossofpay_leaves,
												A.basic_pay as emp_basic_pay, E.title as paymentMethod, A.payment_referance as referances
												FROM payroll_salary_pay A 
												
												LEFT JOIN payroll_payment_details B ON A.id = B.payment_id 
												LEFT JOIN payroll_benifits_deductions C ON B.deduction_id = C.id 
												LEFT JOIN employee D ON A.userid= D.e_id
												
												LEFT JOIN payroll_payment_methods E ON A.payment_method = E.id
												LEFT JOIN department F ON F.depart_id= D.departid
												
												LEFT JOIN designation G ON G.desig_id= D.e_post
												LEFT JOIN branches H ON H.branch_id= D.branchid
												  WHERE pay_period ='$requestedDate' and userid='$employeeid'");
		
		
	
		//print_r($paymentDetails);
		$salRows = count($paymentDetails);
		if($salRows > 0){	
		
		$leave_tot_ded=$paymentDetails[0]['leave_deduction'];
			//if($lossofpayleaves > 0){
			//	$salary[$salRows-1]['emp_basic_pay'] = $salary[$salRows-1]['emp_basic_pay']-(($salary[$salRows-1]['emp_basic_pay']/$daysLastMth)*$lossofpayleaves);
			//}
			$salary  =$paymentDetails;
			
			$salary[$salRows-1]['over_time_sal'] 	= $over_time_sal;
			$salary[$salRows-1]['over_time'] 	= $over_time;
			
			$salary[$salRows-1]['totalDays'] = $totalattendance;
			//$salary[$salRows-1]['lossofpay'] =  $salary[$salRows-1]['lossofpay_leaves'];
			$salary[$salRows-1]['lossofpay'] =  $totallossleaves_final;
			$salary[$salRows-1]['lastMonthDays'] =  $totalattendance;
			//$salary[$salRows-1]['lastMonthDays'] =  $workingDays-$salary[$salRows-1]['earnesLeaves']-$salary[$salRows-1]['lossofpay'];
			$salary[$salRows-1]['totalDays'] =$daysLastMth;
			$salary[$salRows-1]['status'] ="paid";
			$salary[$salRows-1]['totalDays'] =$daysLastMth;
			$salary[$salRows-1]['workingDays'] =$workingDays;
			$salary[$salRows-1]['leave_tot_ded'] =  $leave_tot_ded;
			
			//$salary[$salRows-1]['earnesLeaves'] =  $earnedLeaves;
			
		
		}else{
		
		///////////////////////////////////////////////// Start Payslip details collection /////////////////////////////////////////////////////////
		
		
		 /// Monthly requested leaves;
		 //find allowed leaves and leave tyes
		 $leaves = $db->fetchQuery("SELECT * FROM payroll_user_leave_requests A 
		 									LEFT JOIN payroll_leave B ON A.leave_id=B.lid
		 									WHERE employee_id='$employeeid' AND (MONTH(day_from) ='$lastmonth' OR MONTH(day_to) ='$lastmonth') AND B.based_on='1' ");
		  $a=0;
	
		//  echo "SELECT * FROM payroll_user_leave_requests WHERE employee_id='$employeeid' AND (MONTH(day_from) ='$lastmonth' OR MONTH(day_to) ='$lastmonth') ";
		$totalleaves = 0;
		 foreach($leaves as $leaves){
		 	$day_from 	= $leaves['day_from'];
			$day_to		= $leaves['day_to'];
			
			if($endOfLastmth > $day_from &&  $endOfLastmth < $day_to){
				$totalleaves += $db->getWorkingDays( $day_from,$endOfLastmth ,$holidays);
				
			}elseif($firstOfLastmth > $day_from &&  $endOfLastmth > $day_to){
				$totalleaves += $db->getWorkingDays( $firstOfLastmth,$day_to ,$holidays);
				
			}elseif($day_to > $firstOfLastmth &&  $day_from > $firstOfLastmth && $day_to < $endOfLastmth &&  $day_from < $endOfLastmth){
				$totalleaves += $db->getWorkingDays( $day_from,$day_to ,$holidays);
			}
			
			$a++;
		 }
			//echo $totalleaves;
			// Mthly allowed leaves
			$mthlyAllowedLeaves = $db->fetchQuery("SELECT * FROM payroll_user_leave A
														LEFT JOIN payroll_leave B ON A.leave_id=B.lid WHERE A.employee_id='$employeeid' and B.based_on='1'");
			$totalAllowedLeavesPerMth=0;
			$totallossofpay=0;												
			foreach($mthlyAllowedLeaves as $mthlyAllowedLeaves){
				if($mthlyAllowedLeaves['earned'] == 1){
					$totalAllowedLeavesPerMth += $mthlyAllowedLeaves['number_of_days'];
				}else{
					$totallossofpay +=$mthlyAllowedLeaves['number_of_days'];
				}
				
			}											
			
								

			
			
			// Yearly allowed leaves
			$yearlyAllowedLeaves = $db->fetchQuery("SELECT * FROM payroll_user_leave A
														LEFT JOIN payroll_leave B ON A.leave_id=B.lid WHERE A.employee_id='$employeeid' and B.based_on='2'");
			$totalAllowedLeavesPeryearly=0;
										
			foreach($yearlyAllowedLeaves as $yearlyAllowedLeaves){
			
				if($yearlyAllowedLeaves['earned'] == 1){
					$totalAllowedLeavesPeryearly += $yearlyAllowedLeaves['number_of_days'];
				}else{
					$totallossofpay +=$yearlyAllowedLeaves['number_of_days'];
				}
			}											
			
			// Yearly requested leaves
			$yearlyRequestedLeaves = $db->fetchQuery("SELECT * FROM payroll_user_leave_requests A 
														LEFT JOIN payroll_leave B ON A.leave_id = B.lid 
														WHERE A.employee_id='$employeeid' 
														AND B.based_on='2' and (YEAR(day_from) ='$yearofLastMth' or YEAR(day_to)='$yearofLastMth')");
			$yearlyRequestedLeave=0;
														
			foreach($yearlyRequestedLeaves as $yearlyRequestedLeaves){
					$yearlyRequestedLeave += $yearlyRequestedLeaves['no_of_days'];
					
					$day_from 	= $yearlyRequestedLeaves['day_from'];
					$day_to		= $yearlyRequestedLeaves['day_to'];
					
					if($endOfLastmth > $day_from &&  $endOfLastmth < $day_to){
						$totalleavesYearly += $db->getWorkingDays( $day_from,$endOfLastmth ,$holidays);
						
					}elseif($firstOfLastmth > $day_from &&  $endOfLastmth > $day_to){
						$totalleavesYearly += $db->getWorkingDays( $firstOfLastmth,$day_to ,$holidays);
						
					}elseif($day_to > $firstOfLastmth &&  $day_from > $firstOfLastmth && $day_to < $endOfLastmth &&  $day_from < $endOfLastmth){
						$totalleavesYearly += $db->getWorkingDays( $day_from,$day_to ,$holidays);
					}
					
					
			}										
				
			
			/////// Balance leaves in this year (earned);
			$balanceLeavesInThisYear =  $totalAllowedLeavesPeryearly-$yearlyRequestedLeave;	
			
			/////// Balance leaves in this Mth (earned);
			$leavesInthisMth =$totalAllowedLeavesPerMth-$totalleaves;
			
			
			/////// Leave calculation based on month.
			if($totalAllowedLeavesPerMth < $totalleaves){
				$lossofpayleaves = $totalleaves-$totalAllowedLeavesPerMth;
				$earnedLeaves	 = $totalAllowedLeavesPerMth;
			}else{
				$lossofpayleaves = 0;
				$earnedLeaves	 = $totalleaves;
			}	
			
			
			//echo $lossofpayleaves;
			
			if($totalleavesYearly > 0){
			
				if($totalAllowedLeavesPeryearly > $yearlyRequestedLeave){
					$earnedLeaves += $yearlyRequestedLeave;
					$lossofpayleaves += 0;
				}else{
					$earnedLeaves += $totalAllowedLeavesPeryearly;
					$lossofpayleaves += $yearlyRequestedLeave-$totalAllowedLeavesPeryearly;
				}
				
			}
			
			
		/*	if($lossofpayleaves > 0 ){
				
			/////// Check Requested Leave from yearly based;
				if($yearlyRequestedLeave > 0 && $lossofpayleaves  > $yearlyRequestedLeave){
				
					$lossofpayleaves = $lossofpayleaves-$yearlyRequestedLeave;
					$earnedLeaves	 = $earnedLeaves + $yearlyRequestedLeave;
					
				}elseif($yearlyRequestedLeave > 0 && $lossofpayleaves  < $yearlyRequestedLeave){
				
					$lossofpayleaves = $yearlyRequestedLeave-$lossofpayleaves;
					$earnedLeaves	 = $earnedLeaves + ($yearlyRequestedLeave-$lossofpayleaves);
					
				}
				
			}*/
			
			
											
		 
		
		
		 
			$totalWorkingdays = $db->fetchQuery("SELECT count(e_id) as totalDays FROM time WHERE e_id='$employeeid' and MONTH(e_date)='$lastmonth' GROUP BY DAY(e_date)");
			$count =count($totalWorkingdays);
			
			if($lossofpayleaves > 0){
				$basicSal = " (A.emp_basic_pay - (A.emp_basic_pay/'$daysLastMth') * $lossofpayleaves)";
			}else{
				$basicSal = "  A.emp_basic_pay";
			}
			
		
			$salary  = $db->fetchQuery("SELECT *, IF(C.unit = 2, $basicSal*C.amount/100,amount) as totalamount,G.branch_name
			FROM employee A LEFT JOIN payroll_user_deductions B ON A.e_id = B.employee_id LEFT JOIN payroll_benifits_deductions C ON B.deduction_id= C.id LEFT JOIN department D ON D.depart_id= A.departid
												
												LEFT JOIN designation F ON F.desig_id= A.e_post
												LEFT JOIN branches G ON G.branch_id= A.branchid
												 WHERE A.e_id='$employeeid' order by c.name desc");
		
			$salRows = count($salary);
			
			for($k=0;$k<$salRows;$k++)
			{
			  $name_ded=$salary[$k]['name'];
			 $emp_basic_pay=$salary[$k]['emp_basic_pay'];
			
			  $amount_ded=$salary[$k]['amount'];
			
			$salary_DA  = $db->fetchQuery("SELECT amount from payroll_benifits_deductions where emp_id ='$employeeid' and name='DA'");
			if(!empty($salary_DA))
			 $DA=$salary_DA[0]['amount'];
			else
			 $DA=0;
			 
			  $salary_ALLOWANCE  = $db->fetchQuery("SELECT amount from payroll_benifits_deductions where emp_id ='$employeeid' and name='ALLOWANCE'");
			if(!empty($salary_ALLOWANCE))
			 $ALLOWANCE=$salary_ALLOWANCE[0]['amount'];
			else
			 $ALLOWANCE=0;
			 
			if($name_ded=='PF')
			{
			
			
				if(($emp_basic_pay+$DA) <= 6500)
				{
				 $totalamount_PF=($amount_ded*($emp_basic_pay+$DA))/100;
				$salary[$k]['totalamount']=$totalamount_PF;
				}
				else
				{
				$salary[$k]['totalamount']=$totalamount_PF=0;
				}
				
			
			
			}
			if($name_ded=='ESI')
			{

			$ded_amount=0;$earn_amount=0;
			
			$salary_ESI_earn  = $db->fetchQuery("SELECT * from payroll_benifits_deductions where emp_id ='$employeeid' and is_blocked=0 and name!='PF' and name!='ESI'");
			
			
			if(!empty($salary_ESI_earn))
			{	
			foreach($salary_ESI_earn as $salary_ESI_earns)
			{
				$ded_earn=$salary_ESI_earns['deduction_benefit'];
				$ded_earn_unit=$salary_ESI_earns['unit'];
				 $ded_earn_rp=$salary_ESI_earns['amount'];
				
				if($ded_earn_unit==2)
				{
				$ded_earn_amount=($ded_earn_rp*$emp_basic_pay)/100;
				}
				else
				{
				$ded_earn_amount=$ded_earn_rp;
				}
				
				if($ded_earn==1)
				{
				$ded_amount=$ded_amount+$ded_earn_amount;
				}
				elseif($ded_earn==2)
				{
				$earn_amount=$earn_amount+$ded_earn_amount;
				}
				
			}
			$earn_amount=$earn_amount+$emp_basic_pay;
			}		
			
			if(($emp_basic_pay+$ALLOWANCE) <= 15000)
				{
				 $totalamount_ALLOWANCE=($amount_ded*($emp_basic_pay+$ALLOWANCE))/100;
				 $salary[$k]['totalamount']=$totalamount_ALLOWANCE;
				}
				else
				{
				$salary[$k]['totalamount']=$totalamount_ALLOWANCE=0;
				}
			}
			
			
			}
			
			
			
			//if($lossofpayleaves > 0){
			//	$salary[$salRows-1]['emp_basic_pay'] = $salary[$salRows-1]['emp_basic_pay']-(($salary[$salRows-1]['emp_basic_pay']/$daysLastMth)*$lossofpayleaves);
			//}
			
			
			$salary[$salRows-1]['over_time_sal'] 	= $over_time_sal;
			$salary[$salRows-1]['over_time'] 	= $over_time;
			$salary[$salRows-1]['totalDays'] = $totalattendance;
			$salary[$salRows-1]['lastMonthDays'] =  $totalattendance;
			//$salary[$salRows-1]['lastMonthDays'] =  $workingDays-$earnedLeaves-$lossofpayleaves;
			$salary[$salRows-1]['totalDays'] =$daysLastMth;
			$salary[$salRows-1]['earnesLeaves'] =  $nolossleave;
			$salary[$salRows-1]['workingDays'] =  $workingDays;
			$salary[$salRows-1]['lossofpay'] =  $totallossleaves_final;
			$salary[$salRows-1]['status'] 	 = "notpaid";
			$salary[$salRows-1]['DA'] 	= $DA;
			$salary[$salRows-1]['grosssalary'] 	= ($earn_amount-($ded_amount+$totalamount_PF));
			$salary[$salRows-1]['PF'] 	= $totalamount_PF;
			$salary[$salRows-1]['ESI'] 	= $totalamount_ALLOWANCE;
			$salary[$salRows-1]['leave_tot_ded'] =  $leave_tot_ded='';
			}
			
			
		echo '{"salaryDetails":'.json_encode($salary).'}';
			 
			
}
elseif($action == "printsalary"){
		
		$employeeid = $_GET['emp_id'];
		$payperiod  = $_GET['from'];
		$branch  = $_GET['branch'];
		$requestedMonth	 =$_GET['month'];
		$requestedYear	 =$_GET['year'];
		
		if(!$requestedMonth){
			$requestedMonth	 	= date("m",strtotime(" -1 months"));
			 $requestedYear		=date("Y",strtotime(" -1 months"));
		}
		
		$earnedLeaves=0;
		$lossofpayleaves=0;
		
	 $givendate = "01-".$requestedMonth ."-". $requestedYear;
		//echo $givendate;
		$lastmonth = date('m',strtotime($givendate));
		$daysLastMth = date('t',strtotime($givendate));
		$yearofLastMth = date('Y',strtotime($givendate));
		 
		$date = $yearofLastMth."-".$lastmonth."-01";


		$firstOfLastmth= date('Y-m-01', strtotime($date));
		$endOfLastmth= date('Y-m-t', strtotime($date));
		 
		 
		 
		 $lastMtnHolidays = $db->fetchQuery("SELECT * FROM payroll_holiday_calendar WHERE MONTH(date)='$lastmonth' and YEAR(date)='$yearofLastMth' and is_blocked='0'");
		 $holidays=array();
		 foreach($lastMtnHolidays as $lastMtnHolidays){
			$holidays[]=$lastMtnHolidays['date'];
		 }
		 $workingDays=  $db->getWorkingDays($firstOfLastmth,$endOfLastmth,$holidays);
		
		//////////////////////////////////////////////// Check Payment Status //////////////////////////////////////////////////////////////////////
		
		$requestedDate = date('m-Y',strtotime($givendate));
		$getemployeeslist = $db->fetchQuery("SELECT * FROM employee WHERE branchid=$branch");
		
		$printpayslip='';
		foreach($getemployeeslist as $getemployeeslists)
		{
		
		 $employeeid=$getemployeeslists['e_id'];
		
		
		$paymentDetails= $db->fetchQuery("SELECT A.userid,B.deduction_total_amount as totalamount,B.deduction_id,
												C.*,D.*,A.earned_leaves as earnesLeaves ,A.lossofpay_leaves,
												A.basic_pay as emp_basic_pay, E.title as paymentMethod, A.payment_referance as referances
												FROM payroll_salary_pay A 
												
												LEFT JOIN payroll_payment_details B ON A.id = B.payment_id 
												LEFT JOIN payroll_benifits_deductions C ON B.deduction_id = C.id 
												LEFT JOIN employee D ON A.userid= D.e_id
												LEFT JOIN payroll_payment_methods E ON A.payment_method = E.id
												  WHERE pay_period ='$requestedDate' and userid='$employeeid'");
		
		
	
		//print_r($paymentDetails);
		$salRows = count($paymentDetails);
		if($salRows > 0){	
			//if($lossofpayleaves > 0){
			//	$salary[$salRows-1]['emp_basic_pay'] = $salary[$salRows-1]['emp_basic_pay']-(($salary[$salRows-1]['emp_basic_pay']/$daysLastMth)*$lossofpayleaves);
			//}
			$salary  =$paymentDetails;
			$salary[$salRows-1]['totalDays'] = $count;
			$salary[$salRows-1]['lossofpay'] =  $salary[$salRows-1]['lossofpay_leaves'];
			
			$salary[$salRows-1]['lastMonthDays'] =  $workingDays-$salary[$salRows-1]['earnesLeaves']-$salary[$salRows-1]['lossofpay'];
			$salary[$salRows-1]['totalDays'] =$daysLastMth;
			$salary[$salRows-1]['status'] ="paid";
			//$salary[$salRows-1]['earnesLeaves'] =  $earnedLeaves;
			
		
		}else{
		
		///////////////////////////////////////////////// Start Payslip details collection /////////////////////////////////////////////////////////
		
		
		 /// Monthly requested leaves;
		 //find allowed leaves and leave tyes
		 $leaves = $db->fetchQuery("SELECT * FROM payroll_user_leave_requests A 
		 									LEFT JOIN payroll_leave B ON A.leave_id=B.lid
		 									WHERE employee_id='$employeeid' AND (MONTH(day_from) ='$lastmonth' OR MONTH(day_to) ='$lastmonth') AND B.based_on='1' ");
		  $a=0;
	
		//  echo "SELECT * FROM payroll_user_leave_requests WHERE employee_id='$employeeid' AND (MONTH(day_from) ='$lastmonth' OR MONTH(day_to) ='$lastmonth') ";
		$totalleaves = 0;
		 foreach($leaves as $leaves){
		 	$day_from 	= $leaves['day_from'];
			$day_to		= $leaves['day_to'];
			
			if($endOfLastmth > $day_from &&  $endOfLastmth < $day_to){
				$totalleaves += $db->getWorkingDays( $day_from,$endOfLastmth ,$holidays);
				
			}elseif($firstOfLastmth > $day_from &&  $endOfLastmth > $day_to){
				$totalleaves += $db->getWorkingDays( $firstOfLastmth,$day_to ,$holidays);
				
			}elseif($day_to > $firstOfLastmth &&  $day_from > $firstOfLastmth && $day_to < $endOfLastmth &&  $day_from < $endOfLastmth){
				$totalleaves += $db->getWorkingDays( $day_from,$day_to ,$holidays);
			}
			
			$a++;
		 }
			//echo $totalleaves;
			// Mthly allowed leaves
			$mthlyAllowedLeaves = $db->fetchQuery("SELECT * FROM payroll_user_leave A
														LEFT JOIN payroll_leave B ON A.leave_id=B.lid WHERE A.employee_id='$employeeid' and B.based_on='1'");
			$totalAllowedLeavesPerMth=0;
			$totallossofpay=0;												
			foreach($mthlyAllowedLeaves as $mthlyAllowedLeaves){
				if($mthlyAllowedLeaves['earned'] == 1){
					$totalAllowedLeavesPerMth += $mthlyAllowedLeaves['number_of_days'];
				}else{
					$totallossofpay +=$mthlyAllowedLeaves['number_of_days'];
				}
				
			}											
			
								

			
			
			// Yearly allowed leaves
			$yearlyAllowedLeaves = $db->fetchQuery("SELECT * FROM payroll_user_leave A
														LEFT JOIN payroll_leave B ON A.leave_id=B.lid WHERE A.employee_id='$employeeid' and B.based_on='2'");
			$totalAllowedLeavesPeryearly=0;
										
			foreach($yearlyAllowedLeaves as $yearlyAllowedLeaves){
			
				if($yearlyAllowedLeaves['earned'] == 1){
					$totalAllowedLeavesPeryearly += $yearlyAllowedLeaves['number_of_days'];
				}else{
					$totallossofpay +=$yearlyAllowedLeaves['number_of_days'];
				}
			}											
			
			// Yearly requested leaves
			$yearlyRequestedLeaves = $db->fetchQuery("SELECT * FROM payroll_user_leave_requests A 
														LEFT JOIN payroll_leave B ON A.leave_id = B.lid 
														WHERE A.employee_id='$employeeid' 
														AND B.based_on='2' and (YEAR(day_from) ='$yearofLastMth' or YEAR(day_to)='$yearofLastMth')");
			$yearlyRequestedLeave=0;
														
			foreach($yearlyRequestedLeaves as $yearlyRequestedLeaves){
					$yearlyRequestedLeave += $yearlyRequestedLeaves['no_of_days'];
					
					$day_from 	= $yearlyRequestedLeaves['day_from'];
					$day_to		= $yearlyRequestedLeaves['day_to'];
					
					if($endOfLastmth > $day_from &&  $endOfLastmth < $day_to){
						$totalleavesYearly += $db->getWorkingDays( $day_from,$endOfLastmth ,$holidays);
						
					}elseif($firstOfLastmth > $day_from &&  $endOfLastmth > $day_to){
						$totalleavesYearly += $db->getWorkingDays( $firstOfLastmth,$day_to ,$holidays);
						
					}elseif($day_to > $firstOfLastmth &&  $day_from > $firstOfLastmth && $day_to < $endOfLastmth &&  $day_from < $endOfLastmth){
						$totalleavesYearly += $db->getWorkingDays( $day_from,$day_to ,$holidays);
					}
					
					
			}										
				
			
			/////// Balance leaves in this year (earned);
			$balanceLeavesInThisYear =  $totalAllowedLeavesPeryearly-$yearlyRequestedLeave;	
			
			/////// Balance leaves in this Mth (earned);
			$leavesInthisMth =$totalAllowedLeavesPerMth-$totalleaves;
			
			
			/////// Leave calculation based on month.
			if($totalAllowedLeavesPerMth < $totalleaves){
				$lossofpayleaves = $totalleaves-$totalAllowedLeavesPerMth;
				$earnedLeaves	 = $totalAllowedLeavesPerMth;
			}else{
				$lossofpayleaves = 0;
				$earnedLeaves	 = $totalleaves;
			}	
			
			
			//echo $lossofpayleaves;
			
			if($totalleavesYearly > 0){
			
				if($totalAllowedLeavesPeryearly > $yearlyRequestedLeave){
					$earnedLeaves += $yearlyRequestedLeave;
					$lossofpayleaves += 0;
				}else{
					$earnedLeaves += $totalAllowedLeavesPeryearly;
					$lossofpayleaves += $yearlyRequestedLeave-$totalAllowedLeavesPeryearly;
				}
				
			}
			
			
		/*	if($lossofpayleaves > 0 ){
				
			/////// Check Requested Leave from yearly based;
				if($yearlyRequestedLeave > 0 && $lossofpayleaves  > $yearlyRequestedLeave){
				
					$lossofpayleaves = $lossofpayleaves-$yearlyRequestedLeave;
					$earnedLeaves	 = $earnedLeaves + $yearlyRequestedLeave;
					
				}elseif($yearlyRequestedLeave > 0 && $lossofpayleaves  < $yearlyRequestedLeave){
				
					$lossofpayleaves = $yearlyRequestedLeave-$lossofpayleaves;
					$earnedLeaves	 = $earnedLeaves + ($yearlyRequestedLeave-$lossofpayleaves);
					
				}
				
			}*/
			
			
											
		 
		
		
		 
			$totalWorkingdays = $db->fetchQuery("SELECT count(e_id) as totalDays FROM time WHERE e_id='$employeeid' and MONTH(e_date)='$lastmonth' GROUP BY DAY(e_date)");
			$count =count($totalWorkingdays);
			
			if($lossofpayleaves > 0){
				$basicSal = " (A.emp_basic_pay - (A.emp_basic_pay/'$daysLastMth') * $lossofpayleaves)";
			}else{
				$basicSal = "  A.emp_basic_pay";
			}
			
			$salary  = $db->fetchQuery("SELECT *, IF(C.unit = 2, $basicSal*C.amount/100,amount) as totalamount
			FROM employee A LEFT JOIN payroll_user_deductions B ON A.e_id = B.employee_id LEFT JOIN payroll_benifits_deductions C ON B.deduction_id= C.id WHERE A.e_id='$employeeid'");
		
			$salRows = count($salary);
			
			//if($lossofpayleaves > 0){
			//	$salary[$salRows-1]['emp_basic_pay'] = $salary[$salRows-1]['emp_basic_pay']-(($salary[$salRows-1]['emp_basic_pay']/$daysLastMth)*$lossofpayleaves);
			//}
			$salary[$salRows-1]['totalDays'] = $count;
			$salary[$salRows-1]['lastMonthDays'] =  $workingDays-$earnedLeaves-$lossofpayleaves;
			$salary[$salRows-1]['totalDays'] =$daysLastMth;
			
			$salary[$salRows-1]['earnesLeaves'] =  $earnedLeaves;
			$salary[$salRows-1]['lossofpay'] =  $lossofpayleaves;
			$salary[$salRows-1]['status'] 	 = "notpaid";
			
			}
			
		
						$printpayslip.="<table width='100%' style='display:block' height='224' class='paySlip' border='1' cellpadding='0' cellspacing='0'> 
							   <tr> 
								 <td height='80' align='center'> 
								<div class='pay-slip-title-res-name' style='height:50px;'></div> 
								 <div class='pay-slip-title'>Pay Slip for the period of ".$requestedDate."</div></td> 
								 </tr> 
							   <tr> 
								 <td height='122' valign='top'><table class='employee-details' width='100%' height='121' border='1' cellpadding='0' cellspacing='0'> 
								   <tr> 
									 <td width='13%'>Employee ID</td> 
									 <td width='37%' class='empid'>".$salary[0]['e_id']."</td> 
									 <td width='14%'>Employee Name</td> 
									 <td width='36%' class='empname'>".$salary[0]['e_fname']."</td> 
								   </tr> 
								   <tr> 
									 <td>Joining Date</td> 
									 <td class='joiningdate'>".date('d-m-Y',strtotime($salary[0]['e_dstart']))."</td> 
									 <td>Designation</td> 
									 <td class='designation'>".$salary[0]['departid']."</td> 
								   </tr> 
								   
								 </table></td> 
							   </tr> 
							   <tr> 
								 <td height='122' valign='top'> 
								
								 <table width='100%' class='earnings-deduction' border='1' cellpadding='0' cellspacing='0'> 
								   <tr> 
									 <td width='50%' height='30'>Earning</td> 
									 <td width='50%'>Deductions</td> 
								   </tr> 
								   
								   <tr><td valign='top' class='totalEarnings'> 
								   <span class='basicPay' style='width:80%; height:25px; float:left;'>Basic Pay</span> 
									 <span class='basicPayAmt' style='float:right; width:20%; text-align:right;'>".$salary[0]['emp_basic_pay']."</span> 

								  
								   </td><td valign='top' class='totalDeductions'> 
								  

								  
								   </td></tr> ";
								  $perdaydeduction=$salary[0]['emp_basic_pay']/30;
								  $perdaydeduction=round($perdaydeduction,2);
								$totalearnings+=round($salary[0]['emp_basic_pay']);
								   foreach($salary as $salary)
								   {
								   
								   if($salary['deduction_benefit']==2)
								   {
								   
								   $totalearnings+=round($salary['totalamount'],2);
								   
								$printpayslip.="<tr><td valign='top' class='totalEarnings'> 
								   <span class='basicPay' style='width:80%; height:25px; float:left;'>".$salary['name']."</span> 
									 <span class='basicPayAmt' style='float:right; width:20%; text-align:right;'>".round($salary['totalamount'],2)."</span> 

								  
								   </td><td valign='top' class='totalDeductions'> 
								  

								  
								   </td></tr>";
								   }
								   if($salary['deduction_benefit']==1)
								   {
								   $totaldeductions+=round($salary['totalamount'],2);
								  
								 $printpayslip.="<tr><td valign='top' class='totalEarnings'> 
								   
								  
								   </td><td valign='top' class='totalDeductions'> 
								   <span class='basicPay' style='width:80%; height:25px; float:left;'>".$salary['name']."</span> 
									 <span class='basicPayAmt' style='float:right; width:20%; text-align:right;'>".round($salary['totalamount'],2)."</span> 

								  
								   </td></tr>";
								   
								   
								   }
								  $lossofpay=$salary['lossofpay'];
								 
								   }
								  
								  
								 
								     $totaldeductions+=($perdaydeduction*$lossofpay);
									
								    $printpayslip.="
									<tr><td valign='top' class='totalEarnings'> 
								  
								  
								   </td><td valign='top' class='totalDeductions'> 
								  
 <span class='basicPay' style='width:80%; height:25px; float:left;'>Leave</span> 
									 <span class='basicPayAmt' style='float:right; width:20%; text-align:right;'>".($perdaydeduction*$lossofpay)."</span> 

								  
								   </td></tr> 
								   <tr class='total-earnings'> 
									 <td  height='30'><span class='earnings' style='width:80%; height:25px; float:left;'>Total Earnings</span> 
									 <span class='totalEarningsAmount' style='float:right; width:20%; text-align:right;'>".$totalearnings."</span></td> 
									 <td><span class='earnings' style='width:80%; height:25px; float:left;'>Total Deduction</span> 
									 <span class='totalDeductionAmount' style='float:right; width:20%; text-align:right;'>".$totaldeductions."</span></td> 
								   </tr> 
								  
								 </table></td> 
								 </tr> 
							   <tr> 
								 <td> 
								
								 <table width='100%' border='1' cellspacing='0' cellpadding='0' class='paymentSummery'> 
                                   <tr> 
                                     <td width='50%'></td> 
									
                                     <td><span class='earnings' style='width:80%; height:25px; float:left;'>Net Payable</span> 
									 <span class='netPayable' style='float:right; width:20%; text-align:right;'>".($totalearnings-$totaldeductions)."</span></td> 
                                   </tr> 

                                 </table> 
								
								 </td> 
							   </tr> 
							   
							 </table>";
			$totalearnings=0;
			$totaldeductions=0;
			
			}
			echo $printpayslip;
			exit;
		echo '{"salaryDetails":'.json_encode($salary).'}';
			 
			}
elseif($action == 'paySal'){



$cntdeduction=count($_POST['deductionhiddenAmt']);
$totalded=0;
$allowance=0;
$incentive=0;
for($i=0;$i<$cntdeduction;$i++)
{
$ded_amt=$_POST['deductionhiddenAmt'][$i];
$totalded=$totalded+$ded_amt;
}

$get_earnings = $db->fetchQuery("SELECT * FROM payroll_benifits_deductions WHERE emp_id ='".$_POST['userid']."'");
foreach($get_earnings as $earnings)
{
	//print_r($earnings);
	if($earnings['name'] == 'ALLOWANCE')
	{
		$allowance = $earnings['amount'];
	}
	
	if($earnings['name'] == 'INCENTIVE')
	{
		$incentive = $earnings['amount'];
	}
}


	//payroll_salary_pay
	//payroll_payment_details
	$vars['payment_date']		= date('Y-m-d H:i:s');
	$pf_esi['emp_id']	= $vars['userid']	= $_POST['userid'];
	$vars['total_payable']	 	= $_POST['total_payable'];
	//$vars['total_payable']	 	= $_POST['total_payable'];
	$vars['total_paid']	 		= $_POST['total_payable'];
	$vars['payment_method']	 	= $_POST['paymentThrough'];
	$vars['payment_referance']	= $_POST['referance'];
	
	$vars['basic_pay']			= $_POST['basicPayAmt'];
	$vars['earned_leaves']		= $_POST['earned_leaves'];
	$vars['lossofpay_leaves']	= $_POST['lossofpay_leaves'];
	$vars['leave_deduction']	= $_POST['leave_deduction'];
	$vars['total_earnings']	= $_POST['total_earnings'];
	$vars['total_deduction']	= $totalded+$vars['leave_deduction'];
	
	$vars['worked_days']	=$_POST['totworkeddays'];
	$vars['allowance_amt']	= $allowance;
	$vars['incentive_amt']	= $incentive;
	$vars['total_payable_words']	= $_POST['sum_to_words'];
	$emp_da		= $_POST['emp_da'];
	$grosssalary= $_POST['grosssalary'];
	$pf_esi['emp_pf']	= $_POST['emp_PF'];
	$pf_esi['emp_esi'] = $_POST['emp_ESI'];
	
	
	if(($_POST['emp_PF']>0) && (($emp_da+$vars['basic_pay'])<=6500))
	{
	$pf_esi['cmp_pf']	=$PF_cmpny=($_POST['basicPayAmt']*13.61)/100;
	
	}
	else
	{
	$pf_esi['cmp_pf']	=$PF_cmpny=0;
	}
	if($_POST['emp_ESI']>0)
	{
	$pf_esi['cmp_esi']	=$ESI_cmpny=($_POST['emp_ESI']*4.75)/1.75;
	}
	else
	{
	$pf_esi['cmp_esi']	=$ESI_cmpny=0;
	}
	
	
	$pf_esi['pay_period']	= $vars['pay_period']	=$_POST['year']."-".$_POST['month']."-"."01";
	
	
	$db->Insert($vars,'payroll_salary_pay');
	
	$paymentid = $db->LastInsertID();
	
	
	$pf_esi['salary_pay_id']= $data['payment_id']	 	= $paymentid;
	$data['user_id']	 	= $_POST['userid'];
	
	$pf_esi['date']	= $data['date']			= date('Y-m-d H:i:s');
	
	$db->Insert($pf_esi,'pf_esi_details');
	$k=0;
	foreach($_POST['deductionAmt']  as $deduction){
	
		$data['deduction_id']	 		= $_POST['deductionId'][$k];
		$data['deduction_total_amount']	= $_POST['deductionAmt'][$k];
		$data['deduction_price']	 	= $_POST['deductionPrice'][$k];
		$data['deduction_unit']	 		= $_POST['deductionUnit'][$k];
		$db->Insert($data,'payroll_payment_details');
		$k++;
		
	}
	
	
}elseif($action == "updateBasicPay"){
	$set['emp_basic_pay'] = $_GET['newSalary'];
	$where['e_id'] = $_GET['eid'];
	$db->Update('employee',$set,$where);
}
elseif($action == "updateovertime"){
	$set['over_time'] = $_GET['newSalary'];
	$where['e_id'] = $_GET['eid'];
	$db->Update('employee',$set,$where);
}
/*SELECT A.e_fname,A.emp_basic_pay, 
	
	IF(C.deduction_benefit=2,sum( IF(C.unit = 2, A.emp_basic_pay*C.amount/100,amount)),null) as benefits, 
	IF(C.deduction_benefit=1,sum( IF(C.unit = 2, A.emp_basic_pay*C.amount/100,amount)),null) as deduction, 
	
	c.amount FROM employee A LEFT JOIN payroll_user_deductions B ON A.e_id = B.employee_id LEFT JOIN payroll_benifits_deductions C ON B.deduction_id= C.id GROUP BY A.e_id'*/

?>