<script type="text/javascript" src="js/tableExport.js"></script>

<script type="text/javascript" src="js/jquery.base64.js"></script>

<style>.top-bar-minimize{display:none;}
thead, tfoot {display: table-header-group;}
.top-bar+.well,.accordion .accordion-heading+.accordion-body{display: inline-block !important;width: 100% !important;overflow: inherit !important;} 
.dynamic{display:none}
table td {
padding: 6px !important;
}
legend{line-height: 16px;font-weight:100;}  

.outer .MigrateLeftFee{
  background-color: #DADADA !important; 
  border: 5px solid #181616 !important;
  min-height: 440px;
  min-width:700px;
} 
.st {
	width: 55px;
	font-size:10px;
	display: inline-block;
	color: #021EF0;
}
.size{
	font-size:12px;
}
.recepit {
	width: 717px !important;
	height: 344px !important;
}
.total{
	color: darkgreen;
    font-weight: 800;
}
</style>

<?php
$pgMod="date_wise_report";
$pgAct="view";

$monthsList = array(
    'January',
    'February',
    'March',
    'April',
    'May',
  
    'July ',
    'August',
    'September',
    'October',
    'November',
    'December',
);
$monthsList1 = array(
    1=>'Apr',
    2=>'May',
    3=>'Jul ',
    4=>'Aug',
    5=>'Sep',
    6=>'Oct',
    7=>'Nov',
    8=>'Dec',
	9=>'Jan',
    10=>'Feb',
    11=>'Mar'
);

if(isset($_GET['action']) && trim($_GET['action'])!='')
		$pgAct=strtolower($_GET['action']);
