<script>
    function checkAll(){
    	if($('#checkboxa').prop('checked')) {
    		$('.checkboxes').prop('checked', true);
        } else {
            $('.checkboxes').prop('checked', false);
        }
        getamount();
    }
     
    function monthlycheck(month){
    	if($('#month'+month).prop('checked')) {
    		$('.month'+month).prop('checked', true);
        } else {
            $('.month'+month).prop('checked', false);
        }
        getamount();
    }
    
    function checktution(){
    	if($('#tution').prop('checked')) {
    		$('.allmonths').prop('checked', true);
    		$('.tution').prop('checked', true);
        } else {
    		$('.allmonths').prop('checked', false);
            $('.tution').prop('checked', false);
        }
        getamount();
    }

    function checkbus(){
    	if($('#bus').prop('checked')) {
    		$('.allmonths').prop('checked', true);
    		$('.bus').prop('checked', true);
        } else {
    		$('.allmonths').prop('checked', false);
            $('.bus').prop('checked', false);
        }
        getamount();
    }
    
    function checkextra(id){
    	if($('#'+id).prop('checked')) {
    		$('.allmonths').prop('checked', true);
    		$('.extra'+id).prop('checked', true);
        } else {
    		$('.allmonths').prop('checked', false);
            $('.extra'+id).prop('checked', false);
        }
        getamount();
    }

    function checkother(id){
    	if($('#'+id).prop('checked')) {
    		$('.allmonths').prop('checked', true);
    		$('.other'+id).prop('checked', true);
        } else {
    		$('.allmonths').prop('checked', false);
            $('.other'+id).prop('checked', false);
        }
        getamount();
    }


    function getamount(){

        var feeary = [];
        var totalfee = 0;
        var totaldiscountamount = 0;

        var disc_amt = $("#disc_amount").val();
        var percent = $("#disc_percent").val();
        
        if(disc_amt != ""){
            
            var tempamt = disc_amt;
            for(var i = 1 ; i <= 12; i++){
            	if($('#month'+i).prop('checked')) {
                    var  feetype = [];
        	        $('.month'+i).each(function() {
                	    if($(this).prop('checked')){
            	           var fee = $(this).val();
            	           totalfee = parseFloat(totalfee)+parseFloat(fee);
            	           if(tempamt>0){
            	               if(parseFloat(tempamt) > parseFloat(fee)){
            	                   var discount = parseFloat(fee); 
            	                   tempamt = parseFloat(tempamt)-parseFloat(fee);
            	               } else {
            	                   var discount = parseFloat(tempamt);
            	                   tempamt = tempamt-tempamt;
            	               }
                   	           totaldiscountamount = parseFloat(totaldiscountamount)+parseFloat(discount);
                 				var dataname = $(this).attr('data-name');
                   				var datatype = $(this).attr('data-type');
                   			
                   				feetype.push({name:dataname, type:datatype, disamount:discount});

            	           }

                	    }
        	        });
        	        feeary.push({month:i, feedetail:feetype});
            	}
            }

        }
        
        if(percent != "") {
            for(var i = 1 ; i <= 12; i++){
            	if($('#month'+i).prop('checked')) {
                    var  feetype = []; 
        	        $('.month'+i).each(function() {
                	    if($(this).prop('checked')){
            	           var fee = $(this).val();
            	           totalfee = parseFloat(totalfee)+parseFloat(fee);
            	           var discount = parseFloat((percent*fee)/100);
            	           totaldiscountamount = parseFloat(totaldiscountamount)+parseFloat(discount);
            	           
               				var dataname = $(this).attr('data-name');
               				var datatype = $(this).attr('data-type');

               				feetype.push({name:dataname, type:datatype, disamount:discount});

                	    }
        	        });
        	        feeary.push({month:i, feedetail:feetype});
            	}
            }
        }

        $("#totalfee").html(totalfee);
        $("#discountfee").html(totaldiscountamount.toFixed(2));
    }

    function save(){

        var feeary = [];
        var totalfee = 0;
        var totaldiscountamount = 0;

        var disc_amt = $("#disc_amount").val();
        var percent = $("#disc_percent").val();

        var disc_mode = $("#disc_mode").val();

        if(disc_amt != ""){
            
            var tempamt = disc_amt;
            for(var i = 1 ; i <= 12; i++){
            	if($('#month'+i).prop('checked')) {
                    var  feetype = [];
        	        $('.month'+i).each(function() {
                	    if($(this).prop('checked')){
            	           var fee = $(this).val();
            	           totalfee = parseFloat(totalfee)+parseFloat(fee);
            	           if(tempamt>0){
            	               if(parseFloat(tempamt) > parseFloat(fee)){
            	                   var discount = parseFloat(fee); 
            	                   tempamt = parseFloat(tempamt)-parseFloat(fee);
            	               } else {
            	                   var discount = parseFloat(tempamt);
            	                   tempamt = tempamt-tempamt;
            	               }
                   	           totaldiscountamount = parseFloat(totaldiscountamount)+parseFloat(discount);
                 				var dataname = $(this).attr('data-name');
                   				var datatype = $(this).attr('data-type');
                   				var dataid   = $(this).attr('data-id');
                   			
                   				feetype.push({name:dataname, type:datatype, disamount:discount, other_id: dataid});
            	           }
                	    }
        	        });
        	        feeary.push({month:i, feedetail:feetype});
            	}
            }

                $.post("ajax.php", { type: "completediscount", idno:<?php echo $_GET['id']; ?>, discount_detail: feeary, disc_mode: disc_mode, disc_type:'amount', disc_amt:disc_amt}, function( data ) { 
                    location.reload();
                });
        }

        if(percent != ""){
            if(percent > 0){
                for(var i = 1 ; i <= 12; i++){
                	if($('#month'+i).prop('checked')) {
                        var  feetype = [];
            	        $('.month'+i).each(function() {
                    	    if($(this).prop('checked')){
                	           var fee = $(this).val(); 
                	           totalfee = parseFloat(totalfee)+parseFloat(fee);
                	           var discount = parseFloat((percent*fee)/100);
                	           totaldiscountamount = parseFloat(totaldiscountamount)+parseFloat(discount);
                	           
                   				var dataname = $(this).attr('data-name');
                   				var datatype = $(this).attr('data-type');
                   				var dataid   = $(this).attr('data-id');
                   				
                   				feetype.push({name:dataname, type:datatype, disamount:discount, other_id: dataid});
                    	    } 
            	        });
            	        feeary.push({month:i, feedetail:feetype});
                	}
                }

                $.post("ajax.php", { type: "completediscount", idno:<?php echo $_GET['id']; ?>, discount_detail: feeary, disc_mode: disc_mode, disc_type:'percent', disc_amt:percent}, function( data ) {
                    location.reload();
                });
            } else {
                alert('Please enter discount percent');
            }
        }

    }

