<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="student_date_wise_report";
$pgAct="view";

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">
                    <h3><i class="icon-eye-open"></i> <?php echo ucwords($pgAct." ".$pgMod); ?></h3>
				</div>
				<div class="well no-padding">
                	<div class="controls controls-row">
                        <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>
                        
                      <br>  
                    <div style="float:left;">
                        
                        <select style="width: 165px !important;padding:20px;margin:15px;" name="studentclass" >
                            <option value="">--Select class--</option>
                            <?php 
                                $classes = $db->getRows("Select class from class where status=1 and school_id=1");
                               foreach($classes as $cls){
                                    $selected="";
                                    if($_GET["studentclass"]==$cls['class']){
										 $selected=" selected ";
									}
                                echo "<option $selected>$cls[class]</option>";
                               }
                            ?>
                        </select>

                        <select style="width: 165px !important;padding:20px;margin:15px;" name="studentsection" >
                            <option value="">--Select Section--</option>
                            <?php   $section = $db->getRows("Select name from section where school_id=1");
                                foreach($section as $sec){
                                    $selected="";
                                    if($_GET["studentsection"]==$sec['name']){
										 $selected=" selected ";
									}
                                    echo "<option $selected>$sec[name]</option>";
                                }
                            ?>
                        </select>

                        <button type="submit" name="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>

                    </div>
                    <br><br>

                    </div>
                    
				</div>
			</div>
    </div>
    </form>
	<?php
	$where=array();
	$qry="";
	
    if(isset($_GET["attendance_report"])){
        $where  =   "";
		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"];
			$fnewDate = date("d-M-Y", strtotime($fdate));
			$tdate=$_GET["tyear"]."-".$_GET["tmonth"]."-".$_GET["tdate"];
				$tnewDate = date("d-M-Y", strtotime($tdate));
			$where.=" (date between '$fdate' and '$tdate') ";
		}


	    if(isset($_GET["studentclass"]) && trim($_GET["studentclass"])!=""){
			$conwhere.=" where class='".$_GET["studentclass"]."' ";
		}

		if(isset($_GET["studentsection"]) && trim($_GET["studentsection"])!=""){
			$conwhere.=" AND section='".$_GET["studentsection"]."' ";
		}

        ////////////////////////// where condition for correct holiday count ////////////

        $whereHoliday  =   "";
        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"];
            $fnewDate = date("d-M-Y", strtotime($fdate));
            $tdate=$_GET["tyear"]."-".$_GET["tmonth"]."-".$_GET["tdate"];
            $tnewDate = date("d-M-Y", strtotime($tdate));

            $to_date_one_less = (new DateTime("$tdate"))->sub(new DateInterval('P1D'));
            $to_date_where = $to_date_one_less->format('Y-m-d');
            $whereHoliday.=" (date between '$fdate' and '$to_date_where') ";
