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

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

if($action == "totval"){



			$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.php";

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

/*if(isset($_REQUEST['page'])){
$page=$_REQUEST['page'];
}else{
$page=15;
}*/

$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['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++;
		
		
			
			
			
			$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;
			$basicpaytotal=$basicpaytotal+$list['emp_basic_pay'];
			$deductiontotal=$deductiontotal+$totalDeductionAmt+$paymentperDay;
			$benefittotal=$benefittotal+$totalBenefitAmt;
			$contributiontotal=$contributiontotal+$totalContributionAmt;
			$completetotal=$completetotal+(($list['emp_basic_pay']-($totalDeductionAmt+$paymentperDay)+$totalBenefitAmt+$totalContributionAmt));
			
			
			
		$b++;
	}
	
	//print_r($salaryList);
			$totalsalary[$b]['basicpaytotal'] = $basicpaytotal;
			$totalsalary[$b]['deductiontotal'] = $deductiontotal;
			$totalsalary[$b]['benefittotal'] = $benefittotal;
			$totalsalary[$b]['contributiontotal'] = $contributiontotal;
			$totalsalary[$b]['completetotal'] = $completetotal;
	$count = count($salaryList);
	$salaryList[$count-1]['totalrows'] = $total_pages;
	
	echo '{"salaryTotal":'.json_encode($totalsalary).'}';
	
}
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"){
		
		$employeeid = $_GET['emp_id'];
		$payperiod  = $_GET['from'];
		
		$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));
		$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";
			
			}
			
		echo '{"salaryTotal":'.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 '{"salaryTotal":'.json_encode($salary).'}';
			 
			}elseif($action == 'paySal'){
	//payroll_salary_pay
	//payroll_payment_details
	$vars['payment_date']		= date('Y-m-d H:i:s');
	$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['pay_period']	=$_POST['month']."-".$_POST['year'];
	
	
	$db->Insert($vars,'payroll_salary_pay');
	$paymentid = $db->LastInsertID();
	
	
	$data['payment_id']	 	= $paymentid;
	$data['user_id']	 	= $_POST['userid'];
	$data['date']			= date('Y-m-d H:i:s');
	
	$k=0;
	foreach($_POST['deductionAmt']  as $deduction){
	echo "<br/>".$_POST['payroll_payment_details'][$k];
		$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);
}

/*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'*/

?>