<?php
	ob_start();
	session_start();
	function firstSunday($DATE)
    {
	// $DATE='2014-04-01';
         $date = date('Y-m',strtotime($DATE));
         $day = trim(strtotime("%e",$DATE));

        for($day; $day <= '7'; $day++){
             $dd = strftime("%A",strtotime($date.'-'.$day));
            if($dd == 'Sunday'){
                return $day;
            }
        }
    }
?>
<?php 
include_once("../class/class.MySQL.php");
include_once("../class/userdefinedfunctions.php");
$db	=new MySQL();
$userfunction	=new userdefinefunctions();

//////////////////////////////// GET Branch list /////////////////////////
if(isset($_GET['act']) && $_GET['act']=='getbranch'){
	$empid = $_GET['eid'];
	$getBranch = $db->ExecuteSQL("SELECT branchid FROM employee WHERE e_id='$empid'");
	echo '{"emp":'.json_encode($getBranch).'}';
}else{




//----------------------------------------retrieving get values--------------------//
$limit=$page_emp;
$page=1; $employees='';
$basicnt=0;
$sumtotaltime =0;$brch_half=0;
$month=date("m");
$year=date("Y");
if(isset($_GET['page']))
$page=$_GET['page'];
else
$page=1;
if($page) 
		$start = ($page - 1) * $limit;  //first item to display on this page
	else
		$start = 0;			
if(isset($_GET['month']) && ($_GET['month']!='undefined' || $_GET['month']!=''))
{

$month=$_GET['month'];
}
else
{
$month=date("m");
}
if(isset($_GET['year'])  && ($_GET['year']!='undefined'  || $_GET['year']!='' ))
{
$year=$_GET['year'];
}
else
{
$year=date("Y");
}
if(isset($_GET['employees']))
{
 
 $employees=$_GET['employees'];
}

//---------------------------------------------------------------------------------------------//
$start=0;
$view="";

if($month=='null')$month=date('m');if($year=='null')$year=date("Y");
if($employees=='null'){
$qqry="select  e_id from employee limit 0,1";
$ssql=mysql_query($qqry);
$oobj=mysql_fetch_object($ssql);
$employees=$oobj->e_id;
}
else
{

$qqry="select  employee.e_fname,branches.brch_half from employee  LEFT JOIN branches  ON employee.branchid = branches.branch_id where e_id='$employees' limit 0,1";
$ssql=mysql_query($qqry);
$oobj=mysql_fetch_object($ssql);
$employees_name=$oobj->e_fname;
$brch_half=$oobj->brch_half;
}

$nummonth=cal_days_in_month(CAL_GREGORIAN,$month,$year);
$check=$year.'-'.$month;

$todaysday=date('Y-m-d');

$endOfLastmth=$year.'-'.$month.'-31';
$firstOfLastmth=$year.'-01-01';
$firstOfLastmth2=$year.'-05-01';
    $lastMtnHolidays = $db->fetchQuery("SELECT * FROM payroll_holiday_calendar WHERE MONTH(date)='$month' and YEAR(date)='$year' and is_blocked='0' and employee_id=1 group by date");
   
   $holidays=array();
   foreach($lastMtnHolidays as $lastMtnHolidays){
   $holidays[]=$lastMtnHolidays['date'];
   }
  
   $noofholidays=count($holidays);
   //echo "SELECT count(id) FROM time WHERE e_date>='$firstOfLastmth' and date<='$endOfLastmth'";
   
   $workingDays=  $db->getWorkingDays($firstOfLastmth,$endOfLastmth,$holidays);
    
	$workingDays2=  $db->getWorkingDays($firstOfLastmth2,$endOfLastmth,$holidays);

	$lastyrattendance = $db->fetchQuery("SELECT count(distinct(e_date)) FROM time WHERE e_date>='$firstOfLastmth2' and e_date<='$endOfLastmth' and e_id='$employees'");
	 
	 $yrattendance2=$lastyrattendance[0]['count(distinct(e_date))'];
	 
	$lastyrattendance = $db->fetchQuery("SELECT count(distinct(e_date)) FROM time WHERE e_date>='$firstOfLastmth' and e_date<='$endOfLastmth' and e_id='$employees'");
	 
	 $yrattendance=$lastyrattendance[0]['count(distinct(e_date))'];
	 
	$availedleaves=$workingDays2-$yrattendance2;
	 
	
	 	$nolossleaveapplied = $db->fetchQuery("Select count(*) as nolossleave from payroll_user_leave_requests where employee_id=$employees and is_cancelled=0 and imd_status=1 and day_from>='$firstOfLastmth2' and day_from<='$endOfLastmth' and (leave_id='3' or leave_id='1') ");
	 
	   $nolossleaves=$nolossleaveapplied[0]['nolossleave'];
	
	$leavesentitledqry = $db->fetchQuery("SELECT sum(`number_of_days`) as entitled FROM `payroll_leave` WHERE `lid` IN  (select `leave_id` from `payroll_user_leave` where `employee_id`='$employees')");
	$leavesentitled=$leavesentitledqry[0]['entitled'];
	
	
	$balanceleaves=$leavesentitled-$nolossleaves;
	
	if($balanceleaves<0)
	{
	$balanceleaves=0;
	}
/* $sql=" select a.* from time as a,employee as b where a.e_id=b.e_id and a.e_id=".$employees." and    DATE_FORMAT(a.e_date,'%m-%Y') = '".$month."-".$year."' limit ".$start.",".$limit;
$employees=$db->fetchQuery($sql);

*/ 
$headingview='<div class="employee-tab-01">
<div class="employee-tab-head"><span id="Emp_Name">'.$employees_name.'</span>Timesheet As on <span  id="selmonth" >'.date("F", mktime(0, 0, 0, $month, 10)).''.$year.'</span></div>
<div class="employee-tab-dwn"></div>';

////////////////////////Alotted leaves Heading-------------;/////////////////////
/*$alotted_view ='

<div class="clear-float"></div>
</div>
<div style="font-size:13px;"><table  border="0" cellspacing="5" cellpadding="5">
<tr><td>Allotted Leaves:</td><td style="border-right:1px solid #aaa; padding-right:8px;">'.$leavesentitled.'</td>
<td >Availed Leaves:</td><td style="border-right:1px solid #aaa; padding-right:8px;">'.$availedleaves.'</td>
<td >Balance Leaves:</td><td>'.$balanceleaves.'</td><tr>
</table>
</div>';*/

////////////////////////Alotted leaves Heading end-------------;/////////////////////
/*<div class="employee-col-01" style="width:37px;float:left;">
<table width="37" border="1" cellspacing="0" cellpadding="0">
  <tr>
    <td align="center" valign="middle">Date</td>
  </tr>';
  for($s=1;$s<=$nummonth;$s++)
  {
  $view.='<tr>
    <td align="center" valign="middle">'.$s.'</td>
  </tr>';
 }
 
$view.='</table>
</div> ';*/
 $view.=
'<div class="employee-col-02" style="width:900px;float:left;">
  <table width="900" border="1" cellspacing="0" cellpadding="0">
  <tr>
  	  <td align="center" valign="middle" class="employee-date-col-01" width="37" >Date</td>
	  <td align="center" valign="middle" class="employee-row-01">Status</td>
	  <td align="center" valign="middle" class="employee-row-01">Time In</td>
	  <td align="center" valign="middle" class="employee-row-01">Time Out</td>
	  <td align="center" valign="middle" class="employee-row-01">Total</td>
  </tr>';

$empid=$employees;
if($month=='null')$month=date("m");if($year=='null')$year=date("Y");


   $firstsunday = firstSunday('01'.'-'.$month.'-'.$year);
   
   $secondsunday=$firstsunday+7;
  	$thirdsunday=$secondsunday+7;
	$fourthsunday=$thirdsunday+7;
	if(($fourthsunday+7)<=$nummonth)
	$fivthsunday=$fourthsunday+7;
//---------------------------------------for date 1 of the selected month------------//

for($s=1;$s<=$nummonth;$s++)
  {

$view.='<tr>';
$datewise=$check.'-'.$s;
$datewise = date("Y-m-d",strtotime($datewise));

$qry=$userfunction->individual_qry($empid,$datewise,$db);



 $cnt= count($qry);

$diffcnt=4-$cnt;$num = 0;

?>

<?php

if($cnt>0)
{ 

$rtqry=$db->fetchQuery("select * from report_time ");
 $reportime=$rtqry[0]['late_time'];
 $reportfullday=$rtqry[0]['full_day'];
 $reporthalfday=$rtqry[0]['half_day'];
 $flag=0;
 for($num=0;$num < $noofholidays;$num++)
 {
 	$day=date('d',strtotime($holidays[$num]));
	if($day==$s)
	{
	$flag=1;
	break;
	}
 }
if($s!=$firstsunday && $s!=$secondsunday && $s!=$thirdsunday && $s!=$fourthsunday && $s!=$fivthsunday && ($flag!=1 || $cnt!=0))
{

for($k=0;$k<1;$k++)
{	
$view.=' <td align="center" class="employee-date-col-01" valign="middle">'.$s.'</td>  ';
$countqry= count($qry);

	if($countqry<=1)
	{
		$tot_time= $qry[$k]['total_worked_hours'];
	}
	else
	{
		$tot_time= $qry[$countqry-1]['total_worked_hours'];
	}
	

	$e_in= $qry[$k]['e_in'];
	$half='';
	$checkdate=$year.'-'.$month.'-'.$s;
	
	if($e_in <= $reportime)
	{
		if($brch_half=='1')
	{
		if(date('w', strtotime($checkdate)) == 6) 
		{
		if(($tot_time <= '0'.$reportfullday) && ($tot_time >= '0'.$reporthalfday))
		{
			$half = '';
		}
		$view.=' <td align="center" valign="middle"   bgcolor="#45a9cb">Present ' .$half.'</td>  ';
		}
		else
		{
		if(($tot_time <= '0'.$reportfullday) && ($tot_time >= '0'.$reporthalfday))
		{
			$half = '(Half Day)';
		}
		$view.=' <td align="center" valign="middle"   bgcolor="#45a9cb">Present ' .$half.'</td>  ';
		
		}
	}
		else
		{
		
		if(($tot_time <= '0'.$reportfullday) && ($tot_time >= '0'.$reporthalfday))
		{
			$half = '(Half Day)';
		}
		$view.=' <td align="center" valign="middle"   bgcolor="#45a9cb">Present ' .$half.'</td>  ';
		
		
		
		}
	}
	elseif($e_in > $reportime)
	{
		if(($tot_time <= '0'.$reportfullday)  && ($tot_time >= '0'.$reporthalfday))
		{
		
		if($brch_half=='1')
	{
			if(date('w', strtotime($checkdate)) == 6) 
		{
			$half = '';
			$view.=' <td align="center" valign="middle"  bgcolor="#bc202b" >Delay ' .$half.'</td>';
			}
			else
			{
			$half = '(Half Day)';
			$view.=' <td align="center" valign="middle"  bgcolor="#bc202b" >Delay ' .$half.'</td>';
			
		}
	}
	else
	{
	$half = '(Half Day)';
			$view.=' <td align="center" valign="middle"  bgcolor="#bc202b" >Delay ' .$half.'</td>';
	
	}
	
	}
	
	else
	{
		$view.=' <td align="center" valign="middle"  bgcolor="#bc202b" >Delay</td>  ';
	
	}
	}
	else
	{
		
	}
	
	if($e_in=="")$e_in="ww:00:00";
	if($countqry<=1)
	{
	$e_out= $qry[$k]['e_out'];
	}
	else
	{
	
	$e_out= $qry[$countqry-1]['e_out'];
	}
	if($e_out=="")$e_out="ee:00:00";
	$view.=' <td align="center" valign="middle"> '.$e_in.'</td><td align="center" valign="middle"> '.$e_out.'</td> ';
	
	
	
	$sumtotaltime = $sumtotaltime + strtotime($tot_time);
	$view.=' <td align="center" valign="middle">'.$tot_time.'</td>  ';
	
	
}

}

else
{

/*$view.=' <td align="center" class="employee-date-col-01" valign="middle">'.$s.'</td>   <td align="center" valign="middle"   bgcolor="#4edfc0" >Sun</td>  <td align="center" valign="middle"  bgcolor="#4edfc0">Sun</td><td align="center" valign="middle"  bgcolor="#4edfc0">Sun</td><td align="center" valign="middle"  bgcolor="#4edfc0">Sun</td>  ';*/

if($flag==0)
		{
		$view.=' <td align="center" class="employee-date-col-01" valign="middle">'.$s.'</td>   <td align="center" valign="middle"   bgcolor="#4edfc0" >Sun</td>  <td align="center" valign="middle"  bgcolor="#4edfc0">Sun</td><td align="center" valign="middle"  bgcolor="#4edfc0">Sun</td><td align="center" valign="middle"  bgcolor="#4edfc0">Sun</td>  ';
		}
		else
		{
		$view.=' <td align="center" class="employee-date-col-01" valign="middle">'.$s.'</td>   <td align="center" valign="middle"   bgcolor="#4edfc0" >Holiday</td>  <td align="center" valign="middle"  bgcolor="#4edfc0">Holiday</td><td align="center" valign="middle"  bgcolor="#4edfc0">Holiday</td><td align="center" valign="middle"  bgcolor="#4edfc0">Holiday</td>  ';
		}

}



$get_time[$basicnt]=$tot_time;

$basicnt++;


/*foreach($qry as $qry)
{
  	$e_in= $qry['e_in'];
	if($e_in=="")$e_in="00:00:00";
	$e_out= $qry['e_out'];
	if($e_out=="")$e_out="00:00:00";
	$view.=' <td align="center" valign="middle"> '.$e_in.'</td><td align="center" valign="middle"> '.$e_out.'</td> ';
	
}*/

if($diffcnt>0)
	{
		for($c=1;$c<=$diffcnt;$c++)
		{
			//$view.=' <td align="center" valign="middle">&nbsp;</td><td align="center" valign="middle">&nbsp;</td> ';
		}
	}
	//$tot_time=$userfunction->ind_calldisplay($empid,$datewise,$db);
	
}
else
{
$flag=0;
for($num=0;$num<$noofholidays;$num++)
 {
 
  $day=date('d',strtotime($holidays[$num]));
	if($day==$s)
	{
	$flag=1;
	break;
	}
 }
 
 
if($s!=$firstsunday && $s!=$secondsunday && $s!=$thirdsunday && $s!=$fourthsunday && $s!=$fivthsunday && $flag!=1)
{
$view.=' <td align="center" class="employee-date-col-01" valign="middle">'.$s.'</td> ';
 $incrementdate=$year.'-'.$month.'-'.$s;



		if(strtotime($incrementdate)<strtotime($todaysday))
		{
		
		$leaveqry =$db->fetchQuery("select * from payroll_user_leave_requests where employee_id='$employees' and day_from='$incrementdate'");
		//echo "select * from payroll_user_leave_requests where employee_id='$employees' and day_from='$incrementdate'";
		//print_r($leaveqry);
		if(empty($leaveqry))
		{
		$view.=' <td align="center" valign="middle" bgcolor="#f46020" >Absent</td>  ';
		}
		else
		{
		   if($leaveqry[0]['imd_status']==0 && $leaveqry[0]['is_blocked']==1 )
		   {
		$view.=' <td align="center" valign="middle" bgcolor="#f46020" >Absent</td>  ';
		  }
		  else if($leaveqry[0]['imd_status']==0 && $leaveqry[0]['is_blocked']==0 )
		  {
		  $view.=' <td align="center" valign="middle" bgcolor="#f46020" >Absent</td>  ';
		  }
		  else
		  {
		  $view.=' <td align="center" valign="middle" bgcolor="#ffd109" >Leave</td>  ';
		  }
		}
		}
		else
		{
		$view.=' <td align="center" valign="middle">00:00:00</td>  ';
		}
for($c=2;$c<=4;$c++)
		{
			$view.=' <td align="center" valign="middle">00:00:00</td>  ';
		}
		
		}
		else
		{
		if($flag==0)
		{
		$view.=' <td align="center" class="employee-date-col-01" valign="middle">'.$s.'</td>   <td align="center" valign="middle"   bgcolor="#4edfc0" >Sun</td>  <td align="center" valign="middle"  bgcolor="#4edfc0">Sun</td><td align="center" valign="middle"  bgcolor="#4edfc0">Sun</td><td align="center" valign="middle"  bgcolor="#4edfc0">Sun</td>  ';
		}
		else
		{
		$view.=' <td align="center" class="employee-date-col-01" valign="middle">'.$s.'</td>   <td align="center" valign="middle"   bgcolor="#4edfc0" >Holiday</td>  <td align="center" valign="middle"  bgcolor="#4edfc0">Holiday</td><td align="center" valign="middle"  bgcolor="#4edfc0">Holiday</td><td align="center" valign="middle"  bgcolor="#4edfc0">Holiday</td>  ';
		}

}

}
	$view.='</tr>';
	
	}
//--end for date1----------------------------------------------------------------------------------------//

//--end for date1----------------------------------------------------------------------------------------//

$totaltimecnt=count($get_time);
$total_hr=0;$total_min=0;$total_sec=0;
for($newcnt=0;$newcnt<$totaltimecnt;$newcnt++)
{
$time=$get_time[$newcnt];

$explode_time=explode(":",$time);

$time_hr=$explode_time[0];
$total_hr=$total_hr+$time_hr;
$time_min=$explode_time[1];
$total_min=$total_min+$time_min;
$time_sec=$explode_time[2];
$total_sec=$total_sec+$time_sec;
}
$total_min=$total_min + intval($total_sec/60);
$total_sec=$total_sec%60;


$total_hr=$total_hr + intval($total_min/60);
$total_min=$total_min%60;
$total_time_hour=$total_hr.':'.$total_min.':'.$total_sec;
		   $view.=' </tr> ';

$time_query="select SEC_TO_TIME(SUM(TIME_TO_SEC(e_work))) as totalhours from TIME where month(e_date)='$month' and year(e_date)='$year' AND  e_id =".$empid."    ";	
					
		
		$sql_time=$db->fetchQuery($time_query);
		$totalhours=$sql_time[0]['totalhours'];
 $view.='  </table>




  <table width="100%" border="0" cellspacing="0" cellpadding="0" ><tr>
      <td colspan="3" style="padding-left:50px;font-weight:bold" class="employee-row-01" >Total</td>
      <td align="center" valign="middle" class="employee-row-01" style="font-weight:bold">'.$total_time_hour.'</td>
      </tr>
	  </table>
    </div>

<div class="clear-float"></div>';

$sub_rights=mysql_fetch_array(mysql_query("select * from menu as m,menu_sub as s where  s.s_menu_name='Timesheet_show' and m.menu_id=s.menu_id "));
	
	$userid=$_SESSION['admin_id'];

	$where['user_id']	= $userid;
	$where['s_submenu_id']	= $sub_rights['s_id'];
	
	$m_rights=mysql_fetch_array(mysql_query("select * from tbl_user_rights where  user_id='$userid' and s_submenu_id='$sub_rights[s_id]'"));
	
	
	if($userid!=1)
	{
	if($m_rights['view_right']==0)
 {
 $view='<font color="red" size="3"><b>Sorry You Do Not Have Enough Permission To View This Form....</b></font>';
 }
   }

$_SESSION['heading_view']=$headingview;
$_SESSION['download_view']=$view;
echo $alotted_view;
echo $view;
}