<?php
include("db.php");
header('Content-Type: application/json');

$decoded = base64_decode($_GET['token']);
$decoded = str_replace("print/?page_id=recepitNew_hostel&","", $decoded);

$array = explode("&", $decoded);

$d1 = array();

foreach($array as $key=>$val){
    $d = explode("=",$val);
    $d1[$d[0]] = $d[1];
}

$_REQUEST = $_GET = $d1;

$_SESSION["admin"]["session"] = $_REQUEST["session"];
$_SESSION["admin"]["added_by"] = $_REQUEST["uid"];
$_SESSION["admin"]["school_id"] = 1;

// Receipt Code Starts

$feemonth = explode(",",$_GET["month"]);

$fmonth = $feemonth[0];
$allmonths = [];
for($jk = $fmonth; $jk <= $_GET['install']; $jk++){
    $allmonths[] = $jk;
}
  
$_REQUEST["month"] = implode(",",$allmonths);
$_GET["month"] = implode(",",$allmonths);
$rrid=explode("-",$_GET["rrid"]);
$rr=array();

for($i=1;$i<count($rrid);$i++){$rr[]=$rrid[$i];}
$newrrid=implode("-",$rr);
$rridary=$rr;

foreach($_REQUEST as $key=>$val){
	$fess=explode("-",$key);
	
	if($fess[0]=="fee" && $val!=0){$i++;
		$feeData=$fess[1];
		$data[$feeData]=$val;
	}elseif($fess[0]=="extrafee" && $val!=0){$i++;
		$fe=explode("`",$fess[1]);
		$feeDat=$fe[0];
			$name1[]= $fe[0];
		if(array_key_exists($feeDat,$data))
		{
			$data[$feeDat]=$data[$feeDat]+$val;
			//echo $data[$feeDat];
		}
		else
		{
			 $data[$feeDat]=$val;
		}
		
	}
}

$data1=$data;

    $aryForm=$db->getRow("SELECT * FROM student WHERE  school_id='".$_SESSION["admin"]["school_id"]."' and idno='".$_GET['idno']."'");

    $idno=$aryForm["idno"];
    $cls=$aryForm["class"];
    $type=$aryForm["htype"];

    $check_other=implode(",",$rr);

    if(isset($_GET['Months']))  $tm= explode(',',$_GET['Months']);
    if(isset($_REQUEST["month"]))  $tm= explode(',',$_REQUEST["month"]);
    $tm = array_filter(array_unique($tm));

    $feename=array();
    foreach($data1 as $key=>$val){
        $feename[]=trim($key);
    }

// Hostel start

    foreach($tm as $month){
        $inspaid = $db->getVal("select count(id) from reff_receipt where idno='".$idno."' and type='hostelfee' and inst_id='$month' and session='".$_SESSION["admin"]["session"]."'  ");
        if($inspaid > 0){
            $temp = $db->getVal("SELECT COALESCE(sum(i".$month."),0)  as result from hostelinstallment  WHERE idno='$idno'   and session='".$_SESSION["admin"]["session"]."' ");    
            $paid = $db->getVal("SELECT COALESCE(sum(amount),0)  as result from reff_receipt where idno='".$idno."' and type='hostelfee' and inst_id='$month' and session='".$_SESSION["admin"]["session"]."' and id not in ($check_other) ");
            $total += $temp-$paid;

        } else {
            $total+=$db->getVal("SELECT COALESCE(sum(i".$month."),0)  as result from hostelinstallment  WHERE idno='$idno'   and session='".$_SESSION["admin"]["session"]."' ");
        }
    }

    if($total>0){
        if(!in_array('hostel',$feename) ){ 
            if(!in_array('Hostel_Fees',$feename)) {
     	 		if(isset($_REQUEST['month'])){
            		$pu[hostel]=0;
            		$data1=array_merge($data1,$pu );
			    }
            }
        }
    }

    $to_pay[hostel_total]=$total;