if($pgAct=="delete" && isset($_GET['id']) && trim($_GET['id'])!='')
{
	$res=$db->delete("student","where school_id='".$_SESSION["admin"]["school_id"]."' and idno='".$_GET['id']."'");
	if(!is_null($res)) { $_SESSION['msg']='Deleted Successfully'; }
	else { array_push($alert_err,$db->getErMsg()); }
	redirect(URL_ADMIN_HOME.getQueryString(array("src"=>"Attendance", "page_id"=>$pgMod)));
}
if(isset($_SESSION['msg']) && $_SESSION['msg']!=""){
	?>
	<div class="alert alert-success">
	  <a class="close" data-dismiss="alert">×</a>
	  <i class="icon icon-thumbs-up-alt"></i> <b>Notice</b><?php echo $_SESSION['msg'] ?></i>
	</div>
	<?php
	unset($_SESSION["msg"]);
}
if(is_array($alert_err) && count($alert_err)>0){
	?>
	<div class="alert alert-error">
	  <a class="close" data-dismiss="alert">×</a>
	  <i class="icon icon-warning-sign"></i> <b>Notice</b> <?php echo $alert_err[0] ?></i>
	</div>
	<?php
}

	?>
    <form method="get" action="">
    <input type="hidden" name="src" value="Attendance" />
    <input type="hidden" name="page_id" value="<?php echo $pgMod; ?>" />
	<div class="row-fluid">
            <div class="span12">
            	<div class="top-bar">
                    <p>Face Attendance Report</p>
				</div>
				<div class="well no-padding">

                <div class="controls controls-row">
                        <div class="control-group span6">
                            <label class="control-label" for="class">From Date</label>
                            <div class="controls">
                                     <select class="span3" name="fdate"  id="date" style="width: 65px !important;">
                                    <option value="">Date</option>
                                    <?php
									$ndate=date("d");
									$mdate=date("m");
									$ydate=date("Y");
                                    for($m = 01;$m <= 31; $m++){
                                        $selected="";
										if($_GET["fdate"]==$m)
										{
											$selected=" selected ";
										}
										if($ndate==$m)
										{
											$selected=" selected ";
										}
                                        echo "<option $selected value='$m'>$m</option>";
                                    }
                                    ?> 
                                </select>
                                <select class="span5" name="fmonth" id="fmonth" style="width: 90px !important;">
                                    <option value="">Month</option>
                                 <?php
                                    for($m = 1;$m <= 12; $m++){ 
                                        $newDate=date("Y")."-".$m."-1";
                                        $month =  date("F",strtotime($newDate));//."(".($ij+3).")";
                                        //$month =  date("F", mktime(0, 0, 0, $m)); 
                                        $selected="";if($_GET["fmonth"]==$m)
										{
											$selected=" selected ";
										}
										
										if($mdate==$m)
										{
											$selected=" selected ";
										}
                                        echo "<option $selected value='$m'>$month</option>";
                                    }
                                 ?> 
                                </select>
                                <select class="span4" name="fyear" id="fyear" style="width: 73px !important;">
                                    <option value="">Year</option>
                                    <?php
                                    for($m = 2013;$m <= 2050; $m++){  
                                        $selected="";if($_GET["fyear"]==$m)
										{	
										$selected=" selected ";
										}										
										if($ydate==$m)
										{	
										$selected=" selected ";
										}
                                        echo "<option $selected value='$m'>$m</option>";
                                    }
                                    ?> 
                                </select>
                                </div>
                        </div>
                        <div class="control-group span6">
                            <label class="control-label" for="medium">To date</label>
                            <div class="controls">
                                    <select class="span3" name="tdate" id="tdate" style="width: 65px !important;">
                                    <option value="">Date</option>
                                    <?php
                                    for($m = 01;$m <= 31; $m++){ 
                                         $selected="";
										 if($_GET["tdate"]==$m)
										 {
											 $selected=" selected ";
										 }
										 if($ndate+1==$m)
										{
											$selected=" selected ";
										}
                                        echo "<option $selected value='$m'>$m</option>";
                                    }
                                    ?> 
                                </select>
                                <select class="span5" name="tmonth" id="tmonth" style="width: 90px !important;">
                                    <option value="">Month</option>
                                 <?php
                                    for($m = 1;$m <= 12; $m++){ 
                                        $newDate=date("Y")."-".$m."-1";
                                        $month =  date("F",strtotime($newDate));//."(".($ij+3).")";
                                        //$month =  date("F", mktime(0, 0, 0, $m)); 
                                        $selected="";if($_GET["tmonth"]==$m)
										{
										$selected=" selected ";
										}
										if($mdate==$m)
										{
											$selected=" selected ";
										}
                                        echo "<option $selected value='$m'>$month</option>";
                                    }
                                 ?> 
                                </select>
                                <select class="span4" name="tyear" id="tyear" style="width: 73px !important;">
                                    <option value="">Year</option>
                                    <?php
                                    for($m = 2013;$m <= 2050; $m++){  
                                         $selected="";if($_GET["tyear"]==$m)
										 {	 
										 $selected=" selected ";
										 }
										 if($ydate==$m)
										{
											$selected=" selected ";
										}
                                        echo "<option $selected value='$m'>$m</option>";
                                    }
                                    ?> 
                                </select>
                            </div>
                        </div>
                    </div>

                	<div class="controls controls-row"><br>
                        <button type="submit" name="total_attendance_report" style="background:#FFC224;color:black;font-weight:bold;font-size:16px;border-radius:7px;padding:5px;margin-left:55px;">TOTAL ATTENDANCE REPORT</button>
                        <br>
                    </div>
                    
				</div>
			</div>
    </div>
    </form>
	<?php
	$where=array();
	$qry=""; 

    if(isset($_GET["total_attendance_report"])){
        $where  =   "";
        $whereface = "";
		if(isset($_GET["fyear"]) && trim($_GET["fyear"])!="" && isset($_GET["fmonth"]) && trim($_GET["fmonth"])!="" && isset($_GET["fdate"]) && trim($_GET["fdate"])!="" && isset($_GET["tyear"]) && trim($_GET["tyear"])!="" && isset($_GET["tmonth"]) && trim($_GET["tmonth"])!="" && isset($_GET["tdate"]) && trim($_GET["tdate"])!=""){
			$fdate=$_GET["fyear"]."-".$_GET["fmonth"]."-".$_GET["fdate"];
			
			$tilldate = $_GET["tdate"]-1;
			
            $tdate=$_GET["tyear"]."-".$_GET["tmonth"]."-".$_GET["tdate"];
			$where.=" (date between '$fdate' and '$tdate') ";
			$whereface = " (timestamp between '$fdate' and '".$_GET["tyear"]."-".$_GET["tmonth"]."-".$_GET["tdate"]."') ";
		}

        $currentmonth = date('m');

        $total_days_month = 0;
        $totalsundays = 0;

        $start = new DateTime("$fdate");
        $end = new DateTime($_GET["tyear"]."-".$_GET["tmonth"]."-".($_GET["tdate"]+1));
        $days = $start->diff($end, true)->days;

        $totalsundays = intval($days / 7) + ($start->format('N') + $days % 7 >= 7);
        
        $Dates = getDatesFromRange($fdate, $tdate);
        
        $aryList=$db->getRows("select * from staff where school_id='".$_SESSION["admin"]["school_id"]."' and status=1 order by name");
        ?>

        <div class="row-fluid">
            <div class="span12">
    		<div class="top-bar">
                <h3><i class="icon-cog"></i> Detail</h3>
                <div style="float:right; margin-top:5px">
				<!--<input  class="btn btn-primary" type="button"  onclick="$('.table').tableExport({type:'excel',escape:'false'});" id="btnExport" value=" Export To Excel " />-->
                    <button class="btn btn-success" onclick="exportTableToExcel('tblData', 'Attendance Detail')" style="margin-left:35px;">Excel</button>
                    <button type="button" onclick="printDiv('printDiv2')" class="btn btn-primary">Print</button>
                </div>
            </div>
            <div class="well no-padding" id="printDiv2">

                <h4 style="text-align:center;color:crimson;">Date Wise Attendance Report</h4>
                <h5 style="float:right;margin:0px;margin-top:-15px;">Date: <?php echo $_GET['fdate']."-".$_GET['fmonth']."-".$_GET['fyear']." to ".$_GET['tdate']."-".$_GET['tmonth']."-".$_GET['tyear']; ?></h5>

                <table class="table" id="tblData" border="1" cellspacing="0">
                <thead>
                    <tr>
                        <th>S.No</th>
                        <th>Name</th>
                        <th>F. Name</th>
						<th>Total Working Days</th>
                        <th>Total present</th>
                        <th>Total Absent</th>
                        <th>Total Holidays</th>
                        <th>Total Leave</th>
                        <th>Total OD</th>
                    </tr>
                </thead>

                <tbody>
                <?php
                $ijk=0;
    			 foreach($aryList as $clist){ $i++; $ijk++;
                $aryPgAct["id"]=$clist['idno'];
              $totalpresent = 0;
              $totalabsent = 0;
              $totalholidays = 0;
              $totalsundays = 0;
              $late = 0;
              $early = 0;
              $hf = 0;
              $od = 0;
              $lv = 0;
                ?>
                    <tr class="grade<?php if($i%2==0)echo "C";else "U";?>">
                        <td><?php echo $ijk; ?></td>
                        <td><?php echo ucfirst($clist["name"]); ?></td>
                        <td><?php echo $clist['designation']; ?></td>
                        <?php 
                        // for($i=1; $i<= $maxDays;$i++){
                        foreach($Dates as $d){
                            // $day=date('D',strtotime($y."-".$mn."-".$i));
                            $day=date('D',strtotime($d));
                        $daycolor = "background:red;color:white;";
                        $ColorClass="absent";
                        $msg = "A";

    					$chkHoli=$db->getVal("select status from staff_holiday where school_id='".$_SESSION["admin"]["school_id"]."' and date='$d' and teacher='".$clist['idno']."'");

                if(strlen($i)==1){
                    $i='0'.$i;
                }

                $chkAtt = $db->getRow("SELECT * FROM attendance_new WHERE timestamp like  '%$d%' and teacher_id='".$clist["idno"]."' and school_id='".$_SESSION["admin"]["school_id"]."' ");

                if(strtolower($day)=="sun") {$ColorClass="danger sunday"; $msg="S"; $daycolor="background:black;color:white;"; $totalsundays++;
                    
                }
                elseif($chkHoli===1) {$ColorClass="danger holiday";  $msg="H";  $daycolor="background:	#00CED1;color:white;"; $totalholidays++;
					    }
                elseif($chkAtt['att_type']=='OD') {$msg="O"; $od++; $totalpresent++;  $daycolor="background:brown; color:white;";
					    }
                elseif($chkAtt['att_type']=='HF') {$msg="HF"; $hf++; $totalpresent++;  $daycolor="background:orange; color:white;";
					    }
                elseif($chkAtt['att_type']=='LV') {$msg="LV"; $lv++;  $daycolor="background:purple; color:white;";
					    }

				elseif( $chkAtt['att_type'] == "IN") {
    					   $totalpresent++;

                            $att_time = $db->getRow("SELECT * FROM attendance_timing WHERE date = '$d' and teacher='$clist[idno]' and school_id='".$_SESSION["admin"]["school_id"]."' ");
                            if(count($att_time)>1){

                                $attstart = strtotime("$att_time[date] $att_time[start_time]");
                                $attend   = strtotime("$att_time[date] $att_time[end_time]");
    
        					    $att_in = strtotime($chkAtt['timestamp']); 
        					    if($att_in > $attstart){$late++; $msg="L";$daycolor="background:#FFD700;color:white;";
        					    }

        					    $outtime = $db->getVal("SELECT timestamp FROM attendance_new WHERE cast(timestamp as date) = '$d' and teacher_id='".$clist["idno"]."' and att_type='OUT' and school_id='".$_SESSION["admin"]["school_id"]."' ");
            					    $att_out = strtotime($outtime); 
            					    if($att_out < $attend){$early++;
            					         $msg="E";$daycolor="background:blue;color:white;";
            					    }
                            }
                            if($msg!='L' && $msg!='E'){
                                $ColorClass="success";  $msg="P";   $daycolor="background:green;color:white;";
                            }
    					}
                        else {
                            if($msg=="A"){
            					    $totalabsent+=1;
            					}
                        }
    					?>

                        <?php } ?>
                        <td><?php echo $totalpresent+$totalabsent+$lv; ?> </td>
                        <td><?php echo $totalpresent; ?></td>
                        <td><?php echo $totalabsent; ?></td>
                        <td><?php echo $totalholidays; ?></td>
                        <!--<td><?php echo $totalsundays; ?></td>-->
                        <td><?php echo $lv; ?></td>
                        <td><?php echo $od; ?></td>
                    </tr>
                <?php } ?>
                </tbody>
               
            </table>
            </div>

        </div>
        </div>
        <?php
    }

    function getDatesFromRange($start, $end, $format = 'Y-m-d') {
          
        // Declare an empty array
        $array = array();
          
        // Variable that store the date interval
        // of period 1 day
        $interval = new DateInterval('P1D');
      
        $realEnd = new DateTime($end);
        $realEnd->add($interval);
      
        $period = new DatePeriod(new DateTime($start), $interval, $realEnd);
      
        // Use loop to store date into array
        foreach($period as $date) {                 
            $array[] = $date->format($format); 
        }
      
        // Return the array elements
        return $array;
    }