</script> 

<style>
    .popup-form{
        margin:0px;
        border:2px solid #600;
        padding:5px;
    }
    .title{
        text-align: center;
        color: #fff;
        background-color: #1443BD;
        padding: 4px;
        border: 1px inset #1443BD;
        box-shadow: 0px 0px 10px #050101;
        border-radius: 5px;
    }
    .btn-new{
        background-color: #05967A;
        color: #fff;
        border: 2px outset #05967A;
        padding: 4px 15px;
        font-weight: 700;
        border-radius: 5px;
        box-shadow: 0px 2px #352E2E;
    }
    .btn-delete{
        background-color: #CA1A1A;
        border: 2px outset #CA1A1A;
        box-shadow: 1px 3px #322C2C;
        color: #fff;
        padding: 4px 15px;
        font-weight: 700;
        border-radius: 5px;
    }
    .select-text{
    	padding: 3px;
        border: 2px solid #747171;
        color: #380303;
        font-weight: 600;
    }
    .level, .btn-new, .btn-delete{
        margin-left: 10px;
        margin-right: 5px;
    }
</style>
<?php
$aryForm=$db->getRow("SELECT * FROM student WHERE school_id='".$_SESSION["admin"]["school_id"]."' and idno='".$_GET['id']."'");
?>
<link rel="stylesheet" href="<?php echo URL_ROOT; ?>js/jquery-ui.css">
<script src="<?php echo URL_ROOT; ?>js/jquery-1.10.2.js"></script>
<script src="<?php echo URL_ROOT; ?>js/jquery-ui.js"></script>
<script>
var add_tr='<tr id="row_1"><td ><input type="text" class="st-forminput" style="width:86%;" name="attr_month[]" /></td><td ><textarea type="text" class="st-forminput" style="width:86%;" name="attr_name[]" ></textarea></td><td><input type="text" class="st-forminput" style="width:90%;" name="attr_value[]" /></td><td><a class="delete" href="javascript:;">X</a></td></tr>';
$(document).ready(function(){
	$("#add").click(function(){
		$("#tbody").append($(add_tr));
	
		$('#tbody td a.delete').on('click',function() { 
			var rowCount = $('#tbody tr').length;
			if(rowCount<=1){
				//alert("This item cannot deleted !!!");
			}else{
				$(this).parent().parent().remove(); 
			}
		});	
	});
});
function fetchDetail(ids){
	var values=$(ids).val();
	 $.getJSON("ajax.php?type=getValByRecepit&id="+values, function(field){
		 //alert(field.month)
		$("#month").val(field.month)
		$("#name").val(field.name)
		$("#value").val(field.value)
    });
}
$(function() {
	$(".datepicker").each(function(index, element) {
        var d = new Date(); // for now
		datetext=d.getHours()+": "+d.getMinutes()+": "+d.getSeconds();
		$( this ).datepicker({
		  changeMonth: true,
		  changeYear: true,
		  showOn: "button",
		  buttonImage: "<?php echo URL_ROOT ?>js/images/calendar.gif",
		  buttonImageOnly: true,
		  buttonText: "Select date",
		  dateFormat: 'yy-mm-dd ',
		  onSelect: function(datetext){
			var d = new Date(); // for now
			datetext=datetext+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
			$(this).val(datetext);
		  }
		});
    }); 
});
</script>

