#!/usr/bin/perl
#  Copyright 2001-2024 Leslie Richardson

#  This file is part of Open Admin for Schools.

#  Open Admin for Schools is free software; you can redistribute it 
#  and/or modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2 of 
#  the License, or (at your option) any later version.


my %lex = ('Assess Fees' => 'Assess Fees',
	   'Grade' => 'Grade',
	   'Homeroom' => 'Homeroom',
	   'Main' => 'Main',
	   'Fee' => 'Fee',
	   'Fees' => 'Fees',
	   'Subject-Section' => 'Subject-Section',
	   'Name' => 'Name',
	   'Description' => 'Description',
	   'Amount' => 'Amount',
	   'Group' => 'Group',
	   'Predefined' => 'Predefined',
	   'New' => 'New',
	   'Date' => 'Date',
	   'Create New' => 'Create New',
	   'Continue' => 'Continue',
	   'Blank=All' => 'Blank=All',
	   'Student' => 'Student',
	   'Select' => 'Select',
	   'Checked' => 'Checked',
	   'Chk' => 'Chk',
	   'Predefined Fees' => 'Predefined Fees',
	   'Name' => 'Name',
	   'Description' => 'Description',
	   'Amount' => 'Amount',
	   'Select' => 'Select',
	   'All' => 'All',
	   'Student Number' => 'Student Number',
	   'Error' => 'Error',
	   'Assessment' => 'Assessment',
	   'Charges' => 'Charges',
	   'Confirm' => 'Confirm',
	   'Transaction' => 'Transaction',
	   'Data' => 'Data',
	   'Save' => 'Save',
	   'Record(s) Stored' => 'Record(s) Stored',
	   'Students' => 'Students',
	   'Not Found' => 'Not Found',

	   );

my $self = 'assessfees.pl';
my $rounding = 2;

use CGI;
use DBI;
use Number::Format qw(:all);

eval require "../../etc/admin.conf";
if ( $@ ) {
    print $lex{Error}. " $@<br>\n";
    die $lex{Error}. " $@\n";
}

eval require "../../etc/fees.conf";
if ( $@ ) {
    print $lex{Error}. " $@<br>\n";
    die $lex{Error}. " $@\n";
}


# calc current date
my @tim = localtime(time);
my $year = @tim[5] + 1900;
my $month = @tim[4] + 1;
my $day = @tim[3];
my $currdate = "$year-$month-$day";

my $q = new CGI;
print $q->header( -charset, $charset ); 
my %arr = $q->Vars;

my $checked = $arr{checked};
delete $arr{checked};

my $dsn = "DBI:$dbtype:dbname=$dbase";
my $dbh = DBI->connect($dsn,$user,$password);



# Show page Header
my $title = "$lex{'Assess Fees'}";

print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};
print qq{$chartype\n</head><body>\n};

print qq{[ <a href="$homepage">$lex{Main}</a> |\n};
print qq{<a href="$feespage">$lex{Fees}</a> ]\n};

print qq{<h1>$title</h1>\n};