?>

	<script type="text/javascript">
	$(document).ready(function(e) {
		var oTable = $('.table').dataTable( {
			"bPaginate": false,
			"bLengthChange": false,
			"bFilter": true,
			"bSort": true,
			"bInfo": true,
			"bAutoWidth": false
		});
	});
	function activeNowMe(id){
		$.ajax({
			url: "<?php echo URL_ROOT ?>Promote/ajax.php?type=activeMe&id="+id
		}).done(function(data) {
			$("#row"+id).hide("slow");
		});
	}
	function getStudentPopup(){
		var url="";
		$(".checkboxes").each(function(){
			if($(this).prop('checked')==true){
				var idno=$(this).val();
				var name=$(".name"+idno).html()
				var left=$(".left"+idno).html()
				url+="&"+name+"`"+idno+"="+left;
			}
		})
		if(url!=""){
			getPopup("<?php echo URL_ROOT ?>Promote/?page_id=MigrateLeftFee&class=<?php echo $_GET["class"] ?>"+url,"1","MigrateLeftFee");
			$(".close").click(function() {
				$(this).parent().remove();
			});
			$(".outer").click(function() {
				$(this).remove();
			});

		}else{
			alert("select atleast one student to mgrate");
		}
	}
	
    function exportTableToExcel(tableID, filename = '',e){
    $(".myclass").css("color", "black");   
    var tableType = document.getElementById('tblData').getAttribute("data-tblname");

    var downloadLink;
    var dataType = 'application/vnd.ms-excel';
    var tableSelect = document.getElementById(tableID);
    var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');

    // Specify file name
    filename = filename?filename+'.xls':'excel_data.xls';
    
    // Create download link element
    downloadLink = document.createElement("a");
    
    document.body.appendChild(downloadLink);
    
    if(navigator.msSaveOrOpenBlob){
        var blob = new Blob(['\ufeff', tableHTML], {
            type: dataType
        });
        navigator.msSaveOrOpenBlob( blob, filename);
    }else{
        // Create a link to the file
        downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
    
        // Setting the file name
        downloadLink.download = filename;
        
        //triggering the function
        downloadLink.click();
    }
    window.location.reload();
    e.preventDefault();
    
}

	</script>
    <style>
    tfoot{display: table-footer-group !important;}
	.MigrateLeftFee{width:650px !important}
    </style>