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


if(isset($_POST['save']))
{
	$_SESSION['form']=$_POST;
	$flgEr=FALSE; 
	if(!isset($_POST['total']) || trim($_POST['total'])=='')
	{
		$flgEr=TRUE;
		array_push($alert_err,"Please enter total."); 
	}
	if($pgAct=="edit" && isset($_GET['id']) && trim($_GET['id'])!='')
	{
		$flgUp=$db->updateAry("examterm",$_POST,"where school_id='".$_SESSION["admin"]["school_id"]."' and id='".$_GET['id']."'");
		if(!is_null($flgUp))
		{   
			$_SESSION['msg']='update Successfully';
			unset($_SESSION['form']);
			redirect(URL_ADMIN_HOME.getQueryString(array("src"=>"ExamCBSE", "page_id"=>$pgMod)));
		}
		else
		{
			array_push($alert_err,$db->getErMsg());
		
		}
	} 
}
if(isset($_POST['save_term'])){


$start = str_replace("T"," ",$_POST['start_date'][0]);
// echo $start.":00";
// // print_r($_POST);
// die();

    $i = 0;
    foreach($_POST['cls'] as $cls){
        $section    = $_POST['section'][$i];
        $percent    = $_POST['percent'][$i];
        // $total      = $_POST['total'][$i];
        
        // $start = str_replace("T"," ",$_POST['start_date'][$i]);
        // $start = $start.":00";
        
        // $end = str_replace("T"," ",$_POST['end_date'][$i]);

        $j = 0;
        foreach($_POST["subject_$i"] as $sub){

            $total = $_POST["total_$i"][$j];

            $saveary = array(
                "school_id" =>  $_SESSION["admin"]["school_id"],
                "name"      =>  $_POST['name'],
                "full_name" =>  $_POST['full_name'],
                "percent"   =>  $percent,
                "term_percent"   =>  $_POST['term_percent'][$i],
                "month"     =>  "April",
                "total"     =>  $total,
                "added_by"  =>  $_SESSION["admin"]["uid"],
                "term"      =>  "term1",
                "class"     =>  $cls,
                "section"   =>  $section,
                "subject"   =>  $sub,
                "start_date"=>  $_POST['start_date'][$i],
                "end_date"  =>  $_POST['end_date'][$i],
                "session"   =>  $_SESSION["admin"]["session"]
            );
            
            $check = $db->getVal("select id from examterm where name='$_POST[name]' and class='$cls' and section='$section' and subject='$sub' and session='".$_SESSION["admin"]["session"]."' ");

            if($percent!="" || $total !=""){
                if($check > 0){
                    $flg = $db->updateAry("examterm", array("percent" => $percent, "term_percent"=>$_POST['term_percent'][$i], "total" => $total, "start_date"=>$_POST['start_date'][$i], "end_date"=>$_POST['end_date'][$i]), "where name='$_POST[name]' and class='$cls' and section='$section' and subject='$sub' and session='".$_SESSION["admin"]["session"]."'");
                } else {
                    $flg = $db->insertAry("examterm", $saveary);
                }
            }
            
            // print_r($saveary);

            $j++;
        }

        $i++;
    }
// die();

    redirect(URL_ADMIN_HOME.getQueryString(array("src"=>"ExamCBSE", "page_id"=>$pgMod)));
    
}
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
}
if($pgAct=="edit" && $_GET["id"]!="")
{   
	$aryForm=$db->getRow("SELECT * FROM examterm WHERE school_id='".$_SESSION["admin"]["school_id"]."' and id='".$_GET['id']."'");
}
if($pgAct=="add" || ($pgAct=="edit" && isset($_GET['id']) && trim($_GET['id']) !=''))
{
?>
<!-- Forms --> 
	<div class="row-fluid">
        <form method="post" action="">
			<!-- Forms: Box -->
			<div class="span12">

				<!-- Forms: Top Bar -->
				<div class="top-bar">
					<h3><i class="icon-cog"></i> Terms</h3>
				</div>
				<!-- Forms: Content -->
				<div class="well no-padding">

						<div class="control-group">
							<label class="control-label" for="class">Term</label>
							<div class="controls">
								<?php echo $aryForm["full_name"] ?>
							</div>
						</div>
                        <div class="control-group">
							<label class="control-label" for="total">Total</label>
							<div class="controls">
								<input type="text" id="total" name="total" class="input-block-level" value="<?php if($_POST)echo $_POST["total"]; else echo $aryForm["total"] ?>">
							</div>
						</div>
						<div class="form-actions">
							<button type="submit" class="btn btn-primary" name="save"> Save</button>
							<button type="button" class="btn"> Cancel</button>
						</div>
                        
				</div>
				<!-- / Forms: Content -->

			</div>
			<!-- / Forms: Box --> 

        </form>
	</div>
<?php   
}
elseif(isset($_GET["add_term"])){
    $exam = $db->getRow("select * from examname where id='$_GET[exam]' ");

    // print_r($examterm);

		?><form method="post" action="">
		<div class="row-fluid">
            <div class="span12">
            	<div class="top-bar">
					<h3><i class="icon-cog"></i>Add New Term</h3>
                    <div>
						<button type="submit" name="save_term" class="btn btn-primary"> Save Term</button> 
					</div>
				</div>
				<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>SNo.</th>
                <th>Class</th>
                <th>Exam wise Percent</th>
                <th>Term wise Percent</th>
                <th>Subject Total</th> 
                <th>Start Time</th>
                <th>End Time</th>
            </tr>
			<?php $i=0; $j = 0;
			$allclass = $db->getRows("SELECT concat(class, '/',section) as newclass from subject where  session='".$_SESSION['admin']['session']."' GROUP BY newclass ");
			foreach($allclass as $cls){$i++;
                $ary = explode("/",$cls['newclass']); 
			 //   $examterm = $db->getRow("select * from examterm where name='".$exam['name']."' and class='$ary[0]' and session='".$_SESSION['admin']['session']."' ");

                $data = $db->getRow("select percent,term_percent, start_date, end_date from examterm where name='".$exam['name']."' and class='$ary[0]' and section='$ary[1]' and session='".$_SESSION['admin']['session']."' ");

                $start = $data['start_date'];
                $start = str_replace(" ", "T", $start);
 
                $end = $data['end_date'];
                $end = str_replace(" ", "T", $end);
                
                $subjects = $db->getRows("select subject from subject where class='$ary[0]' and section='$ary[1]' and session='".$_SESSION['admin']['session']."' ");

				?>
				<tr> 
                	<td><?php echo $i; ?></td> 
                	<td><?php echo $cls['newclass']; ?>
                	<input type="hidden" name="cls[]" value="<?php echo $ary[0]; ?>" />
                	<input type="hidden" name="section[]" value="<?php echo $ary[1]; ?>" />
                	</td> 
                	<td><input type="text" name="percent[]" value="<?php echo $data['percent']; ?>" style="width:80px;" /></td>
                	<td><input type="text" name="term_percent[]" value="<?php echo $data['term_percent']; ?>" style="width:80px;" /></td>
                	<td>
                	    <?php foreach($subjects as $sub){ 
                	        $total = $db->getVal("select total from examterm where name='".$exam['name']."' and class='$ary[0]' and section='$ary[1]' and subject='$sub[subject]' and session='".$_SESSION['admin']['session']."' ");
                	    ?>
                	    <div style="display:inline-block;">
                	        <?php echo $sub['subject']; ?>
                    	    <br>
                    	    <input type="text" name="total_<?php echo $j; ?>[]" value="<?php echo $total; ?>" style="width:80px;" />
                    	    
                    	    <input type="hidden" name="subject_<?php echo $j; ?>[]" value="<?php echo $sub['subject']; ?>" />
                	    </div>

                	    <?php } ?>
                	    <!--<input type="text" name="total[]" value="<?php echo $examterm['total']; ?>" />-->
            	    </td>
            	    
            	    <td>
            	        <input type="datetime-local" name="start_date[]" value="<?php echo $start; ?>" style="width:150px;"  />
            	    </td>
            	    <td>
            	        <input type="datetime-local" name="end_date[]" value="<?php echo $end; ?>" style="width:150px;"  />
            	    </td>
                </tr>
				<?php $j++;
			}
			?></table>
			</div>
		</div></div></div></div></form><?php
	}