// Hostel end


// other fee start-----------
    if($type!=""){
  $om=implode(',',$tm);
  $other_fee_name= $db->getRows("SELECT id,fee, name,month from hostel_otherfee_structure  WHERE class='$cls'  and (otype='".$idno."' or otype='$type' or otype='') and month in ($om) and session='".$_SESSION["admin"]["session"]."' ");

  foreach($other_fee_name as $other_fee_name1){
	
	$ins_id=$db->getVal("SELECT sum(amount) from reff_receipt  WHERE  idno='".$idno."' and id in ($check_other) and type = '".$other_fee_name1[name]."' and session='".$_SESSION["admin"]["session"]."' ");

	$o_name=$other_fee_name1[name];
	$rem=$o_name.'_Remaining';
	$dis=$db->getVal("SELECT COALESCE(sum(discount),0) from hostelotherfee_discount WHERE other_id='".$other_fee_name1[id]."' and class='$cls' and idno='".$idno."' and month ='".$other_fee_name1[month]."' and session='".$_SESSION["admin"]["session"]."'  ");

	if(!empty($data1[$rem])){
    	$tmp=$data1[$rem];
        $exy_other[$rem]=$other_fee_name1[fee]-$ins_id-$dis;
	}else{
	  $o_name = str_replace(' ', '_', $o_name);
		$exy_other[$o_name]=$other_fee_name1[fee]-$ins_id-$dis;
	}

  }
}
 // other fee end----------

 //***************************************************

// section  for 0 pay   start..............