<div style="width:100%;float:right;border:solid 2px;padding:5px;">
    <div style="width:100%;padding:5px;">
        <label style="color:crimson;font-weight:bold;font-size:18px;">
            Discount Percent: 
            <input type="text" id="disc_percent" onkeyup="getamount()" required style="width:80px" />
        </label>
        <label style="color:crimson;font-weight:bold;font-size:18px;">
            Discount Amount: 
            <input type="text" id="disc_amount" onkeyup="getamount()" required style="width:80px;" />
        </label>
        <label style="color:crimson;font-weight:bold;font-size:18px;">
            Discount Mode: 
            <!--<input type="text" id="disc_amount" onkeyup="getamount()" required style="border-radius:2px;" />-->
            <select id="disc_mode">
                <?php $aryList=$db->getRows("SELECT * FROM discount_mode ");
                    foreach($aryList as $clist){ ?>
                    <option><?php echo $clist["name"] ?></option>
                <?php } ?>
            </select>
        </label>
    </div>
    <table class="table" border="1" cellspacing="0" style="width:100%;">
        <tr style="text-align:left;">
            <th><input type="checkbox" id="checkboxa" onclick="checkAll()" />Months</th>
            <!--<th>Fee Heads</th>-->
            <th>
                <label style="border-right:solid 2px crimson;">
                    <input type="checkbox" id="tution" data-id="" data-name="tution" data-type="tution" onclick="checktution()" /> Tuition
                </label>
                <label style="border-right:solid 2px crimson;">
                    <input type="checkbox" id="bus" data-id="" data-name="bus" data-type="bus" onclick="checkbus()" /> Bus
                </label>
                <label>
                <?php   $extrafee = $db->getRows("select * from extrafee where idno='".$_GET['id']."' and session='".$_SESSION["admin"]["session"]."' and school_id='".$_SESSION["admin"]["school_id"]."' and type in (select id from extrafee_type where class='$aryForm[class]') group by type");
                        foreach($extrafee as $fee){
                            $name = $db->getVal("select type from extrafee_type where id='".$fee["type"]."' and class='$aryForm[class]' and session='".$_SESSION["admin"]["session"]."' ");
                            ?>
                            <label style="border-right:solid 2px crimson;padding-right:5px;"><input type="checkbox" id="<?php echo $fee['type']; ?>" data-id="<?php echo $fee['type']; ?>" data-name="<?php echo $name; ?>" data-type="extra" onclick="checkextra(<?php echo $fee['type']; ?>)" /> <?php echo $name; ?></label>
                        <?php   }   ?>
                </label>

                <label>
                    <?php $otherfee = $db->getRows("select * from otherfee_structure where session='".$_SESSION["admin"]["session"]."' and class='".$aryForm["class"]."' and (otype='' OR otype='".$aryForm["stype"]."' OR otype='".$_GET["id"]."') group by name");
                          foreach($otherfee as $other){
                            $checkother = $db->getVal("select sum(amount) from reff_receipt where type='$other[name]' and idno='$_GET[id]' and session='".$_SESSION["admin"]["session"]."' ");
                                if(!$checkother){ ?>
                                <label style="border-right:solid 2px crimson;padding-right:5px;"><input type="checkbox" id="<?php echo $other['id']; ?>" data-id="<?php echo $other['id']; ?>" data-name="<?php echo $other['name']; ?>" data-type="otherfee" onclick="checkother(<?php echo $other['id']; ?>)" /> <?php echo $other['name']; ?></label>
                            <?php    }
                            } ?>
                </label>

            </th>
        </tr>
        <?php 	//for($i=1;$i<=12;$i++){
                    $allmonths = $db->getRows("select * from months");
                        foreach($allmonths as $mn){
				            $i = $mn['month'];
						  //if($i<=9){
								// $newDate=date("Y")."-".($i+3)."-1";
						  //}
						  //else{
								// $newDate=date("Y")."-".($i-9)."-1";
						  //}
						  ?>
               <tr>
                   <td>
                       <input type="checkbox" class="checkboxes allmonths" id="month<?php echo $i; ?>" onclick="monthlycheck(<?php echo $i; ?>)" />
                       <?php echo $mn['name']; //date("F",strtotime($newDate)); ?>
                   </td>

                   <td>
                    <label>
                        <?php $tuition = $db->getRow("select i$i, ip$i from installment where idno='$_GET[id]' and session='".$_SESSION["admin"]["session"]."' ");
                                if($tuition["i$i"]>0 && $tuition["ip$i"]==""){ ?>
                                <label style="border-right:solid 2px crimson;padding-right:5px;"><input type="checkbox" data-id="" data-name="tution" data-type="tution" value="<?php echo $tuition["i$i"]; ?>" class="checkboxes month<?php echo $i; ?> tution" onclick="getamount()" /> Tuition</label>
                        <?php   }  ?>
                       </label>

                       <label>
                        <?php $bus = $db->getRow("select b$i, bp$i from installment where idno='$_GET[id]' and session='".$_SESSION["admin"]["session"]."' and status='1' ");
                                if($bus["b$i"] > 0 && $bus["bp$i"] == ""){ ?>
                                <label style="border-right:solid 2px crimson;padding-right:5px;"><input type="checkbox" data-id="" data-name="bus" data-type="bus" value="<?php echo $bus["b$i"]; ?>" class="checkboxes month<?php echo $i; ?> bus" onclick="getamount()" /> Bus</label>
                        <?php   }  ?>
                       </label>

                       <label>
                        <?php 	$extrafee = $db->getRows("select * from extrafee where pid='p$i' and idno='".$_GET['id']."' and session='".$_SESSION["admin"]["session"]."' and school_id='".$_SESSION["admin"]["school_id"]."' and type in (select id from extrafee_type where class='$aryForm[class]')");
                                foreach($extrafee as $fee){
                                if($fee["fee"] > 0 && $fee["pay"] == "0"){
                                $name = $db->getVal("select type from extrafee_type where id='".$fee["type"]."' and class='$aryForm[class]' and session='".$_SESSION["admin"]["session"]."' ");
                                ?>
                                <label style="border-right:solid 2px crimson;padding-right:5px;"><input type="checkbox" data-id="<?php echo $fee['type']; ?>" data-name="<?php echo $name; ?>" data-type="extra" value="<?php echo $fee['fee']; ?>" class="checkboxes month<?php echo $i; ?> extra<?php echo $fee['type']; ?>" onclick="getamount()" /> <?php echo $name; ?></label>
                            <?php   }
                            } ?>
                       </label>

                        <label>
                        <?php $otherfee = $db->getRows("select * from otherfee_structure where month='$i' and session='".$_SESSION["admin"]["session"]."' and class='".$aryForm["class"]."' and (otype='' OR otype='".$aryForm["stype"]."' OR otype='".$_GET["id"]."')");
                                foreach($otherfee as $other){
                                    $checkother = $db->getVal("select sum(amount) from reff_receipt where type='$other[name]' and idno='$_GET[id]' and session='".$_SESSION["admin"]["session"]."' ");
                                    if(!$checkother){ ?>
                                    <label style="border-right:solid 2px crimson;padding-right:5px;"><input type="checkbox" data-id="<?php echo $other['id']; ?>" data-name="<?php echo $other['name']; ?>" data-type="otherfee" value="<?php echo $other['fee']; ?>" class="checkboxes month<?php echo $i; ?> other<?php echo $other['id']; ?>" onclick="getamount()" /> <?php echo $other['name']; ?></label>
                                <?php    }
                            } ?>
                        </label>

                   </td>

               </tr> 
		<?php		}
		?>
		
		<tr>
		    <td style="color:teal;font-size:25px;font-weight:bold;" colspan="2">Total Fee: 
		    <!--</td>-->
		    <!--<td style="color:red;font-size:25px;font-weight:bold;">-->
		        <label id="totalfee">0</label> <span style="color:crimson;">|</span>
		        Discount Amount: 
		        <label id="discountfee">0</label> <span style="color:crimson;">|</span>
                <?php 
                $makediscountpermission = $db->getVal("select id from tbl_privilages where roll_id='".$_SESSION["admin"]["roll"]."' and page_name='MakeDiscount' and a='1' ");
                if($makediscountpermission){ ?>
    		        <button onclick="save()" style="margin-left:100px;background:teal;color:white;border:none;cursor:pointer;padding:5px;width:80px;font-size:17px;">Save</button>
		        <?php } ?>
		        
		    </td>
		</tr>
    </table>
