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


 div.divclass {
        margin: 4px, 4px;
        padding: 4px;
        /*background-color: #08c708;*/
        width: 100%;
        overflow-x: auto;
        overflow-y: hidden;
        white-space: nowrap;
    }
</style>

<?php
$pgMod="cummulative";
$pgAct="view";
if(isset($_GET['action']) && trim($_GET['action'])!='')
    $pgAct=strtolower($_GET['action']);
?>
    <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="button" onclick="printDiv('printDiv2')" class="btn btn-primary">Print</button>
                        <input type="button" class="btn btn-primary" id="btn_excel" value="Excel" />
                        <button type="submit" name="search" class="btn btn-primary">Search</button>
      <!--                  <button type="submit" name="marks" class="btn btn-primary">Cross List</button>-->
						<!--<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=""> -- Select Term -- </option>
                                     <option value="Term1" <?php if($_GET["term"]=="Term1")echo 'selected';?>>Term1</option>
                                    <option value="Term2" <?php if($_GET["term"]=="Term2")echo 'selected';?>>Term2</option>
                                    <option value="Final" <?php if($_GET["term"]=="Final")echo 'selected';?>>Final</option>
                                </select>
                                <?php
									//echo $db->getLastQuery();
								?>
                            </div>
                        </div>
                    </div>
                    <br>
				</div>
				
			</div>
    </div>
    </form>
	<?php
	$where = array();
	$qry="";

    if(isset($_GET["search"])){

        $checksection = $db->getVal("select count(section) from subject where class='$_GET[class]' and section!='' and session='".$_SESSION["admin"]["session"]."' ");

        $wheresection = '';
        if($checksection > 0){
            $wheresection = " and section='$_GET[section]' ";
        }

        $section = "";
        if($_GET['section']!=""){
            $section = " and section='$_GET[section]' ";
        }

    	$allStudent = $db->getRows("select * from student where school_id='".$_SESSION["admin"]["school_id"]."' and session='".$_SESSION["admin"]["session"]."' and class='".$_GET["class"]."' $section and status=1 and issue_TC=0 order by name, cast(fincome as signed)");

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

    	$clsteacher = $db->getRow("select * from assign_teacher where class='".$_GET["class"]."' and section='$_GET[section]' and session='".$_SESSION["admin"]["session"]."' ");

		$teacher = $db->getVal("select name from staff where idno='".$clsteacher["teacher_id"]."' and session='".$_SESSION["admin"]["session"]."' ");

        $terms = $db->getRows("select exam from term_permission where term='$_GET[term]' and class='$_GET[class]' order by ordering ");

		$chkclassoptional = $db->getVal("select id from optional_class where class='$_GET[class]' and section='$_GET[section]' ");

        $newsubject = array();
        $k = 0;
        foreach($allsubject as $s){
            // echo $s['subject'];
            if($s['subject'] == "English Literature"){
                $newsubject[$k]["subject"] = $s['subject'];
                $k++;
                $newsubject[$k]["subject"] = "English";
            } 
            elseif($s['subject'] == "Hindi Literature"){
                $newsubject[$k]["subject"] = $s['subject'];
                $k++;
                $newsubject[$k]["subject"] = "Hindi";
            }
            else {
                $newsubject[$k]["subject"] = $s['subject'];
            }
            
            $k++;
        }

        $allsubject = $newsubject;

        // echo "<br>";
        // print_r($newsubject);

        // die();

        $coscholastic = $db->getVal("select co_scholastic from term_permission where term='$_GET[term]' and class='".$_GET["class"]."'  ");
        $termname = $db->getVal("select name from examname where id='$coscholastic' ");

	    $record = $db->getRows("select type from criteria where class='$_REQUEST[class]' and session='".$_SESSION["admin"]["session"]."' group by type ");

        ?>
        <div class="well no-padding divclass" id="printDiv2">
        <?php
        // foreach($allsubject as $sub){
            ?>
            <div class="mydiv">
                <label style="float:left;display:inline-block;">Class Teacher Name : <?php echo $teacher; ?></label>
                <label style="float:right;display:inline-block;">Class & Sec : <?php echo $_GET["class"]." - ".$_GET["section"]; ?></label>
            	<table class="table" border="1" id="tblData"  style="margin-bottom:20px;" cellspacing="0">
    				<thead>
        				<tr style="background:teal;">
                            <td rowspan="2">S. No.</td>
                            <td rowspan="2">Adm No.</td>
                            <td rowspan="2">Student</td>
                			<td rowspan="2">Roll No.</td>
                			<?php foreach($allsubject as $sub){

                			$colspan = count($terms)+2;

                			?>
                			<td colspan="<?php echo $colspan; ?>" style="text-align:center;"><?php echo $sub["subject"]; ?></td>
                			<?php } ?>
                			<td rowspan="2" style="color:black;">Marks</td>
                			<td rowspan="2" style="color:black;">Percentage</td>
                			<td rowspan="2" style="color:black;">Rank</td>
                			<?php foreach($record as $r){
                                $names = $db->getRows("select * from criteria where type='$r[type]' and class='$_REQUEST[class]' and session='".$_SESSION["admin"]["session"]."' ");
    	                    ?>
                			<td colspan="<?php echo count($names); ?>" style="text-align:center;"><?php echo $r["type"]; ?></td>
                			<?php } ?>
                            <td rowspan="2" style="color:black;">Attendance</td>
                			<td rowspan="2" style="color:black;">Remarks</td>
                        </tr>
                        <tr style="background:teal;"> 
                            <?php 
                            $finalTotal = 0;
                            foreach($allsubject as $sub){
                                
                                $maxtotal = 0;
                                $examtotal = 0;

        				        foreach($terms as $term){

        				            if($sub['subject']== 'English' ){
        						        $wheresubject = " and (subject='English Language' || subject='English Literature' || subject='English') ";
        						    }
        						    elseif($sub['subject']== 'Hindi' ){
        						        $wheresubject = " and (subject='Hindi Language' || subject='Hindi Literature' || subject='Hindi') ";
        						    }
        						    else {
        						        $wheresubject = " and subject='$sub[subject]' ";
        						    }

        				            $marks = $db->getVal("select term_percent from examterm where name='$term[exam]' and class='$_GET[class]' and session='".$_SESSION["admin"]["session"]."' $wheresection $wheresubject ");

                                        $examname = $term["exam"];
                                        if($term["exam"] === "NOTE1"){
                                            $examname = "NB";
                                        }
                                        if($term["exam"] === "SUBEN1"){
                                            $examname = "SE";
                                        }
                                        if($term["exam"] === "HALFYEARLY"){
                                            $examname = "HY";
                                        }
                					        echo "<td style='color:black;'>$examname <br> ($marks)</td>";
                					        $maxtotal+=$marks;

        				        }
                			
                			?>
                			<td style="color:black;">Total <br> (<?php echo $maxtotal; 
                            if(($sub['subject'] !== "English Language") && ($sub['subject'] !== "English Literature") && ($sub['subject'] !== "Hindi Language") && ($sub['subject'] !== "Hindi Literature") ){
                                // $finalTotal+=$maxtotal;
                            }

                			 ?>)</td>
                			<td style="color:black;">Grade</td>
                			
                			<?php }
                			
                			foreach($record as $r){
                                $names = $db->getRows("select * from criteria where type='$r[type]' and class='$_REQUEST[class]' and session='".$_SESSION["admin"]["session"]."' ");
                			foreach($names as $name){
                                    $coscholastic = $db->getVal("select co_scholastic from term_permission where term='$_GET[term]' and class='".$_GET["class"]."'  ");
                                    $termname = $db->getVal("select name from examname where id='$coscholastic' ");
                                    $grade=$db->getVal("select grade from examcriteriarecord where school_id='".$_SESSION["admin"]["school_id"]."' and idno=".$stu["idno"]." and subcriteria='".$name["name"]."' and criteria='".$row['type']."' and session='".$_SESSION["admin"]["session"]."' and term='$termname' ");
                                ?>
                                    <td style="text-align:left;color:black;"><?php if($name['name']==="Health & Physical Education"){echo "H&PE";} else { echo $name['name']; } ?></td>
                            <?php }
                			}
                			?>
                			
                        </tr>
                    </thead>
                <tbody>
    			<?php $i=0; $percentArray = array();
    			foreach($allStudent as $stu){$i++;
                $finalTotal = 0;
    			$hiderank = false;
    			
    				?>
    				<tr>
                    	<td><?php echo $i; ?></td>
                		<td><?php echo $stu["admissionno"] ?></td>	
                    	<td><?php echo $stu["name"] ?></td>
    					<td><?php echo $stu["fincome"] ?></td> 

                        <?php $finalObtain = 0;
                        foreach($allsubject as $sub){
                            $allobtainmarks = 0;
                            if($_GET["term"] == "Term1" || $_GET["term"]=="Term2"){
                                $examobtain = 0;
                                
                            $chksubjectoptional = 0;
    						if($chkclassoptional > 0){
    						    $chksubjectoptional = $db->getVal("select id from optional_subject where idno='$stu[idno]' and subject='$sub[subject]' and session='".$_SESSION["admin"]["session"]."' ");
    						}

    						        foreach($terms as $term){
    						            
    						            if($chksubjectoptional == 0){
    						            
    						            if($sub['subject']== 'English' ){
            						        $wheresubject = " and (subject='English Language' || subject='English Literature' || subject='English') ";
            						    } elseif($sub['subject']== 'Hindi' ){
            						        $wheresubject = " and (subject='Hindi Language' || subject='Hindi Literature' || subject='Hindi') ";
            						    } else {
            						        $wheresubject = " and subject='$sub[subject]' ";
            						    }

    						            $termpercent = $db->getVal("select term_percent from examterm where name='$term[exam]' and class='$_GET[class]' and session='".$_SESSION["admin"]["session"]."' $wheresection $wheresubject ");

                                        if($term['exam']=="PT"){
                                            $wherexam = "(type='PT1' or type='PT2' ) ";

            								$examResultData=$db->getRow("select  sum(total) as total, sum(obtain) as obtain  from exammarks where idno='".$stu["idno"]."' and $wherexam $wheresubject ");

                                        } else {
                                            $examResultData=$db->getRow("select  sum(total) as total, sum(obtain) as obtain  from exammarks where idno='".$stu["idno"]."' and type='$term[exam]' $wheresubject ");
                                        }

                					       $obtain = number_format($examResultData["obtain"]*$termpercent/$examResultData["total"],1)+0;

                					        echo "<td>".round($obtain)."</td>";

                					        $allobtainmarks+=round($obtain);
                					        
                					        $finalTotal+=$termpercent;
    						            } else {
    						                echo "<td>0</td>";
    						            }
                                }
                            }  ?>
                        <td><?php echo round($allobtainmarks);
                        
                            if(($sub['subject'] !== "English Language") && ($sub['subject'] !== "English Literature") && ($sub['subject'] !== "Hindi Language") && ($sub['subject'] !== "Hindi Literature") ){
                                $finalObtain+=round($allobtainmarks);
                            }

                            if(round($allobtainmarks)<33){
							        $hiderank = true;
                            }
                        ?></td>
                        <td><?php echo FindGrades($allobtainmarks, 100); ?></td>
                        <?php } ?>
                        <td><?php echo "$finalObtain/$finalTotal"; ?></td>
                        <td><?php echo $percentage = number_format(($finalObtain*100/ $finalTotal),2); $percentArray[$stu['idno']]= $percentage; ?> %</td>
                        <td><span id="rank_<?php echo $stu['idno']; ?>"></span></td>
                        <?php
                        foreach($record as $r){
                                $names = $db->getRows("select * from criteria where type='$r[type]' and class='$_REQUEST[class]' and session='".$_SESSION["admin"]["session"]."' ");
                            foreach($names as $name){
                                    $grade=$db->getVal("select grade from examcriteriarecord where idno=".$stu["idno"]." and subcriteria='".$name["name"]."' and criteria='".$r['type']."' and session='".$_SESSION["admin"]["session"]."' and term='$termname' ");
                                ?>
                                    <td style="text-align:left;"><?php echo $grade; ?></td>
                            <?php } } 
                            
                            
                        $fdate = "2022-03-21";
            			$tdate = "2022-10-01";
    
                        $data = $db->getRow("select * from attendance_remark where idno='$stu[idno]' and class='$_GET[class]' and type='$_GET[term]' and session='".$_SESSION["admin"]["session"]."' ");
    
                        $result1 = $db->getVal("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' ");
                        $totalpresent=$data["working_days"]-$result1;
        				?>
    					<td><?php echo $data['present']."/".$data['working_days']; ?></td>
                        <td><?php echo $data['remark']; ?></td>

                    </tr>
    				<?php 
        			$allobtainmarks=0;$alltotalmarks=0; $finalObtain = 0;
    			}
    			
    			
			    arsort($percentArray);
	            /*
		        $rank = 1;    
                foreach($percentArray as $key => $value){
                    ?>
                    <script>
                        $("#rank_"+<?php echo $key; ?>).html(<?php echo $rank; ?>);
                    </script>
                    <?
                    $rank++;
                }
                */

        	    $unique = array_unique($percentArray);
        
        	    $temp = []; $j = 1;
        	    foreach($unique as $un){
        	        $temp["$un"] = $j;
        	        $j++;
        	    }
        
                foreach($percentArray as $key => $val){
                    foreach($temp as $key1 => $val1){
                        if($val==$key1){
                            ?>
                            <script>
                                $("#rank_"+<?php echo $key; ?>).html(<?php echo $val1; ?>);
                            </script>
                            <?
                        }
                    }
                    
                }

    			?>
    			</tbody>
            </table>
                <div style="width:800px;">.</div>
                    <style>
                    @media print {
                        .mydiv {page-break-after: always;}
                    }
                    </style>
        	</div>
 
	    </div> 
	    <?php

    }
 
	function FindGrades($obtain,$total){
	$per=round(($obtain*100)/$total);
	global $db;
	$data=$db->getRows("select * from examgrade  where school_id='".$_SESSION["admin"]["school_id"]."' ");
	if(is_array($data) && count($data)>0){
		foreach($data as $d){
			if($per>=$d["minrange"] && $per<=$d["maxrange"]){
				return "<div style='width:25px;height:20px;padding-top:5px;text-align:center;margin:auto;'>$d[grade]</div>"; 
			}
		}
	}
	return $per;
}


?>

<script>
    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 || ('Term Wise Report.' + (type || 'xlsx')));
    }
</script>

<script type="text/javascript">

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' || c=='NA'){
    
}
else if(v>t){
	alert("Please enter correct marks");
	a.value='';
}
else {
    alert("Please enter only AB or NA");
    a.value='';
}

// if(c!='AB' && isNaN(v))
// {
// alert("Please enter only AB");
// a.value='';	
// }
// else if(v>t){
// 		alert("Please enter correct marks");
// 		a.value='';
// 	}
	//else if(c!='A'){
		
		//a.value='';
	//}
	
		
	//alert(r);
}

    $("#btn_excel").click(function(e) {
        var filename = $("#filename").val();
        if(filename==''){filename='Report';}
        let file = new Blob([$('.divclass').html()], {type:"application/vnd.ms-excel"});
        let url = URL.createObjectURL(file);
        let a = $("<a />", {
        href: url,
        download: "Cummulative Term Wise Report.xls"}).appendTo("body").get(0).click();
        window.location.reload();
        e.preventDefault();
    });

</script>



