<?php
//echo "<pre>";print_r($_SERVER);exit;
if($_POST){
	//echo "<pre>";
	if(is_array($_POST["student"]) && count($_POST["student"])>0){
		$i=0;
		foreach($_POST["student"] as $stu){
			$detail=json_decode(base64_decode($_POST["detail"][$i]),true);
			$db->delete("exammarks","where school_id='".$_SESSION["admin"]["school_id"]."' and idno=".$detail["idno"]." and type='".$detail["term"]."' and subject='".$detail["subject"]."' and session='".$_SESSION["admin"]["session"]."'");
			$newExam=array("obtain"=>$stu,
							"idno"=>$detail["idno"],
							"subject"=>$detail["subject"],
							"type"=>$detail["term"],
							"total"=>$detail["total"],
							"school_id"=>$_SESSION["admin"]["school_id"],"added_by"=>$_SESSION["admin"]["uid"],
							"session"=>$_SESSION["admin"]["session"]
			);
			$db->insertAry("exammarks",$newExam);
			$i++;
		}
	}
	//print_r($_POST);echo "</pre><hr/>";
	redirect();
}
?>

<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;} 
</style>
<?php
$pgMod="marks";
$pgAct="view";
if(isset($_GET['action']) && trim($_GET['action'])!='')
		$pgAct=strtolower($_GET['action']);

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="page_id" value="<?php echo $pgMod; ?>" />
	<div class="row-fluid">
            <div class="span12">
            	<div class="top-bar">
					<h3><i class="icon-cog"></i>Search Student Record</h3>
                    <div>
						<button type="submit" name="fee" class="btn btn-primary"> Add Marks</button>
                        <button type="submit" name="create_file" class="btn btn-primary"> Create Excel file</button>
                        
					</div>
				</div>
				<div class="well no-padding">
                	<div class="controls controls-row">
                        
                        <div class="control-group span4">
                            <label class="control-label" for="class">Class</label>
                            <div class="controls">
                                <select name="class" id="class">
                                    <option value="">Class</option>
                                    <?php 
                                        $class=$db->getRows("select * from class where school_id='".$_SESSION["admin"]["school_id"]."' ");
                                        foreach($class as $cla){
                                            ?>
                                            <option <?php if($cla["class"]==$_GET["class"])echo 'selected';?> value="<?php echo $cla["class"] ?>">
                                                <?php echo $cla["class"] ?>
                                            </option>
                                            <?php
                                        }
                                    ?>
                                </select>
                            </div>
                        </div>
                        <div class="control-group span4">
                            <label class="control-label" for="class">Section</label>
                            <div class="controls">
                               <select name="section" id="section" >
                <option value="">Section</option>
                <?php 
                    $class=$db->getRows("select * from section where school_id='".$_SESSION["admin"]["school_id"]."'");
                    foreach($class as $cla){
                        ?>
                        <option <?php if($cla["name"]==$_GET["section"])echo 'selected';?> value="<?php echo $cla["name"] ?>">
                            <?php echo $cla["name"] ?>
                        </option>
                        <?php
            
                    }
                ?>
            </select>
                            </div>
                        </div>
                        <div class="control-group span4 hide">
                            <label class="control-label" for="medium">Medium</label>
                            <div class="controls">
                                <select name="medium" id="medium">
                                    <option <?php if("hindi"==$aryForm["sibling"])echo 'selected';?> value="hindi">Hindi</option>
                                    <option <?php if("english"==$aryForm["sibling"])echo 'selected';?> value="english">English</option>
                                </select>
                            </div>
                        </div>
                        <div class="control-group span4">
                            <label class="control-label" for="term">Term</label>
                            <div class="controls">
                                <select name="term" id="term">
                                    <option value="">Term</option>
                                    <?php 
                                        $class=$db->getRows("select * from examterm where school_id='".$_SESSION["admin"]["school_id"]."'");
                                        foreach($class as $cla){
                                            ?>
                                            <option <?php if($cla["name"]==$_GET["term"])echo 'selected';?> value="<?php echo $cla["name"] ?>">
                                                <?php echo $cla["name"] ?>
                                            </option>
                                            <?php
                                        }
                                    ?>
                                </select>
                                <?php
									//echo $db->getLastQuery();
								?>
                            </div>
                        </div>
                    </div>
                    <br>
				</div>
				<!-- / Forms: Content -->
			</div>
    </div>
    </form>
	<?php
	$where=array();
	$qry="";
	if(isset($_GET["fee"])){
		?><form method="post" action="">
		<div class="row-fluid">
            <div class="span12">
            	<div class="top-bar">
					<h3><i class="icon-cog"></i>Add Result of students</h3>
                    <div>
						<button type="submit" name="fee" class="btn btn-primary"> Save Marks</button>
                         <button type="button" name="fee" onClick="printDivNoHeader('printableDiv')" class="btn btn-primary"> Print</button>
					</div>
				</div>
				<div class="well no-padding">
                	<div class="controls controls-row">
		
		<?php
		$whereC=array();
		if(isset($_GET["class"]) && $_GET["class"]!="")
			$whereC[]=" class='".$_GET["class"]."' ";
		
		/*if(isset($_GET["medium"]) && $_GET["medium"]!="")
			$whereC[]=" medium='".$_GET["medium"]."' ";
		*/	
		$whereM="";$whereM1="";
		if(is_array($whereC) && count($whereC)>0)
			$whereM1=" where ".implode(" and ",$whereC);
		
		if(isset($_GET["section"]) && $_GET["section"]!="")
			$whereC[]=" section='".$_GET["section"]."' ";
		if(is_array($whereC) && count($whereC)>0)
			$whereM=" where ".implode(" and ",$whereC);
		
		$allstudent=$db->getRows("select * from student $whereM and school_id='".$_SESSION["admin"]["school_id"]."' and session='".$_SESSION["admin"]["session"]."' and issue_TC=0 and status=1 order by name ");
		$allsubject=$db->getRows("select * from subject $whereM1 and school_id='".$_SESSION["admin"]["school_id"]."' and session='".$_SESSION["admin"]["session"]."' order by id");
		//echo $db->getLastQuery();
		if(is_array($allstudent) && count($allstudent)>0){
			?>
            <div id="printableDiv">
            <table class="table">
			<tr>
            <td>SNo.</td>
            <td>Student</td>
            <?php 
			if(is_array($allsubject) && count($allsubject)>0){
				foreach($allsubject as $sub){
					?><td><?php echo $sub["subject"] ?></td><?php
				}
			}?>
            </tr>
			<?php $i=0;
			foreach($allstudent as $stu){$i++;
				?>
				<tr> 
                	<td><?php echo $i; ?></td>	
                	<td><?php echo $stu["name"]."(".$stu["fname"].")" ?></td>
                    <?php $total=$db->getVal("select total from examterm where school_id='".$_SESSION["admin"]["school_id"]."' and name='".$_GET["term"]."'"); ?>
                    <input type="hidden" name="total" id="total" value="<?php echo $total?>" />
                    <?php 
					if(is_array($allsubject) && count($allsubject)>0){
						foreach($allsubject as $sub){
							?><td>
                            <?php 
							$examResultData=$db->getRow("select * from exammarks where school_id='".$_SESSION["admin"]["school_id"]."' and idno='".$stu["idno"]."' and type='".$_GET["term"]."' and subject='".$sub["subject"]."'");
							?>
                            <?php echo $total; ?>/
                            <input required type="text" style="width:70px" name="student[]" onchange="validateme(this)" class="onlyZero obtain <?php echo $_GET["term"];?>_obtain_marks" value="<?php if($examResultData["obtain"]!="") echo $examResultData["obtain"]; else echo "0"; ?>" placeholder="Obtain Maks" />
                             (<?php echo FindGrade($examResultData["obtain"],$total); ?>)
                             
                             <?php
							 $detail=array("idno"=>$stu["idno"],
							 				"subject"=>$sub["subject"],
											"term"=>$_GET["term"],
											"total"=>$total,
											"class"=>$_GET["class"]
											);
							$data=base64_encode(json_encode($detail));
							 ?>
                             <input type="hidden" name="detail[]" value="<?php echo $data ?>" />
                             
                            </td><?php
							
						}
					}?>
                </tr>
				<?php
			}
			?></table>
			</div>
			<?php
		}
		?></div></div></div></div></form><?php
	}
	elseif(isset($_GET["create_file"])){
		
		$whereC=array();
		if(isset($_GET["class"]) && $_GET["class"]!="")
			$whereC[]=" class='".$_GET["class"]."' ";
		
		/*if(isset($_GET["medium"]) && $_GET["medium"]!="")
			$whereC[]=" medium='".$_GET["medium"]."' ";
		*/	
		$whereM="";$whereM1="";
		if(is_array($whereC) && count($whereC)>0)
			$whereM1=" where ".implode(" and ",$whereC);
		
		if(isset($_GET["section"]) && $_GET["section"]!="")
			$whereC[]=" section='".$_GET["section"]."' ";
		if(is_array($whereC) && count($whereC)>0)
			$whereM=" where ".implode(" and ",$whereC);
			
		if($_GET["term"]==""){
			echo "Please select term of exam..!";exit;
		}
		else{
			$total=$db->getVal("Select total from examterm where name='".$_GET['term']."'");
		}
		
		$allstudent=$db->getRows("select * from student $whereM and school_id='".$_SESSION["admin"]["school_id"]."' and session='".$_SESSION["admin"]["session"]."' and issue_TC=0 and status=1 order by name ");
		$allsubject=$db->getRows("select * from subject $whereM1 and school_id='".$_SESSION["admin"]["school_id"]."' and session='".$_SESSION["admin"]["session"]."' order by id");
		//echo $db->getLastQuery();
		if(is_array($allstudent) && count($allstudent)>0){
			define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');
					/** Include PHPExcel */
			require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
			$objPHPExcel = new PHPExcel();
			$objPHPExcel->setActiveSheetIndex(0)
						->setCellValue('A1', 'idno')
						->setCellValue('B1', 'name')
						->setCellValue('C1', 'foccupation')
						->setCellValue('D1', 'class')
						->setCellValue('E1', 'section')
						->setCellValue('F1', 'term')
						->setCellValue('G1', 'total');
			$i=1;
			foreach($allstudent as $student){$i++;
				$objPHPExcel->setActiveSheetIndex(0)
							->setCellValue('A'.$i.'', ''.$student["idno"].'')
							->setCellValue('B'.$i.'', ''.$student["name"].'')
							->setCellValue('C'.$i.'', ''.$student["foccupation"].'')
							->setCellValue('D'.$i.'', ''.$student["class"].'')
							->setCellValue('E'.$i.'', ''.$student["section"].'')
							->setCellValue('F'.$i.'', ''.$_GET["term"].'')
							->setCellValue('G'.$i.'', ''.$total.'');
			}$alpha="G";
			foreach($allsubject as $sub){$alpha++;
				$objPHPExcel->setActiveSheetIndex(0)
							->setCellValue(''.$alpha.'1', ''.$sub["subject"].'')
							->setCellValue(''.$alpha.'1', ''.$sub["subject"].'')
							->setCellValue(''.$alpha.'1', ''.$sub["subject"].'');
			}
			//$objPHPExcel->getActiveSheet()->setTitle('marks123');
			$objPHPExcel->setActiveSheetIndex(0);
            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
			//echo $root=getcwd()."\\files\marks_".$_GET['class']."_".$_GET['section']."_".$_GET['term'].".xls";
			$root="D:\marks_excel\marks_".$_GET['class']."_".$_GET['section']."_".$_GET['term'].".xls";
			$objWriter->save($root);
			
			echo 'Files have been created in ' , $root , EOL;
			/*$callEndTime = microtime(true);
			$callTime = $callEndTime - $callStartTime;
			
			echo date('H:i:s') , " File written to " , str_replace('.php', '.xls', pathinfo(__FILE__, PATHINFO_BASENAME)) , EOL;
			echo 'Call time to write Workbook was ' , sprintf('%.4f',$callTime) , " seconds" , EOL;
			// Echo memory usage
			echo date('H:i:s') , ' Current memory usage: ' , (memory_get_usage(true) / 1024 / 1024) , " MB" , EOL;
			
			
			// Echo memory peak usage
			echo date('H:i:s') , " Peak memory usage: " , (memory_get_peak_usage(true) / 1024 / 1024) , " MB" , EOL;
			
			// Echo done
			echo date('H:i:s') , " Done writing files" , EOL;
			echo __FILE__ , EOL;*/
			

			/*header("Content-Type: application/vnd.ms-excel");
			$filename=$_GET['class']."marks_file.xlsx";
			header("Content-disposition: attachment; filename=".$filename."");
			
			echo 'idno' . "\t" . 'name' . "\t" . 'fname' . "\n";
			foreach($allstudent as $student)
			echo ''.$student["idno"].'' . "\t" . ''.$student["name"].'' . "\t" . ''.$student["fname"].'' . "\n";*/
			
		}
	}
	
	echo $db->getErMsg();
?>
<script type="text/javascript">

$(document).ready(function(){
	/*$("student").change(function() {
		var v=this.val();
		alert(v);
		});*/
});
function validateme(a){
	var v=parseInt(a.value);
	var t=$('#total').val();
//	var r=$(this).val();
	if(v>t){
		alert("Please enter correct marks");
		//return false;
		a.value='';
	}
	else if(isNaN(v)){
		alert("Please enter only number");
		a.value='';
	}
	//alert(r);
}
</script>