<?php
$pgMod="time_setting";
$pgAct="view";
if(isset($_GET['action']) && trim($_GET['action'])!='')
		$pgAct=strtolower($_GET['action']);


if(isset($_POST['save_data'])){

    if($_POST['teacher'] == "ALL"){
        $allteachers = $db->getRows("select * from staff where school_id='".$_SESSION["admin"]["school_id"]."' and status='1' ");
    } else {
        $allteachers = $db->getRows("select * from staff where idno='$_POST[teacher]' and school_id='".$_SESSION["admin"]["school_id"]."' and status='1' ");
    }

    // Function call with passing the start date and end date
    $Dates = getDatesFromRange($_POST["fdate"], $_POST["tdate"]);

    foreach($allteachers as $teacher){
        
        foreach($Dates as $d){
            
            $array = array(
                "date"          =>  $d,
                "start_time"    =>  $_POST['start_time'],
                "end_time"      =>  $_POST['end_time'],
                "teacher"       =>  $teacher['idno'],
                "school_id"     =>  $_SESSION["admin"]["school_id"],
                "added_by"      =>  $_SESSION["admin"]["uid"]
            );
            
            $check = $db->getVal("select id from attendance_timing where date='$d' and teacher='$teacher[idno]' and school_id='".$_SESSION["admin"]["school_id"]."'  ");
            if($check == ""){
                $flg = $db->insertAry("attendance_timing", $array);
            } else {
                $updary = array(
                    "start_time" => $_POST["start_time"],
                    "end_time"   => $_POST["end_time"]
                    );
                $flg = $db->updateAry("attendance_timing", $updary, " where date='$d' and teacher='$teacher[idno]' and school_id='".$_SESSION["admin"]["school_id"]."' ");
            }

        }

    }

    redirect(URL_ADMIN_HOME.getQueryString(array("src"=>"Attendance", "page_id"=>$pgMod, "get_report"=>"", "fdate"=>$_POST['fdate'], "tdate"=>$_POST['tdate'], "teacher"=>$_POST['teacher'] )));
}

    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;
    }

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
}
?>

	<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>

        <div class="well no-padding">
<div class="controls controls-row">

    <form method="post" action="">
        <table border="0" cellpadding="5">
            <tr>
                <td>From Date <br> <input type="date" id="fdate" name="fdate" value="<?php if($_GET['fdate']){ echo $_GET['fdate']; } else { echo date('Y-m-d'); } ?>" required /></td>
                <td>To Date <br> <input type="date" id="tdate" name="tdate" value="<?php echo date('Y-m-d', strtotime(' + 1 days')); ?>" required /></td>
                <td>Staff <br>
                    <select name="teacher" id="teacher">
                        <option value="ALL">ALL</option>
                         <?php
            			 	$clsses=$db->getRows("select * from staff where school_id='".$_SESSION["admin"]["school_id"]."' and status=1");
                            foreach($clsses as $cla){
            					$name=$cla["name"];
            						$id=$cla["idno"];
                                echo "<option $selected value='$id'>$name</option>";
                            } 
                         ?> 
                    </select> 
                </td>
                <td>Start Time <br> <input type="time" name="start_time" value="" style="width:150px;" required /></td>
                <td>End Time <br> <input type="time" name="end_time" value="" style="width:150px;"  /></td>
                <td style="float:right;"> <br>
                    <button type="submit" name="save_data" style="float:right;background:green;padding:5px;width:70px;color:white;border:none;border-radius:5px;">Save</button>
                </td>
            </tr>
        </table>
    </form>

    <form method="get" action="">

        <input type="hidden" name="src" value="Attendance" />
        <input type="hidden" name="page_id" value="<?php echo $pgMod; ?>" />

            <button class="btn btn-primary" type="button" style="margin:20px;" onclick="window.location.href = './?src=Attendance&page_id=time_setting&get_report&fdate='+$('#fdate').val()+'&tdate='+$('#tdate').val()+'&teacher='+$('#teacher').val()">Get Report</button>

    </form>