if ( not $arr{page} ) {
    showStartPage();

} elsif ( $arr{page} == 1 ) { # Set Basic Transaction Parameters
    delete $arr{page};
    if ( $arr{assesstype} eq $lex{'Create New'} ) {
	createNew();
    } elsif ( $arr{assesstype} eq $lex{'Predefined Fees'} ) {
	usePredefined();
    } else {
	print qq{<h3>$lex{'Not Found'}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

} elsif ( $arr{page} == 2 ) {  # Select students, confirm taxes
    delete $arr{page};
    chooseStudents();

} elsif ( $arr{page} == 3 ) { # Show confirmation page
    delete $arr{page};
    showConfirmation();

} elsif ( $arr{page} == 4 ) { # Write records to fees journal
    delete $arr{page};
    writeRecords();

} else {
    # Do nothing at all...
}


#-------------------
sub showConfirmation {
#-------------------

    #foreach my $key ( sort keys %arr) { print qq{K:$key V:$arr{$key}<br>\n}; }

    print qq{<h1>$lex{Confirm} $lex{Charges}</h1>\n};

    # Setup the form and start of table.
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="4">\n};
    print qq{<table cellpadding="6" border="1" cellspacing="0">\n};
    print qq{<tr><th style="text-align:center;">$lex{Transaction} $lex{Data}</th></tr>\n};

    foreach my $key ( keys %arr) { 
	print qq{<input type="hidden" name="$key" value="$arr{$key}">\n};
    }

    # Show Confirmation of these 4 values
    my $amount = $arr{amount};
    my $date = $arr{date};
    my $description = $arr{description};
    my $name = $arr{name};

    delete $arr{name};
    delete $arr{description};
    delete $arr{date};
    delete $arr{amount};
     
    for my $i ( 1..4 ) { 
	my $name = 'tax'. $i;
	delete $arr{$name};
    }


    print qq{<tr><td class="la"><b>$lex{Name}</b> $name</td></tr>\n};
    print qq{<tr><td class="la"><b>$lex{Description}</b> $description</td></tr>\n};
    print qq{<tr><td class="la"><b>$lex{Date}</b> $date</td></tr>\n};
    print qq{<tr><td class="la"><b>$lex{Amount}</b> $amount</td></tr>\n};


    my $sth = $dbh->prepare("select lastname, firstname from studentall where studnum = ?");

    print qq{<tr><th>$lex{Students}</th></tr>\n};

    # Now confirmation of students.
    foreach my $studnum ( sort keys %arr) { 

	$sth->execute( $studnum );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	my ( $lastname, $firstname ) = $sth->fetchrow;

	print qq{<tr><td style="text-align:left;"><b>$lastname</b>, $firstname ($studnum)</td></tr>\n};
    }
    
    print qq{<tr><td class="cn">};
    print qq{<input type="submit" value="$lex{Save}"></td></tr>\n};

    print qq{</table></form></body></html>\n};

    exit;

}


#----------------
sub showStartPage {
#----------------

    # Setup the form and start of table.
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};

    print qq{<input type="submit" name="assesstype" value="$lex{'Create New'}"> \n};
    print qq{<input type="submit" name="assesstype" value="$lex{'Predefined Fees'}"> \n};

    print qq{</form>\n};
    print qq{</body></html>\n};

    exit;

}



#----------------
sub usePredefined {
#----------------

    print qq{<h1>$lex{Select} $lex{'Predefined Fees'}</h1>\n};
    print qq{<table cellspacing="0" cellpadding="3" border="1" style="margin: 0em 3em;">\n};
    print qq{<tr><th>$lex{Name}</th><th>$lex{Description}</th><th>$lex{Amount}</th>};
    print qq{<th>$lex{Group}</th><th>$lex{Select}</th></tr>\n};

    # First load and display the predefined ones...
    my $sth = $dbh->prepare("select * from fees_predefined order by name");
    $sth->execute;
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }

    my %groups = ( 'grade' => $lex{Grade}, 'homeroom' =>
     $lex{Homeroom}, 'studnum' => $lex{'Student Number'} );


    # Loop through all predefined values.
    while ( my ($id, $name, $description, $amount, $discount,
    $tax1_flag, $tax2_flag, $tax3_flag, $tax4_flag, $group_name,
    $group_value ) = $sth->fetchrow ) {

	my $gname = $groups{$group_name};
	$gname .= " - $group_value";


	print qq{<tr><td>$name</td><td>$description</td><td>$amount</td><td>$gname</td>\n};
	print qq{<td>};

	print qq{<form action="$self" method="post">\n};
	print qq{<input type="hidden" name="page" value="2">\n};
	print qq{<input type="hidden" name="predefined" value="$id">\n};
	print qq{<input type="submit" value="$lex{Select}"> \n};

	print $lex{Chk};
	print qq{<input type="checkbox" name="checked" value="checked">\n};

	print qq{</form></td></tr>\n};


    }

    print qq{</table></body></html>\n};
    exit;

    
} # end of usePredefined;



