<?php
include('../include/config.php');
//error_reporting(0);
session_start();
$iduser=$_SESSION['user_idd'];
$date = new DateTime("now", new DateTimeZone('Africa/Nairobi') );
$timenow=$date->format('Y-m-d H:i:s');
$timenow2=$date->format('Y-m-d');
$month=$date->format('M');

$fid='';

function generatecode() {
	$chars = "003232303232023232023456789";
	srand((double)microtime()*1000000);
	$i = 0;
	$pass = '' ;
	while ($i <= 5) {

		$num = rand() % 33;
		$tmp = substr($chars, $num, 1);
		$pass = $pass . $tmp;
		$i++;
	}
	return $pass;
}

$fid=generatecode();
$fid='BK_'.$fid;


if(isset($_POST['trm']))
{
$trm=addslashes($_POST['trm']);
$yr=addslashes($_POST['yr']);

$sqll=mysqli_query($con,"select * from Fees2 where Year='$yr' AND Term='$trm'");
$num=mysqli_fetch_array($sqll);
if($num>0)
{
  echo 'Sorry you have already created fee period for '.$trm.' '.$yr;  
}else
{
    
$quer=mysqli_query($con,"select * from Fees");
$num=mysqli_fetch_array($quer);
if($num>0)
{
 $bo='';  
    
$queryy=mysqli_query($con,"select * from bofee");
while($row=mysqli_fetch_array($queryy))
{
$bo=htmlentities($row['Fee']);
}

$queryyy=mysqli_query($con,"select * from motifee");
while($row=mysqli_fetch_array($queryyy))
{
$mo=htmlentities($row['Amount']);
}

//Get auto increment No.
$queryyy=mysqli_query($con,"select * from Fees2 order BY id DESC LIMIT 1");
while($row=mysqli_fetch_array($queryyy))
{
$auto=htmlentities($row['count']);
}

$auto=$auto+1;

$sq=mysqli_query($con,"UPDATE pupils SET Year='$yr',Term='$trm',Cod='$fid',AutoNo='$auto'");

$sql=mysqli_query($con,"INSERT INTO Fees2(Year,Term,Grad,pid,Boarder,TutionF,Cod,count) SELECT pupils.Year,pupils.Term,pupils.Claz,pupils.count,pupils.Boarder,Fees.Tution,pupils.Cod,pupils.AutoNo from pupils LEFT join Fees ON Fees.Grade=pupils.Claz WHERE pupils.Status='Active'");

if($sql)
{
//$sqq=mysqli_query($con,"UPDATE Fees2 SET BoF='$bo' where Boarder='Boarder' AND Year='$yr' AND Term='$trm'");

$sqqq=mysqli_query($con,"UPDATE Fees2 SET MotF='$mo' where  Year='$yr' AND Term='$trm' AND Grad !='PP2' AND Grad !='PP1' AND Grad !='BABY CLASS'");

$msg='created new fee payement period: ' .$trm.' '.$yr;
$sql3=mysqli_query($con,"INSERT INTO activity(user,Action,Tim,Dat,shortmsg,Month)values('$iduser','$msg','$timenow','$timenow2','save','$month')");

echo "saved";
}else
{
echo 'Unable to save';
}
}else
{
 echo 'You must set Tution fees first for all classes';  
}
}
}

?>