</div>

<br>

<div style="width:100%;float:left;border:solid 2px;">
    <table border="1" cellspacing="0" style="width:100%;">
        <tr>
            <th>S.No.</th>
            <!--<th>Discount Detail</th>-->
            <th>Total Discount Amount</th>
            <th>Discount Mode</th>
            <th>Disc. Type</th>
            <th>Disc. Value</th>
            <th>Date</th>
            <th>Action</th>
        </tr>
        
        <?php $discounted = $db->getRows("SELECT *, sum(discount_amount) as amount FROM discount_detail WHERE idno='$_GET[id]' GROUP by discount_id");
            foreach($discounted as $row){$j++; ?>
            <tr>
                <td><?php echo $j; ?></td>
                <td><?php echo number_format($row['amount'],2); ?></td>
                <td><?php echo $row['disc_mode']; ?></td>
                <td><?php echo $row['disc_type']; ?></td>
                <td><?php echo $row['disc_amt']; if($row['disc_type']=="percent")echo " %"; ?></td>
                <td><?php echo date('d-m-Y h:i:s', strtotime($row['date'])); ?></td>
                <td>
                    <?php
                    $resetdiscountpermission = $db->getVal("select id from tbl_privilages where roll_id='".$_SESSION["admin"]["roll"]."' and page_name='ResetDiscount' and a='1' ");
                    if($resetdiscountpermission){ ?>
                    <button onclick="resetdiscount(<?php echo $row['discount_id']; ?>)" style="background:red;color:white;border:none;cursor:pointer;box-shadow:0px 0px 5px #333;">Reset</button>
                    <?php } ?>
                </td>
            </tr>
            <?php }
        ?>
        
    </table>
</div>

<script type="text/javascript">
	// update_back_dues start--------
function update(id){
	//alert(id);
	var sta = $('#status'+id).val();

    $.post( "ajax.php", {type: "cheque_status" ,
								cheque_s: sta,
								id:id} , function( data ) {
									alert(data);
		});
}

function resetdiscount(disid){
       $.post("ajax.php", { type: "resetdiscount", idno:<?php echo $_GET['id']; ?>, discount_id: disid}, function( data ) {
               alert(data);
                location.reload();
                // alert(data);
                // $('#studentList').html(data);
            });
}
// update_back_dues end
</script>