#------------
sub createNew { # Create a New Assessment from scratch.
#------------

    # Setup the form and start of table.
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="2">\n};
    print qq{<table cellpadding="3" border="0" cellspacing="0">\n};

    print qq{<tr><td class="bra">$lex{Date}</td><td class="la">\n};
    print qq{<input type="text" name="date" size="10" value="$currdate">\n};
    print qq{</td></tr>\n};

    print qq{<tr><td class="bra">$lex{Fee} $lex{Name}</td><td class="la">\n};
    print qq{<input type="text" name="name" size="16">\n};
    print qq{</td></tr>\n};

    print qq{<tr><td class="bra">$lex{Description}</td><td class="la">\n};
    print qq{<textarea name="description" rows="5" cols="50"></textarea>\n};
    print qq{</td></tr>\n};

    print qq{<tr><td class="bra">$lex{Amount}</td><td class="la">\n};
    print qq{<input type="text" name="amount" size="6">\n};
    print qq{</td></tr>\n};


    # Tax values from $f_Tax1, $f_Tax2, etc.
    for my $i (1..4) {
	my $taxname = 'f_Tax'. $i;
	if ( $$taxname{'rate'} ) {
	    my $fieldname = 'tax'. $i. '_flag';
	    print qq{<tr><td class="bra">$$taxname{'name'}</td><td class="la">\n};
	    print qq{<input type="checkbox" name="$fieldname" value="1">\n};
	    print qq{</td></tr>\n};
	}
    }

    print qq{<tr><td class="bra">$lex{Group}</td><td class="la">\n};
    print qq{<select name="group_name"><option></option>\n};
    print qq{<option>$lex{Grade}</option>\n};
    print qq{<option>$lex{Homeroom}</option>\n};

    # Not Used
    #print qq{<option>$lex{'Subject-Section'} (subjsec)</option>\n};
    #print qq{<option>$lex{'Student Number'} (subjsec)</option>\n};

    print qq{</select> <input type="text" name="group_value" size="6"> };
    print qq{$lex{'Blank=All'}</td></tr>\n};

    print qq{<tr><td class="bra">$lex{Checked}</td><td class="la">\n};
    print qq{<input type="checkbox" name="checked" value="checked" checked>\n};
    print qq{</td></tr>\n};


    # Print Submit Row
    print qq{<tr><td colspan="4" class="cn">};
    print qq{<input type="submit" value="$lex{Continue}"></td></tr>\n};
    
    print qq{</table></form></body></html>\n};

    exit;

}



