<?php
if(isset($_POST["fee"])){
	//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_extra","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, 
			                "class"     =>  $_GET["class"],
							"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_extra",$newExam); 
			$i++;
		}
	}
	//print_r($_POST);echo "</pre><hr/>";
	redirect();
}


define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');
					/** Include PHPExcel */
				require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
				$objPHPExcel = new PHPExcel();
if($_POST){
	$mysqlImportFilename ='';
	if(isset($_FILES["photo"]["name"]) && !empty($_FILES["photo"]["name"])){
		$lfilename = basename($_FILES['photo']['name']);
		$lext = strtolower(substr($lfilename, strrpos($lfilename, '.')+1));
		if(in_array($lext,array('xls'))||in_array($lext,array('xlsx')))
		{
			$lnewfile=md5(microtime()).".".$lext;
			if(move_uploaded_file($_FILES['photo']['tmp_name'],"media/".$lnewfile))
			{
				// Read in entire file
				$file = "media/".$lnewfile;$ij=0;
				// Loop through each line
				if (($handle = fopen($file, "r")) !== FALSE) { 
					
					try { $objPHPExcel = PHPExcel_IOFactory::load($file); } 
					catch(Exception $e) { die('Error loading file "'.pathinfo($file,PATHINFO_BASENAME).'": '.$e->getMessage()); }
					 
						$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
					    $arrayCount = count($allDataInSheet); // Here get total count of row in that sheet
				// 	 $allsubject=$db->getRows("select * from subject where class='".$allDataInSheet[2]["D"]."' and school_id='".$_SESSION["admin"]["school_id"]."' and session='".$_SESSION["admin"]["session"]."' order by id");
					 //print_r($allsubject);exit;

                    $checksection = $db->getVal("select count(section) from subject_extra where class='".$allDataInSheet[2]["D"]."' and section!='' and school_id='".$_SESSION["admin"]["school_id"]."' and session='".$_SESSION["admin"]["session"]."' ");
                        $wheresection = '';
                        if($checksection > 0){
                            $wheresection = " and section='".$allDataInSheet[2]["E"]."' ";
                        }

                    $allsubject=$db->getRows("select * from subject_extra where class='".$allDataInSheet[2]["D"]."' $wheresection and school_id='".$_SESSION["admin"]["school_id"]."' and session='".$_SESSION["admin"]["session"]."' order by id");

					for($i=2;$i<=$arrayCount;$i++){
						$idno=trim($allDataInSheet[$i]["A"]);
						$type=trim($allDataInSheet[$i]["F"]);
						$newExam=array(
										"idno"=>trim($allDataInSheet[$i]["A"]),
										"class"=>trim($allDataInSheet[$i]["D"]),
										"type"=>trim($allDataInSheet[$i]["F"]),
								// 		"total"=>trim($allDataInSheet[$i]["H"]),
										"status"=>1,
										"school_id"=>$_SESSION["admin"]["school_id"],
										"added_by"=>$_SESSION["admin"]["uid"],
										"session"=>$_SESSION["admin"]["session"]
						);
						$totalcolumn = "G";
						$obtaincolumn = "H";
						foreach($allsubject as $sub){
							$newExam['subject'] =   trim($allDataInSheet[1][''.$obtaincolumn.'']);
							$newExam['total']   =   trim($allDataInSheet[$i][''.$totalcolumn.'']);
							$newExam['obtain']  =   trim($allDataInSheet[$i][''.$obtaincolumn.'']);
				// 			print_r($newExam);echo  EOL;
							$db->delete("exammarks_extra","where school_id='".$_SESSION["admin"]["school_id"]."' and idno=".$idno." and type='".$type."' and subject='".$newExam["subject"]."' and session='".$_SESSION["admin"]["session"]."'");
							if($newExam['obtain'] == "NA" || $newExam['obtain']=="AB"){
							    
							}
							elseif($newExam['obtain']>$newExam['total']){
								$_SESSION["msg"].="Marks of subject:-".$newExam['subject']." of row-".$i." should not be more than total makrs..!".EOL;
								$newExam["obtain"]=0;
							}
							elseif($newExam["obtain"]==""){
							    $newExam["obtain"]=0;
							}
								print_r($newExam);
								echo "<br>";
							$db->insertAry("exammarks_extra",$newExam);

						 	  $totalcolumn++;  $totalcolumn++;
						 	  $obtaincolumn++; $obtaincolumn++;
						   }
					}
					fclose($handle);
				}else{
					echo "File error ".$handle ;
				}
				
                unlink("media/".$lnewfile);				
				
				$_SESSION['msg'] = "Marks imported successfully";
				//////////////////////////**************setting backup table***********////////////////////////////
				if($db->getErMsg()=="")
				redirect("?src=ExamCBSE&page_id=extra_marks");
				else
				$alert_err[] = $db->getErMsg();
				
			}
		}else{
			$alert_err[]="Invalid file extension";
		}
	}
	
}
?>
<script type="text/javascript" src="https://unpkg.com/xlsx@0.15.1/dist/xlsx.full.min.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;} 
</style>
<?php
$pgMod="extra_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="ExamCBSE" />
    <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="add_marks" 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="import_file" class="btn btn-primary"> Import 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">
                            <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 examname ");
                                        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["add_marks"])){
		?><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"]."' ";

		$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 ");

        $checksection = $db->getVal("select count(section) from subject_extra where class='$_GET[class]' and section!='' and session='".$_SESSION["admin"]["session"]."' ");
        $wheresection = '';
        if($checksection > 0){
            $wheresection = " and section='$_GET[section]' ";
        }

		$allsubject=$db->getRows("select * from subject_extra $whereM1 $wheresection 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"]."' and class='$_GET[class]' and section='$_GET[section]' and subject='$sub[subject]' and session='".$_SESSION["admin"]["session"]."' "); ?>

                    <?php 
					if(is_array($allsubject) && count($allsubject)>0){
						foreach($allsubject as $sub){
						    
						    $total=$db->getVal("select total from extra_examterm where school_id='".$_SESSION["admin"]["school_id"]."' and name='".$_GET["term"]."' and class='$_GET[class]' $wheresection and subject='$sub[subject]' and session='".$_SESSION["admin"]["session"]."' ");
						    
							?><td>
                            <?php 
							$examResultData=$db->getRow("select * from exammarks_extra where school_id='".$_SESSION["admin"]["school_id"]."' and idno='".$stu["idno"]."' and type='".$_GET["term"]."' and subject='".$sub["subject"]."'");
							?>
		                    <input type="hidden" name="total" id="total" value="<?php echo $total?>" />
                            <?php echo $total; ?>/
                            <input required type="text" style="width:70px" name="student[]" onchange="validateme(<?php echo $total; ?>, 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["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"])){

		?><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 class="btn btn-danger" onclick="ExportToExcel('xlsx')">Export Excel</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"]."' ";

		$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 LENGTH(fincome), fincome ");

        $checksection = $db->getVal("select count(section) from subject_extra where class='$_GET[class]' and section!='' and session='".$_SESSION["admin"]["session"]."' ");
        $wheresection = '';
        if($checksection > 0){
            $wheresection = " and section='$_GET[section]' ";
        }
        $allsubject=$db->getRows("select * from subject_extra where school_id='".$_SESSION["admin"]["school_id"]."' and class='".$_GET["class"]."' $wheresection  and session='".$_SESSION["admin"]["session"]."' order by id");

		if(is_array($allstudent) && count($allstudent)>0){
			?>
            <div id="printableDiv">
            
            	<div class="headPrint hide" style="border: none;">
			 
			  
			 <div style="margin-left:55px"> <img src="<?php echo $LinksDetails["logo"] ?>" height="90px" width="110px" style="margin:0px 0px 3px 10px;"></div>
			 <div style="float:left;text-align:center;margin-bottom:18px;"> <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>
			 </div> 
		  </div>


            <table class="table" cellspacing="0" cellpadding="0" border="1" id="tbl_exporttable_to_xls">
                <thead>
        			<tr>
                    <th style="border-left:2px solid black;border-top:2px solid black;border-bottom:2px solid black;border-right:2px solid black;">idno</th>
                    <th style="border-left:2px solid black;border-top:2px solid black;border-bottom:2px solid black;border-right:2px solid black;">name</th>
                    <th style="border-left:2px solid black;border-top:2px solid black;border-bottom:2px solid black;border-right:2px solid black;">fname</th>
                    <th style="border-left:2px solid black;border-top:2px solid black;border-bottom:2px solid black;border-right:2px solid black;">class</th>
                    <th style="border-left:2px solid black;border-top:2px solid black;border-bottom:2px solid black;border-right:2px solid black;">section</th>
                    <th style="border-left:2px solid black;border-top:2px solid black;border-bottom:2px solid black;border-right:2px solid black;">term</th>
                    <?php
        			if(is_array($allsubject) && count($allsubject)>0){
        				foreach($allsubject as $sub){
        					?>
        					<th style="border-left:2px solid black;border-top:2px solid black;border-bottom:2px solid black;border-right:2px solid black;">Total</th>
        					<th style="border-left:2px solid black;border-top:2px solid black;border-bottom:2px solid black;border-right:2px solid black;"><?php echo $sub["subject"]; ?></th><?php
        				}
        			}?>
                    </tr>
                </thead>
			<?php $i=0;
			foreach($allstudent as $stu){$i++;
				?>
				<tr>
                	<td style="border-left:2px solid black;border-top:2px solid black;border-bottom:2px solid black;border-right:2px solid black;"><?php echo $stu["idno"]; ?></td>
                	<td style="border-left:2px solid black;border-top:2px solid black;border-bottom:2px solid black;border-right:2px solid black;"><?php echo $stu["name"]; ?></td>	
                	<td style="border-left:2px solid black;border-top:2px solid black;border-bottom:2px solid black;border-right:2px solid black;"><?php echo $stu["fname"]; ?></td>
                	<td style="border-left:2px solid black;border-top:2px solid black;border-bottom:2px solid black;border-right:2px solid black;"><?php echo $stu["class"]; ?></td>
                	<td style="border-left:2px solid black;border-top:2px solid black;border-bottom:2px solid black;border-right:2px solid black;"><?php echo $stu["section"]; ?></td>
                	<td style="border-left:2px solid black;border-top:2px solid black;border-bottom:2px solid black;border-right:2px solid black;"><?php echo $_GET["term"]; ?></td>
                    <?php
					if(is_array($allsubject) && count($allsubject)>0){
						foreach($allsubject as $sub){
						    $total=$db->getVal("select total from extra_examterm where school_id='".$_SESSION["admin"]["school_id"]."' and name='".$_GET["term"]."' and class='$_GET[class]' $wheresection and subject='$sub[subject]' and session='".$_SESSION["admin"]["session"]."' ");
							?>
							<td style="border-left:2px solid black;border-top:2px solid black;border-bottom:2px solid black;border-right:2px solid black;"><?php echo $total; ?></td>
							<td style="border-left:2px solid black;border-top:2px solid black;border-bottom:2px solid black;border-right:2px solid black;"></td>
							<?php
						}
					}?>
                </tr>
				<?php
			}
			?></table>
			</div>
			<?php
		}
		?></div></div></div></div></form><?php
	
	}
	
	elseif(isset($_GET["import_file"])){
	    ?>
    	    <div class="row-fluid">
            <form method="post" action="" enctype="multipart/form-data">
    			<div class="span12">
    				<div class="top-bar">
    					<h3><i class="icon-cog"></i> Import File</h3> 
    				</div>

    				<div class="well no-padding">
    						<input type="hidden" name="ss" value="1">
                            <div class="control-group">
    							<label class="control-label" for="msg">CSV File</label>
    							<div class="controls">
                               		<input type="file" id="file" name="photo" class="input-block-level">
    							</div>
    						</div>
    						<div class="form-actions">
    							<button type="submit" class="btn-classic"> Import</button>
    						</div>
    				</div>
    			</div>
            </form>
    	</div>
	    <?php
	}
	
	echo $db->getErMsg();
?>
<script type="text/javascript">
 
$(document).ready(function(){ 
	/*$("student").change(function() {
		var v=this.val();
		alert(v);
		});*/
});
    function validateme(total, a){

    	var v=parseInt(a.value);
    // 	var t=$('#total').val();
        var t=total;
    	var c=(a.value);

        if(c==='AB' || c==='NA' || (!isNaN(v) && v<=t) ){
            
        }
        else if(v>t){
        	alert("Please enter correct marks");
        	a.value='';
        }
        else {
            alert("Please enter only AB or NA");
            a.value='';
        }

    }


    function ExportToExcel(type, fn, dl) {
        var elt = document.getElementById('tbl_exporttable_to_xls');
        var wb = XLSX.utils.table_to_book(elt, { sheet: "sheet1" });
        return dl ?
            XLSX.write(wb, { bookType: type, bookSST: true, type: 'base64' }) :
            XLSX.writeFile(wb, fn || ('Extra Exam Marks.' + (type || 'xlsx')));
    }

</script>