<?php

function getSalaryPayableDays($db,$branchid,$eid,$month,$year){


$firstDay = $year."-".$month."-1";
$lastDay  =  date("Y-m-t", strtotime($firstDay));


/////// GET ALL WORKED DAYS ///
$timingDetails 		= $db->fetchQuery("SELECT A.*,B.brch_half FROM report_time A LEFT JOIN branches B ON A.brch_id=B.branch_id WHERE A.brch_id = '$branchid' LIMIT 1");
$fullDayHrs 		= $timingDetails[0]['full_day'].":00";     //// =======  FDH
$halfDayHrs 		= $timingDetails[0]['half_day'].":00";    ///// =======  HDH



$reportTimeTimeMng 	= $timingDetails[0]['report_time'];  /////=======  RTM
$lateTimeTimeMng  	= $timingDetails[0]['late_time'];    /////=======  LTM

$reportTimeTimeEven = $timingDetails[0]['aftnoon_report_time']; //===  RTE
$lateTimeTimeEven  	= $timingDetails[0]['aftrnoon_late_time'];  //===  LTE

$numDelayForHalfDay = $timingDetails[0]['num_delay'];  ///////    ===  NDH   /// For half day deduction.
$saturdayHalfDay    = $timingDetails[0]['brch_half']; ////	=========  BHD


$worked_days = $db->fetchQuery("SELECT  SEC_TO_TIME( SUM( TIME_TO_SEC( total_worked_hours ) ) ) AS total_time,e_date,A.e_id  ,A.e_in
														FROM time A
														LEFT JOIN employee B ON A.e_id=B.e_id
														WHERE month(e_date)='$month' and  B.branchid='$branchid'
														 and A.e_id='$eid' GROUP BY A.e_date,A.e_id ORDER BY id ASC");

$workingDays['actualWorkingDays'] = count($worked_days);  // Before checking delay and half day calculations.

$workingDays['delayDays']=array();


$holidays = $db->fetchQuery("SELECT * FROM payroll_holiday_calendar WHERE month(date) = '$month' and YEAR(date)='$year' and branchid='$branchid' and is_blocked='0'");
$holiday=array();

foreach($holidays as $holidays){
	$holiday[]=$holidays['date'];
}
	
$workingDays['totalWorkingDays']=  $db->getWorkingDays($firstDay,$lastDay,$holiday);



$requestedLeaves = $db->fetchQuery("SELECT * FROM payroll_user_leave_requests 
										WHERE imd_status='1' and employee_id='$eid' and month(day_from)='$month' and YEAR(day_from)='$year'");


foreach($requestedLeaves as $requestedLeave){

	if($requestedLeave['half_full_day'] == 1){
		$allLeavesHalfArray[] = $requestedLeave['day_from'];
	}else{
		$allLeavesFullArray[] = $requestedLeave['day_from'];
	}
}


$workingDays['leaveWorking']['fullday'] = array(); 
$workingDays['leaveWorking']['halfdayApproved'] = array();
// GET DELAY DAYS.


foreach($worked_days as $workedday){

	 // CASE 1. //// In-time > delay Time and Worktime >= fullday time ---- then it should be Delay........
	if(date("H:i:s",strtotime($workedday['e_in'])) > $lateTimeTimeMng && $workedday['total_time'] >= date("H:i:s",strtotime($fullDayHrs)) ){
		$workingDays['delayDays'][] =  $workedday['e_date'];
	}else
	
	// CASE 2. //// ITM > LTM && TWT < FDH && TWT >= HDH  &&  (ITM < RTE || ITM > LTE) SHOULD BE delay
	if(date("H:i:s",strtotime($workedday['e_in'])) > $lateTimeTimeMng && ( $workedday['total_time'] < date("H:i:s",strtotime($fullDayHrs)) ) &&   
																			$workedday['total_time'] >= date("H:i:s",strtotime($halfDayHrs)) &&
						 ( date("H:i:s",strtotime($workedday['e_in'])) < $reportTimeTimeEven  || date("H:i:s",strtotime($workedday['e_in'])) > $lateTimeTimeEven )){

		 $workingDays['delayDays'][] =  $workedday['e_date']; 
		 
	}else
	
	// CASE 3.  ////  BHD == 1 && DAY(e_date) == SATURDAY && ITM > LTM   //  should be delay
	if($saturdayHalfDay == 1 && date("l",strtotime($workedday['e_date'])) == "Saturday" && 
								date("H:i:s",strtotime($workedday['e_in'])) > $lateTimeTimeMng && $workedday['total_time'] >= date("H:i:s",strtotime($halfDayHrs))){
								
		$workingDays['delayDays'][] =  $workedday['e_date'];
	}
	
	if($workedday['total_time'] >= date("H:i:s",strtotime($halfDayHrs)) && $workedday['total_time'] < date("H:i:s",strtotime($fullDayHrs)) && 
										(($saturdayHalfDay == 1 && date("l",strtotime($workedday['e_date'])) != "Saturday") || $saturdayHalfDay==0)){
		$workingDays['halfDay'][] =  $workedday['e_date'];
	}
	
	if($workedday['total_time'] < date("H:i:s",strtotime($halfDayHrs))){
		$workingDays['presentAbsent'][] =  $workedday['e_date'];
	}
	

	$searchHolidayWork = searchHolidayWork($workedday['e_date'],$holiday);
	if($searchHolidayWork != false){
		$workingDays['additionalDays'][] = $workedday['e_date'];
	}
	
	
	$leaveWorking	=	searchForLeavePresent($workedday['e_date'],$requestedLeaves); 
	if($leaveWorking!=''){
		if($leaveWorking == '1'){
		
		if($workedday['total_time'] >= date("H:i:s",strtotime($halfDayHrs)) && $workedday['total_time'] < date("H:i:s",strtotime($fullDayHrs)) && 
										(($saturdayHalfDay == 1 && date("l",strtotime($workedday['e_date'])) != "Saturday") || $saturdayHalfDay==0)){
			$workingDays['leaveWorking']['halfdayApproved'][] = $workedday['e_date'];
		}
			
		}else{
			$workingDays['leaveWorking']['fullday'][] = $workedday['e_date'];
		}
	}

}


$absendLeaves = array_diff($allLeavesFullArray,$workingDays['leaveWorking']['fullday']);
$absendHalfDayLeaves = array_diff($allLeavesHalfArray,$workingDays['leaveWorking']['halfdayApproved']);
$workingDays['approvedLeaves'] = $absendLeaves;
$workingDays['approvedLeavesHalfDay'] = $absendHalfDayLeaves;
$workingDays['approvedHalfDay'] = $allLeavesHalfArray;

/*echo "Total Working Days : ".$workingDays['totalWorkingDays']."<br/>";
echo "Actual Worked Days : ".count($worked_days)."<br/>";
echo "Delay Days :" . count($workingDays['delayDays'])."<br/>";
echo "Half Day Taken :" . count($workingDays['halfDay'])."<br/>";
echo "Half Day Allowed : ".count($allLeavesHalfArray)."<br/>";

echo "Full Day Allowed :" . count($allLeavesFullArray)."<br/>";
echo "Allowed Leve But Work : ".count($workingDays['leaveWorking']['fullday'])."<br/>";

echo "Additional Working :".count($workingDays['additionalDays'])."<br/>";
*/





$calc =  count($worked_days)-(intval(count($workingDays['delayDays'])/3) * 0.5) - 

							((count($workingDays['halfDay'])-count($allLeavesHalfArray))*0.5) +
							
							( count($allLeavesFullArray)-count($workingDays['leaveWorking']['fullday'])) -
							  count($workingDays['additionalDays']) - count($workingDays['presentAbsent']);

//echo "Salary Calculation Days : ".  $calc;
$workingDays['salaryPayableDays'] = $calc;


	return $workingDays;
}


function searchHolidayWork($date,$holiday){
	return array_search($date,$holiday);
}

function searchForLeavePresent($date, $array) {
   foreach ($array as $key => $val) {
       if ($val['day_from'] == $date) {
           return $val['half_full_day'];
       }
   }
   return null;
}
//print_r($workingDays);

?>