#-----------------
sub chooseStudents { # Choose students to add assessments for.
#-----------------

    # foreach my $key ( sort keys %arr) { print qq{K:$key V:$arr{$key}<br>\n}; }

    if ( $arr{predefined} ) {  # We are using predefined values for transaction

	my $sth = $dbh->prepare("select * from fees_predefined where id = ?");
	$sth->execute( $arr{predefined} );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }

	( $id, $arr{name}, $arr{description}, $arr{amount}, $discount,
	  $arr{tax1_flag}, $arr{tax2_flag}, $arr{tax3_flag},
	  $arr{tax4_flag}, $arr{group_name}, $arr{group_value} ) = $sth->fetchrow;
	# Note: $id, $discount not in %arr hash.
	delete $arr{predefined};

    }


    # Setup the form and start of table.
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="3">\n};
    print qq{<input type="hidden" name="name" value="$arr{name}">\n};
    print qq{<input type="hidden" name="description" value="$arr{description}">\n};
    print qq{<input type="hidden" name="amount" value="$arr{amount}">\n};
    print qq{<table cellpadding="3" border="1" cellspacing="0">\n};

    # Show transaction information
    if ( not exists $arr{date} ) {
	$arr{date} = $currdate;
    }

    print qq{<tr><td class="bra">$lex{Date}</td><td class="la">\n};
    print qq{<input type="text" name="date" value="$arr{date}"></td></tr>\n};

    print qq{<tr><td class="bra">$lex{Fee} $lex{Name}</td><td class="la">\n};
    print qq{$arr{name}</td></tr>\n};

    print qq{<tr><td class="bra">$lex{Description}</td><td class="la">\n};
    print qq{$arr{description}</td></tr>\n};

     my $amount = format_number($arr{amount}, $rounding, $rounding );
    print qq{<tr><td class="bra">$lex{Amount}</td><td class="la">\n};
    print qq{$amount</td></tr>\n};

    for my $i ( 1..4 ) {
	my $fieldname = 'tax'. $i. '_flag';
        my $taxname = 'f_Tax'. $i;
	if ( $arr{$fieldname} ) {

	    my $taxrate = $$taxname{rate};
	    my $taxamount = format_number( ($amount * $taxrate ), $rounding, $rounding);

	    print qq{<tr><td class="bra">$$taxname{'name'}</td><td class="la">\n};
	    print qq{$taxamount ($amount x $taxrate)\n};
	    print qq{<input type="hidden" name="tax$i" value="$taxamount">\n};
	    print qq{</td></tr>\n};
	}
    }

    # separator
    print qq{<tr style="background-color:black;"><td colspan="2"></td></tr>\n};

    print qq{<tr><th colspan="2"><input type="submit" value="};
    print qq{$lex{Continue}"></td></tr>\n};
    print qq{<tr><th>$lex{Student}</th><th>$lex{Select}</th></tr>\n};


    # Select students, sorted by lastname, firstname,
    my $select;
    if ( $arr{group_name} ) {
	my @values = (split / /, $arr{group_value});
	if ( @values ) {
	    $select = 'where ';
	    $first = 1;
	    foreach my $value ( @values ) {
		$value = $dbh->quote( $value );
		if ( not $first ) { $select .= ' or '; }
		$select .= "$arr{group_name} = $value ";
		$first = 0;
	    }
	}

    }

    #if ($select) { print qq{Select: $select<br>\n"; }
	

    my $sth = $dbh->prepare("select lastname, firstname, studnum from student 
      $select order by lastname, firstname");
    $sth->execute;
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }

    while ( my ($lastname, $firstname, $studnum) = $sth->fetchrow ) {
	print qq{<tr><td><b>$lastname</b>, $firstname ($studnum)</td>\n};
	print qq{<td><input type="checkbox" name="$studnum" value="1" $checked>};
	print qq{</td></tr>\n};
    }


    # Print Submit Row
    print qq{<tr><td colspan="4" class="cn">};
    print qq{<input type="submit" value="$lex{'Continue'}"></td></tr>\n};
    
    print qq{</table>\n</form></body></html>\n};
    
    exit;

}


#---------------
sub writeRecords {
#---------------

    my $date = $dbh->quote( $arr{date} );
    delete $arr{date};

    my $name = $dbh->quote( $arr{name} );
    delete $arr{name};

    my $description = $dbh->quote( $arr{description} );
    delete $arr{description};

    my $total = $arr{amount};  # get starting total here;
    my $amount = $dbh->quote( $arr{amount} );
    delete $arr{amount};


    # put tax values and index into %taxes
    my %taxes;
    for my $i (1..4) {
	my $fieldname = 'tax'. $i;
	if ( $arr{$fieldname} ) {
	    $taxes{$i} = $arr{$fieldname};
	    delete $arr{$fieldname};
	}
    }

    # fill in any missing tax fields (max is 4)
    my %taxname;

    for my $i (1..4) {
	if ( $taxes{$i} ) {
	    $total += $taxes{$i};
	    $taxes{$i} = round( $taxes{$i}, $rounding );
	    #print qq{Tax: $taxes{$i}<br>\n};
	    $taxes{$i} = $dbh->quote( $taxes{$i} );
	    $taxname{$i} = $dbh->quote( $tax[$i]->{name} );
	} else {
	    $taxes{$i} = $sql{default};
	    $taxname{$i} = $sql{default};
	}
    }

    $total = round( $total, $rounding );
    #print qq{The total is: $total<br>\n};

    foreach my $studnum ( keys %arr ) {

	my $sth = $dbh->prepare("insert into fees_jrl values(
         $sql{default}, $studnum, $date, 'chg', $name, $description, $amount,
         $taxes{1}, $taxname{1}, $taxes{2}, $taxname{2}, $taxes{3}, $taxname{3}, 
         $taxes{4}, $taxname{4}, 
         $total, $sql{default}, $sql{default} ) ");
         # last fields are: paid_id and receipt

	$sth->execute;
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }

    }

    print qq{<h3>$lex{'Record(s) Stored'}</h3>\n};
    print qq{<p>[ <a href="$self">$lex{'Assess Fees'}</a> | };
    print qq{<a href="$feespage">$lex{Fees}</a> ]</p>\n};
    print qq{</body></html>\n};

    exit;

} # End of updateRecord
