<?php
if($_POST){

	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_mp","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_mp",$newExam);
			$i++;
		}
	}

	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="src" value="Exam" />
    <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>
                         <button type="submit" name="create_file_extra" class="btn btn-primary"> Create Excel file for Extra Subjects</button>
                         <button type="submit" name="create_file_subhead" class="btn btn-primary"> Create Excel file for Extra Sub Heads</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 onchange="getType(this.value)" 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"]==$aryForm["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"]==$aryForm["section"])echo 'selected';?> value="<?php echo $cla["name"] ?>">
                            <?php echo $cla["name"] ?>
                        </option>
                        <?php
            
                    }
                ?>
            </select>
                            </div>
                        </div>  
                        <div class="control-group span4">   
                                <span id="extype">
                                <select name="type" class="span6">
                                	<option value="">Exam type</option>
                                </select>
                                </span>
                           </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>-->
                     <h3> <i class="icon-cog"></i> <?php if(isset($_GET['type']) && $_GET['type']!="") echo ucwords($_GET['type']); ?>  </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"]."' ";
		*/	
		$whereC["school_id"]=$_SESSION["admin"]["school_id"];
		$whereC["session"]=$_SESSION["admin"]["session"];
					
			$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 order by name ");
		$allsubject=$db->getRows("select * from subject_mp $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){
			?><table class="table">
			<tr>
            <td>S.No</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 $ij=0;
			foreach($allstudent as $stu){$ij++;
				?>
				<tr>
                	<td><?php echo $ij; ?></td>
                	<td><?php echo $stu["name"] ?></td>
                    <?php 
					if(is_array($allsubject) && count($allsubject)>0){
						foreach($allsubject as $sub){
							?><td>
                            <?php 
							$examResultData=$db->getRow("select * from exammarks_mp where school_id='".$_SESSION["admin"]["school_id"]."' and idno='".$stu["idno"]."' and type='".$_GET["type"]."' and subject='".$sub["subject"]."'");
							?>
                            <?php $total=$db->getVal("select total from examtype where school_id='".$_SESSION["admin"]["school_id"]."' and class='".$_GET["class"]."' and  subject='".$sub["subject"]."' and type='".$_GET["type"]."'"); ?>
                            <?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
							 $detail=array("idno"=>$stu["idno"],
							 				"subject"=>$sub["subject"],
											"term"=>$_GET["type"],
											"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><?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["type"]==""){
			echo "Please select term of exam..!";exit;
		}
		else{
			//$total=$db->getVal("Select total from examtype 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_mp $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', 'fname')
						->setCellValue('D1', 'class')
						->setCellValue('E1', 'section')
						->setCellValue('F1', 'term');
			$i=1;
			foreach($allstudent as $student){$i++;
				$objPHPExcel->setActiveSheetIndex(0)
							->setCellValue('A'.$i.'', ''.$student["idno"].'')
							->setCellValue('B'.$i.'', ''.$student["name"].'')
							->setCellValue('C'.$i.'', ''.$student["fname"].'')
							->setCellValue('D'.$i.'', ''.$student["class"].'')
							->setCellValue('E'.$i.'', ''.$student["section"].'')
							->setCellValue('F'.$i.'', ''.$_GET["type"].'');
			}$alpha="F";
			foreach($allsubject as $sub){$alpha++;
				$total=$db->getVal("Select total from examtype where type='".$_GET['type']."' and subject='".$sub["subject"]."' and class='".$student["class"]."' and school_id='".$_SESSION["admin"]["school_id"]."' and session='".$_SESSION["admin"]["session"]."'");
				 //echo $db->getLastQuery();exit;
				$objPHPExcel->setActiveSheetIndex(0)
							->setCellValue(''.$alpha.'1', ''.$sub["subject"].','.$total.'');
			}
			//$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['type'].".xls";
			$objWriter->save($root);
			
			echo 'Files have been created in ' , $root , EOL;
			
			
		}
	}
	elseif(isset($_GET["create_file_extra"])){
		
		$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["type"]==""){
			echo "Please select term of exam..!";exit;
		}
				
		$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_extra_mp $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', 'fname')
						->setCellValue('D1', 'class')
						->setCellValue('E1', 'section')
						->setCellValue('F1', 'term');
			$i=1;
			foreach($allstudent as $student){$i++;
				$objPHPExcel->setActiveSheetIndex(0)
							->setCellValue('A'.$i.'', ''.$student["idno"].'')
							->setCellValue('B'.$i.'', ''.$student["name"].'')
							->setCellValue('C'.$i.'', ''.$student["fname"].'')
							->setCellValue('D'.$i.'', ''.$student["class"].'')
							->setCellValue('E'.$i.'', ''.$student["section"].'')
							->setCellValue('F'.$i.'', ''.$_GET["type"].'');
			}$alpha="F";
			foreach($allsubject as $sub){$alpha++;
				
				$objPHPExcel->setActiveSheetIndex(0)
							->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\sub_ext_".$_GET['class']."_".$_GET['section']."_".$_GET['type'].".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";*/
			
		}
	}
	elseif(isset($_GET["create_file_subhead"])){
		
		$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["type"]=="" || $_GET["type"]!="ANNUAL"){
			echo "Please select final term of exam..!";exit;
		}
				
		$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 extra_head_detail_mp $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', 'fname')
						->setCellValue('D1', 'class')
						->setCellValue('E1', 'section')
						->setCellValue('F1', 'term');
			$i=1;
			foreach($allstudent as $student){$i++;
				$objPHPExcel->setActiveSheetIndex(0)
							->setCellValue('A'.$i.'', ''.$student["idno"].'')
							->setCellValue('B'.$i.'', ''.$student["name"].'')
							->setCellValue('C'.$i.'', ''.$student["fname"].'')
							->setCellValue('D'.$i.'', ''.$student["class"].'')
							->setCellValue('E'.$i.'', ''.$student["section"].'')
							->setCellValue('F'.$i.'', ''.$_GET["type"].'');
			}$alpha="F";
			foreach($allsubject as $sub){$alpha++;
				
				$objPHPExcel->setActiveSheetIndex(0)
							->setCellValue(''.$alpha.'1',''.$sub["head"].','.$sub["subject"].'');
				}
			//$objPHPExcel->getActiveSheet()->setTitle('marks123');
			//echo "obj".$objPHPExcel;
			$objPHPExcel->setActiveSheetIndex(0);
            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
			//echo $root=getcwd()."\\extrahead_detail_".$_GET['class']."_".$_GET['section']."_".$_GET['type'].".xls";
			$root="D:\marks_excel\\extrahead_detail_".$_GET['class']."_".$_GET['section']."_".$_GET['type'].".xls";
			//echo $root;
			$objWriter->save($root);
			
			echo 'Files have been created in ' , $root , EOL;			
		}
	}
	echo $db->getErMsg();
?><script>
function getType(id){
	$.post( "Exam/ajax.php", { type: "exmtype" ,class: id } , function( data ) {
	  	$("#extype").html(data);
	});
}


$(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 c=(a.value);
	//alert(c);
//	var r=$(this).val();
if(c!='AB' && isNaN(v))
{
alert("Please enter only AB");
a.value='';	
}
else if(v>t){
		alert("Please enter correct marks");
		//return false;
		a.value='';
	}
	//else if(c!='A'){
		
		//a.value='';
	//}
	
		
	//alert(r);
}

</script>