// other fee start;;;;;;;;;;;;;;;;;;
    if($type!=""){
    $om=implode(',',$tm);
    $other_fee_name= $db->getRows("SELECT id,fee, name from hostel_otherfee_structure  WHERE class='$cls'  and (otype='".$idno."' or otype='$type' or otype='') and month in ($om) and session='".$_SESSION["admin"]["session"]."' ");
    $i=0;
    foreach($other_fee_name as $other_fee_name6){
        $rem=$other_fee_name6[name].'_Remaining';
        $rem1=$other_fee_name6[name];

    	if(!empty($data1[$rem])){		
    	  	$i++;
    	}

    }

    if($i<1){
        foreach ($other_fee_name as $other_fee_name77){

        $ins_id44=$db->getVal("SELECT sum(amount) from reff_receipt  WHERE  idno='".$idno."' and id not in ($check_other) and type = '".$other_fee_name77[name]."' and session='".$_SESSION["admin"]["session"]."' ");

        $nam=$other_fee_name77[name];
        $nam = str_replace(' ', '_', $nam);

        $other_pay_zero=$other_fee_name77[fee]- $ins_id44;
        $ins_id=$db->getVal("SELECT ifnull(GROUP_CONCAT(inst_id),'' ) from reff_receipt  WHERE  idno='".$idno."' and id  in ($check_other) and type = '".$other_fee_name77[name]."' and session='".$_SESSION["admin"]["session"]."' ");

        $dis=$db->getVal("SELECT COALESCE(sum(discount),0) from hostelotherfee_discount WHERE other_id='".$other_fee_name77[id]."' and class='$cls' and idno='".$idno."' and session='".$_SESSION["admin"]["session"]."'  ");

        $exy_other[$nam]=$other_pay_zero-$dis;

        if(!empty($other_pay_zero)){
            if(!in_array($nam,$feename)) {
    			if(isset($_REQUEST['month'])){
	    		    if(($other_pay_zero-$dis) > 0){
                        $exy_12[$nam]=0;
                        $data1=array_merge($data1,$exy_12 );
			        }
			    }
            }
        }

        }
    }
}
// other fee end;;;;;;;;;;;;;;;;;;;;;

 
// section  for 0 pay end ..............

    // All Discount Fee starts

    $total_tution_discount = 0;
    $total_other_discount = 0;
    $overAllDiscount = 0;

    // Tution Discount
    $x = 0;
    foreach($tm as $m){ $x++;
        $total_tution_discount+= $db->getVal(" select sum(discount_amount) from discount_detail where idno='".$_GET["idno"]."' and installment='i$m' and type='hostel' ");
    }

    // Otherfee Discount
    $otherdis = $db->getRows("select * from discount_detail where idno='".$_GET["idno"]."' and type='hostelother' ");
    foreach($otherdis as $other){
        $other_id = $other['other_id'];
        $otherfee = $db->getRow("select * from hostel_otherfee_structure where id='$other_id' and class='".$_GET["class"]."' and session='".$_SESSION["admin"]["session"]."' ");
        if (in_array("$otherfee[month]", $tm)){
            $total_other_discount+=$other['discount_amount'];
        }
    }


    $overAllDiscount = $total_tution_discount+$total_other_discount;

    // All Discount Fee ends

    $topay1=0;
    foreach($data1 as $key=>$val){
        if($key=="hostel" or $key=="Hostel_Fees" ){ $topay1+=$to_pay[hostel_total]; }
		    else{
		        if($exy_other[$key]==""){
		            $topay1+=$val;
		        } else {
    		        $topay1+=$exy_other[$key];
		        }
		    }
    }

    $i=0;$tdis=0;$bdis=0;$odis=0;$total_dis=0;

    $topayAry = array();

    foreach($data1 as $key=>$val){
    	$fess=explode("-",$key);
    	{	
    		$i++;
    		$feeData=$fess[1]; 
    		$data1[$feeData]=$val;

            if($key=="hostel" or $key=="Hostel_Fees" ){ $topay+=$to_pay[hostel_total]; $topayAry[$key]=$to_pay[hostel_total];}
    	    else{
    	        if($exy_other[$key]==""){
    	            $topay+=$val;
    	            $topayAry[$key]=$val;
    	        } else {
    		        $topay+=$exy_other[$key];  
    		        $topayAry[$key]=$exy_other[$key];
    	        }
    	    }
    
    	}
    }

    $id=$db->getval("select max(id) from hostel_receipt where school_id='".$_SESSION["admin"]["school_id"]."' and type='".$_REQUEST["type"]."'")+1;

    $isAlreadyEntry=$db->getVal("select id from hostel_receipt where idno='".$_GET["idno"]."' and detail='".json_encode($data)."' and amount='".$_GET["amount"]."' and session='".$_SESSION["admin"]["session"]."' and class='".$_GET["class"]."' and school_id='".$_SESSION["admin"]["school_id"]."' and type='".$_GET["type"]."' and install='".$_GET["install"]."' and paytype='overallFee' and rrid='".$newrrid."'");

    $status = 0;
    $flg = 0;
    if($isAlreadyEntry == ""){
        $saveAry = array(
                "id"            =>  $id,
                "idno"          =>  $idno,
                "udate"         =>  $_GET['udate'],
                "topay"         =>  json_encode($topayAry),
                "detail"        =>  json_encode($data),
                "amount"        =>  $_GET["amount"],
                "discount"      =>  $overAllDiscount,
                "payment_mode"  =>  "Cash",
                "remaining"     =>  $topay-$_GET["amount"],
                "total"         =>  $topay,
                "Months"        =>  $_REQUEST["month"],
                "session"       =>  $_REQUEST["session"],
                "class"         =>  $_GET["class"],
                "type"          =>  $_GET["type"],
                "install"       =>  $_GET["install"],
                "paytype"       =>  "overallFee",
                "school_id"     =>  "1",
                "added_by"      =>  $_REQUEST['uid'],
                "rrid"          =>  $newrrid
            );
        $flg = $db->insertAry("hostel_receipt", $saveAry);
        if($flg>0){
            $status = 1;
            $flg = $id;
        }
    }

    $array = array("status"=>$status, "rid"=>$flg );

    echo json_encode($array);

?>