<?php

error_reporting(E_ERROR | E_PARSE);

$servername = "localhost";
$username = "savarna_bps";
$password = "techno@123";
$database = "savarna_bps";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);
 
// Check connection
if ($conn->connect_error) {
    echo "Connection Failed.";
}
else {
    // echo "Connected successfully";
}


$sql = "SELECT * FROM fine_setting";
$result = $conn->query($sql);

$currentdate = date('Y-m-d');  

if ($result->num_rows > 0) {
  while($row = $result->fetch_assoc()) {
 
    $otherfee = $conn->query("select * from otherfee_structure where name='$row[fee]' and class='$row[class]' and session='$row[session]' ");
    
    foreach($otherfee as $fee){$paid = 0;

        // $checkpaid = $conn->query("select id from reff_receipt where idno='$fee[otype]' and type='$fee[name]' and session='$row[session]' ");

        $checkpaid = $conn->query("select id from reff_receipt where idno='$fee[otype]' and type='fee' and inst_id='$fee[month]' and session='$row[session]' ");

        if ($checkpaid->num_rows > 0) {
            $paid = 1;
        }else {
            $checkdiscount = $conn->query("select SUM(discount) as dis from otherfee_discount where idno='$fee[otype]' and other_id='$fee[id]' and class='$row[class]' and session='$row[session]' and discount!='' ");
            if ($checkdiscount->num_rows > 0) {

                $totaldiscount = 0;
                foreach($checkdiscount as $dis){
                    $totaldiscount+=$dis['dis'];
                }
                if($totaldiscount >= $fee['fee']){
                    $paid = 1;
                }
            }
        }

        $newfee = $fee['fee']+$row['amount'];

        if(($currentdate >= $row['fdate']) && ($currentdate <= $row['tdate']) && $paid==0 ){
            $update = $conn->query("UPDATE otherfee_structure SET fee='$newfee' WHERE name='$row[fee]' and class='$row[class]' and otype='$fee[otype]' and session='$row[session]' ");
        }

    }


    // $newfee = $other['fee']+$row['amount']; 

    // if(($currentdate >= $row['fdate']) && ($currentdate <= $row['tdate']) ){
        // $update = $conn->query("UPDATE otherfee_structure SET fee='$newfee' WHERE name='$row[fee]' and class='$row[class]' and session='$row[session]' ");
    // }
 
  }
} else {
  echo "0 results";
}

?>