</div>
</div>



    </div>

    <div class="well no-padding">
    <?php if(isset($_GET["add_time"])){ ?>
		<form method="post" action="">
		<div class="row-fluid">
            <div class="span12">
				<div class="well no-padding">
                	<div class="controls controls-row">

    		<input type="hidden" name="name" value="<?php echo $exam['name']; ?>" />
    		<input type="hidden" name="full_name" value="<?php echo $exam['full_name']; ?>" />
		
            <h3 style="text-align:center;"><?php echo $exam['name']; ?></h3>
            <div id="printableDiv">
            <table class="table">
			<tr>
                <th>S. No.</th>
                <th>Date</th>
                <th>Start Time</th>
                <th>End Time</th>
            </tr>
			<?php $i=0; $j = 0;
        	$month = $_GET["month"];

            $years = explode("-",$_SESSION["admin"]["session"]);

        	if($month < 4){
        	    $y = $years[1];
        	} else {
        	    $y = $years[0];
        	}

    		$mn=date('m',strtotime($y."-".$month."-1"));

    		$maxDays=date('t',strtotime($y."-".$mn."-1"));
			?>
			<input type="hidden" name="totaldays" value="<?php echo $maxDays; ?>" />
			<?php
			for($i=1; $i<=$maxDays; $i++){
                $data = $db->getRow("select * from attendance_timing where date='".$y."-".$month."-$i"."' and month='$_GET[month]' and school_id='".$_SESSION['admin']['school_id']."' ");

				?>
				<tr> 
                	<td><?php echo $i; ?></td> 
                	<td><?php echo $i."-".$month."-$y"; ?>
                    	<input type="hidden" name="date[]" value="<?php echo $y."-".$month."-$i";; ?>" />
                	</td>
            	    <td>
            	        <input type="time" name="start_time[]" value="<?php echo $data['start_time']; ?>" style="width:150px;"  />
            	    </td>
            	    <td>
            	        <input type="time" name="end_time[]" value="<?php echo $data['end_time']; ?>" style="width:150px;"  />
            	    </td>
                </tr>
				<?php $j++;
			}
			?></table>
			</div>
            <div>
				<button type="submit" name="save_time" class="btn btn-primary"> Save Time</button> 
			</div>
		</div></div></div></div>
		</form>
    <?php } 

    if(isset($_GET['get_report'])){
        $whereteacher = "";
        ?>
        <h4 style="text-align:center;color:crimson;">Attendance Timing Report</h4>
        <h5 style="float:right;">Date: <?php echo date('d-M-Y', strtotime($_GET['fdate']))." to ".date('d-M-Y', strtotime($_GET['tdate'])); ?></h5>
        <h5 style="float:left;">Staff: <?php if($_GET['teacher']!="ALL"){ echo $db->getVal("select name from staff where idno='$_GET[teacher]' and school_id='".$_SESSION['admin']['school_id']."' "); $whereteacher = " and teacher='$_GET[teacher]' "; } else { echo $_GET['teacher']; } ?></h5>

		<div class="row-fluid">
            <div class="span12">
				<div class="well no-padding">
                	<div class="controls controls-row">

            <div id="printableDiv">
                <table class="table">
        			<tr>
                        <th>S. No.</th>
                        <th>Date</th>
                        <th>Start Time</th>
                        <th>End Time</th>
                    </tr>
        			<?php $i=0; $j = 0;
                    $Dates = getDatesFromRange($_GET["fdate"], $_GET["tdate"]);
        
                    foreach($Dates as $d){ $i++;
                        $data = $db->getRow("select * from attendance_timing where date='$d' and school_id='".$_SESSION['admin']['school_id']."' $whereteacher ");
        				?>
        				<tr> 
                        	<td><?php echo $i; ?></td> 
                        	<td><?php echo date('d-m-Y', strtotime($d)); ?>
                            	<input type="hidden" name="date[]" value="<?php echo $d; ?>" />
                        	</td>
                    	    <td>
                    	        <input type="time" name="start_time[]" value="<?php echo $data['start_time']; ?>" style="width:150px;"  />
                    	    </td>
                    	    <td>
                    	        <input type="time" name="end_time[]" value="<?php echo $data['end_time']; ?>" style="width:150px;"  />
                    	    </td>
                        </tr>
        				<?php $j++;
        			}
        			?>
    			</table>
			</div>

   <!--         <div>-->
			<!--	<button type="submit" name="save_time" class="btn btn-primary"> Save Time</button> -->
			<!--</div>-->
		</div></div></div></div>

    <?php
    }
?>
	</div></div></div>
<!-- / Forms -->