// 			$conwhere1 .=" AND date = '$fdate' ";
        }

        ////////////////////////////////////////////

        $class=$_GET['studentclass'];
        $section = $_GET['studentsection'];
        $currentmonth = date('m');

        $total_days_month = 0;
        $totalsundays = 0;
        $totalholidays=0;

        $start = new DateTime("$fdate");
        $end = new DateTime("$tdate");

        $days = $start->diff($end, true)->days;

        ////////////////// 1 day substracted from end date (sunday n holiday) for correct counting ///////////////
        $end_one_day_less = (new DateTime("$tdate"))->sub(new DateInterval('P1D'));

        $days_new = $start->diff($end_one_day_less, true)->days;

        $totalsundays = intval($days_new / 7) + ($start->format('N') + $days_new % 7 >= 7);

        $holidays=$db->getRows("SELECT * FROM holiday WHERE session='".$_SESSION["admin"]["session"]."' AND $whereHoliday AND class='$class' GROUP BY id HAVING COUNT(*) >= '1' ");

        $totalholidays = count($holidays);

        $totalworkingdays= ($days - $totalsundays - $totalholidays);

        ?>

        <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 type="button" class="btn btn-primary" id="btn_excel" value="Excel" style="float:right;"/>
                    <button type="button" onclick="printDiv('printDiv2')" class="btn btn-primary">Print</button>
                </div>
                
            </div>

            <div class="well no-padding divclass" id="printDiv2">
                <input type="hidden" id="filename" value="Student Attendance Report" />
                
                <table style="width:100%;">
                    <tr>
            	         <td><img src="<?php echo $LinksDetails["logo"]; ?>" height="90px" width="110px" style="margin:0px 0px 3px 10px;"></td>
            	         <td style="text-align:center;margin-bottom:18px;padding-right:200px !important;"><h1 style="font-size:30px;margin:5px 0px 0px 0px;color: #EC1E1E;"><?php echo ucfirst($LinksDetails["site_name"]) ?></h1>
            		         <span style="font-size:16px;font-weight:800;  color: #186916;"> <?php echo ucfirst(nl2br($LinksDetails["contact_content"])) ?></span>
            	         </td>
                    </tr>
                </table>

                <table class="table" cellspacing="0">
                    <tr>
                        <td>Class  <?php echo $class; ?>-<?php echo $section; ?></td>
                        <td>Total Working Days <?php echo $totalworkingdays; ?>  </td>
                        <td style="text-align:center"><p>Attendance Report</p>  </td>
                        <td><p style="float:right">Date:<?php echo $fnewDate.' to '.$tnewDate; ?></p> </td>
                    </tr>
                </table>

                <table class="table" cellspacing="0" id="tblData" border="1">
                    <thead>
                        <tr>
                            <th>S.No</th>
                            <th>Adm 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>Present Percentage</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                             $students = $db->getRows("Select idno, name, fname, fincome, admissionno  from student $conwhere and session='".$_SESSION["admin"]["session"]."'  and status='1'  order by cast(admissionno as signed), name");

                             $i=0;
                             foreach($students as $stu){ $i++;
                             $totalabsent = $totalpresent = 0;
                            //  $result1 = $db->getRows("SELECT COUNT(attandenc.idno) as absent FROM attandenc WHERE idno='$stu[idno]' AND date >= '$fdate' and date < '$tdate' AND session='".$_SESSION["admin"]["session"]."' and type='2' ");

                            $result1 = $db->getRows("SELECT * FROM attandenc WHERE idno='$stu[idno]' AND date >= '$fdate' and date <= '$tdate' AND session='".$_SESSION["admin"]["session"]."' and type='2' ");

                            foreach($result1 as $row2){
                                
                                $checkholiday = $db->getVal("SELECT id FROM holiday WHERE session='".$_SESSION["admin"]["session"]."' AND date='$row2[date]' AND class='$class' ");
                                if($checkholiday > 0){
                                    
                                } else {
                                    $totalabsent++;
                                }
                            }
                            $totalpresent = $totalworkingdays-$totalabsent;
                        ?>
                        <tr>
                            <td><?php echo $i; ?></td>
                            <td><?php echo $stu['admissionno']; ?></td>
                            <td><?php echo $stu['name']; ?></td>
                            <td><?php echo $stu['fname']; ?></td>
                            <td><?php echo $totalworkingdays; ?></td>
                            <td><?php echo $totalpresent; ?></td>
                            <td><?php echo $totalabsent; ?></td>
                            <td><?php echo $totalholidays; ?></td>
                            <td><?php echo number_format(($totalpresent/$totalworkingdays)*100,2); ?> %</td>
                        </tr>
                        <?php } ?>
                    </tbody>

                </table>
                <style>
                    @media print {
                        .headPrint {display:none !important;}
                    }
                </style>
		    </div>

        </div>

        </div>
        <?php
    }

?>

	<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){
    
    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();
    }
    e.preventDefault();
}

    $("#btn_excel").click(function(e) {
            var filename = $("#filename").val();
            $(".newtable").hide();
        let file = new Blob([$('.divclass').html()], {type:"application/vnd.ms-excel"});
        let url = URL.createObjectURL(file);
        let a = $("<a />", {
        href: url,
        download: filename+".xls"}).appendTo("body").get(0).click();
        e.preventDefault();
    });
    
	</script>
    <style>
    tfoot{display: table-footer-group !important;}
	.MigrateLeftFee{width:650px !important}
    </style>