else{
    	$allexam = $db->getRows("SELECT * FROM examname order by id");
	?>
	<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>
        <form method="get" action="">

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

            <div class="control-group" style="display:inline-block;">
                <label class="control-label" style="color:white;">Select Exam</label>
                <div  class="controls">
                    <select name="exam">
                        <option value=""> -- Select -- </option>
                        <?php foreach($allexam as $exam){ ?>
                            <option value="<?php echo $exam['id']; ?>"><?php echo $exam['name']; ?></option>
                        <?php } ?>
                    </select>
                </div>
            </div>

            <button type="submit" name="add_term" class="btn btn-primary"> Add Term</button>
        </form>
    </div>
    <div class="well no-padding">
	<?php
	$aryPgAct=array("src"=>"ExamCBSE", "page_id"=>$pgMod,"action"=>"add");
	$aryList=$db->getRows("SELECT * FROM examterm where school_id='".$_SESSION["admin"]["school_id"]."'"); $i=0;
	if(is_array($aryList) && count($aryList)>0)
	{
		?>
        <table class="table" id="example"> 
            <thead>
                <tr>
                    <th>S.No.</th>
                    <th>Class</th>
                    <th>section</th>
                    <th>Subject</th>
                    <th>Exam Name</th>
                    <th>Percent</th>
                    <th>Total</th>
                    <!--<th>Action</th>-->
                </tr> 
            </thead>
            <tbody>
            <?php foreach($aryList as $clist){ $i++; 
            $aryPgAct["id"]=$clist['id'];
            ?>
                <tr class="grade<?php if($i%2==0)echo "C";else "U";?>">
                    <td><?php echo $i; ?></td>
                    <td><?php echo $clist["class"] ?></td>
                    <td><?php echo $clist["section"] ?></td>
                    <td><?php echo $clist["subject"] ?></td>
                    <td><?php echo $clist["full_name"]." (".$clist["name"].")"; ?></td>
                    <td><?php echo $clist["percent"] ?></td>
                    <td><?php echo $clist["total"] ?></td>
                    <!--<td>-->
                    <?php //$aryPgAct['action']="edit"; ?>
                         <!--<a style="float:left" href="<?php echo URL_ADMIN_HOME.getQueryString($aryPgAct); ?>"><button type="button" class="btn btn-info">Edit</button></a> -->
                    <!--</td>-->
                </tr>
            <?php } ?>
            </tbody>

        </table>
		<?php
	}
	else{
		?>
        <div class="alert alert-info">
          <a class="close" data-dismiss="alert">×</a>
          <i class="icon icon-warning-sign"></i> <b>Notice</b> Record not found </i>
        </div>
        <?php
	}
	?>
	</div></div></div>
	<?php
}
?>
<!-- / Forms -->