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

if($_POST)
{
	$_SESSION['form']=$_POST;
	$flgEr=FALSE;
	$type=$db->getVal("select id from extrafee_type where type='".$_POST["type"]."' and class='".$_POST["class"]."'  and session='".$_SESSION["admin"]["session"]."' ");
	if(!isset($_POST['type']) || trim($_POST['type'])=='')
	{
		$flgEr=TRUE;
		array_push($alert_err,"Please enter fee type.");
	}else
	if($pgAct=="add" && $type!=""){
		$flgEr=TRUE;
		array_push($alert_err,"fee Type already exist from this class.");
	} 
	elseif(!isset($_POST['class']) || trim($_POST['class'])=='')
	{
		$flgEr=TRUE;
		array_push($alert_err,"Please select Class.");
	}
	if($flgEr!=TRUE && $pgAct=="add")
	{
		$otype=$_POST["otype"];
		
		$feename = $_POST['type'];
    	  $extra_name = str_replace(' ', '_', $feename);
    	$_POST['type'] = $extra_name;
		$_POST["session"]=$_SESSION["admin"]["session"];
		$_POST["school_id"]=$_SESSION["admin"]["school_id"];
		$_POST["added_by"]=$_SESSION["admin"]["uid"];
		//echo "<pre>";print_r($_POST);exit;
		$flgIn=$db->insertAry("extrafee_type",$_POST);
		if(is_null($db->getErMsg()))
		{
			$slist=array();
			if($otype==""){
				$studentList=$db->getRows("select idno from student where class='".$_POST["class"]."' and session='".$_SESSION["admin"]["session"]."' ");
				if(is_array($studentList) && count($studentList)>0){
					foreach($studentList as $sl){
						$slist[]=$sl["idno"];
					}
				}
			}elseif($otype=="new"){
				$studentList=$db->getRows("select idno from student where stype='new' and class='".$_POST["class"]."' and session='".$_SESSION["admin"]["session"]."' ");
				if(is_array($studentList) && count($studentList)>0){
					foreach($studentList as $sl){
						$slist[]=$sl["idno"];
					}
				}
			}elseif($otype=="old"){
				$studentList=$db->getRows("select idno from student where stype='old' and class='".$_POST["class"]."' and session='".$_SESSION["admin"]["session"]."' ");
				if(is_array($studentList) && count($studentList)>0){
					foreach($studentList as $sl){
						$slist[]=$sl["idno"];
					}
				}
			}elseif($otype!="" && is_numeric($otype)){
				$slist[]=$otype;
			}
			if(is_array($slist) && count($slist)>0){
				foreach($slist as $list){
					$saveAry=array(
								"session"	=>	$_SESSION["admin"]["session"],
								"school_id"	=>	$_SESSION["admin"]["school_id"],
								"added_by"	=>	$_SESSION["admin"]["uid"],
								"type"	=>	$flgIn,
								"idno"	=>	$list,
								"pay"	=> 	0,
								"status"	=>	1
					);
					for($i=1; $i<=12;$i++){
						if($_POST["p".$i]>"0"){
							$saveAry["pid"]="p".$i;
							$saveAry["fee"]=$_POST["p".$i];
							$db->insertAry("extrafee",$saveAry);
						}
					}
				}
			}
			$_SESSION['msg']='Saved Successfully';
			unset($_SESSION['form']);
			redirect(URL_ADMIN_HOME.getQueryString(array("src"=>"Student","page_id"=>$pgMod)));
		}
		else
		{
			array_push($alert_err,$db->getErMsg());
			
		}
	}
}		
elseif($pgAct=="delete" && isset($_GET['id']) && trim($_GET['id'])!='')
{
	$reff=$db->getRows("select * from reff_receipt where type='extrafee".$_GET["id"]."'");
	if(is_array($reff) && count($reff)>0){
		array_push($alert_err,"fee already given for this fee sctructure you cannot delete it");
	}else{
		$os=$db->getRow("select * from extrafee_type where school_id='".$_SESSION["admin"]["school_id"]."' and id='".$_GET["id"]."'");
		$res=$db->delete("extrafee_type","where  school_id='".$_SESSION["admin"]["school_id"]."' and id='".$_GET['id']."'");
		$res=$db->delete("extrafee","where  school_id='".$_SESSION["admin"]["school_id"]."' and type='".$_GET['id']."'");
		$insname=$os["class"]."-otherfee";
		if(!is_null($res)) { $_SESSION['msg']='Deleted Successfully'; }
		else { array_push($alert_err,$db->getErMsg()); }
		redirect(URL_ADMIN_HOME.getQueryString(array("src"=>"Student","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 extrafee_type 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> Create a New Extra fee structure</h3>
				</div>
				<!-- / Forms: Top Bar -->

				<!-- Forms: Content -->
				<div class="well no-padding">
						<div class="control-group">
							<label class="control-label" for="type">Fees Type</label>
							<div class="controls">
								<input type="text" id="type" name="type" placeholder="tusion fee or computer fee etc." required class="input-block-level" value="<?php if($_POST)echo $_POST["type"]; else echo $aryForm["type"] ?>">
							</div>
						</div>
                        
						<div class="control-group">
							<label class="control-label" for="class">Class Name </label>
							<div class="controls">
								<select name="class" id="class" onchange="getStudentlist(this.value)">
                                    <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 ">
							<label class="control-label" for="otype">Offer to</label>
							<div class="controls" id="studentList">
								<select name="otype" id="otype">
                                    <option value="">Select class first</option>
                                </select>
							</div>
						</div>
                        <div class="control-group">
							<label class="control-label" for="type">Fees Total</label>
							<div class="controls">
								<input type="text" id="total" name="total" placeholder="Enter Total fee." required class="input-block-level" onkeyup="devideEqualFeetoall(this)" value="<?php if($_POST)echo $_POST["total"]; else echo $aryForm["total"] ?>">
							</div>
						</div>
                        <div class="control-group">
							<label class="control-label" for="">Monthly fee <input type="checkbox" id="checkboxa" onchange="checkCheckedAll()" /></label>
							<div class="controls">
								<table class="table">
                                	<?php for($i=1;$i<=12;$i++){ ?>
                                    <tr>
                                    	<td>
                                        <label for="chked<?php echo $i ?>">
                                        <input type="checkbox" <?php if($aryForm["p".$i]!="0")echo 'checked="checked"'; ?> id="chked<?php echo $i ?>" class="chk" value="p<?php echo $i ?>" /> &nbsp; 
										<?php if($i<=9){
							$newDate=date("Y")."-".($i+3)."-1";
							echo date("F",strtotime($newDate));//."(".($ij+3).")";
						  }
						  else{
							$newDate=date("Y")."-".($i-9)."-1";
							echo date("F",strtotime($newDate));//."(".($ij-9).")";
						  }?>
										<?php //$year=date("Y");echo date("F",strtotime(date("Y-".$i."-d"))) ?></label> </td>
                                        <td><input id="p<?php echo $i ?>" name="p<?php echo $i ?>" readonly="readonly" type="text" class="input-block-level monthfeeDetail" value="<?php if($_POST)echo $_POST["p".$i]; else echo $aryForm["p".$i] ?>" />
                                        </td>
                                    </tr>
                                    <?php } ?>
                                </table>
							</div>
						</div>
                        
                        
                        
						<div class="form-actions">
							<button type="submit" class="btn btn-primary"> Save</button>
							<button type="button" class="btn"> Cancel</button>
						</div>
                        
				</div>
				<!-- / Forms: Content -->

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

        </form>
	</div>
<?php   
}else{
	?>
	<div class="row-fluid"><div class="span12"><div class="top-bar">
    <h3><i class="icon-eye-open"></i> <?php echo ucwords($pgAct." ".$pgMod); ?></h3>
    <button style="float:right; margin-top:5px" onclick="window.location='./?src=Student&page_id=<?php echo $pgMod; ?>&action=add'" class="btn" type="button">Add <?php echo $pgMod; ?></button>
    </div>

    <div class="well no-padding">
    <!--<div style="display:block;background:transparent;width:100%;color:black;" id="due-div">-->
	<?php
	$aryPgAct=array("src"=>"Student","page_id"=>$pgMod,"action"=>"add");
	$aryList=$db->getRows("SELECT * FROM extrafee_type  where session='".$_SESSION["admin"]["session"]."'"); $i=0;
	if(is_array($aryList) && count($aryList)>0)
	{
		?>
        <table class="table" id="example">
            <thead>
                <tr>
                	<th>Fee Type</th>
                    <th>Class</th>
                    <th>Apply to</th>
                    <th>Fee</th>
                    <th>Action</th>
                    <th>Status</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 $clist["type"] ?></td>
                    <td><?php echo $clist["class"];//."(".$clist["medium"].")" ?></td>
                    <td><?php if($clist["otype"]=="")echo "all";elseif(is_numeric($clist["otype"]))echo $db->getVal("select name from student where idno='".$clist["otype"]."'");else echo $clist["otype"] ?></td>
                    <td><?php echo $clist["total"] ?></td>
                    <td>
                    <?php $aryPgAct['action']="delete"; ?>
                         <a href="javascript:;" onclick="del('<?php echo URL_ADMIN_HOME.getQueryString($aryPgAct); ?>')" class="confirmation"><button type="button" class="btn btn-danger">Delete</button></a>
                         
                         <button class="btn btn-info" onclick="updatefee('<?php echo $clist['id']; ?>', '<?php echo $clist['class']; ?>')">Update Fee</button>
                         
                         <div style="display:inline-block;background:transparent;width:100%;color:black;float:right;" id="due-div<?php echo $clist['id']; ?>">
                    </td>
                    <td>
                        <?php $students = $db->getVal("select count(idno) from student where class='$clist[class]' and session='".$_SESSION["admin"]["session"]."' ");
                                // echo $students;
                                
                            $appliedfee = $db->getRows("SELECT id FROM extrafee WHERE type='$clist[id]' AND session='".$_SESSION["admin"]["session"]."' group by idno");
                            // echo "<br>";
                            // echo count($appliedfee);
                            echo "<label style='display:inline-block;'>".$students."<br>".count($appliedfee)."</label>";
                            
                            if($students == count($appliedfee)){
                                echo "<label style='display:inline-block;margin-left:50px;'>Completed</label>";
                            }
                        ?>
                    </td>
                </tr>
            <?php } ?>
            </tbody>
        </table>
        <!--</div>-->
		<?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 -->
<script>
function devideEqualFeetoall(id){
	var total=$(id).val();
	var chked=$('input[type="checkbox"].chk:checked').length;
	if(chked==0){
		alert("please check atleast 1 check box ");
		$(id).val('');$(".monthfeeDetail").val('');
	}else{
		eqial12=total/chked;
		$(".monthfeeDetail").val('');
		$('input[type="checkbox"].chk:checked').each(function(index, element) {
			var name=$(this).val();
			$("#"+name).val(eqial12);
		});
		
	}
	
}
function checkCheckedAll(){
	if($('#checkboxa').prop('checked')) {
		$('.chk').prop('checked', true);
    } else {
        $('.chk').prop('checked', false);
    }
}

$(document).ready(function(e) {
	$('.monthfeeDetail, #total').keydown(function(event) {
	if(event.shiftKey)
	{
		event.preventDefault();
	}
   if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 190 || event.keyCode == 110 )   {
   }
   else {
        if (event.keyCode < 95) {
          if (event.keyCode < 48 || event.keyCode > 57) {
                event.preventDefault();
          }
        }
        else {
              if (event.keyCode < 96 || event.keyCode > 105) {
                  event.preventDefault();
              } 
        }
      }
   });
})
<?php 
if(is_array($aryForm) && count($aryForm)>0){?>
$(document).ready(function(e) {
    getStudentlist('<?php echo $aryForm["class"] ?>');
});
<?php }?>
function getStudentlist(id){
	$.post( "ajax.php", { type: "getStudentlist" ,class: id <?php if(is_array($aryForm) && count($aryForm)>0) echo ',otype:"'.$aryForm["otype"].'"'; ?>} , function( data ) {
	  	$("#studentList").html(data);
	});
}


function updatefee(id, cls){
// 	$.post( "ajax.php", { type: "extrafee_update" ,id: id, cls: cls} , function( data ) {
// 	    alert(data);
// 	});

        var month = $("#month1").val();
        $.ajax({
               method: 'POST',
               url: 'ajax.php?type=extrafee_update',
               data : {id:id, cls:cls},
               beforeSend: function()
            {
                $("#error").fadeOut(0);
                $("#due-div"+id).html('<img src="uploads/ajax-loader.gif" style="margin:20px;width:50px;height:50px;" />   Updating ...');
                // modal.style.display = "block";
            },
            success: function( response ){
                alert(response);
                $("#due-div"+id).html('');
            },
            error: function(xhr, desc, err){
               console.log(err);
            }
        });

}

</script>


