#!/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 = ('Payments' => 'Payments',
	   'Main' => 'Main',
	   'Fees' => 'Fees',
	   'Student' => 'Student',
	   'Search' => 'Search',
	   'No Student(s) Found' => 'No Student(s) Found',
	   'Last,First/Last/Initials/Studnum' => 'Last,First/Last/Initials/Studnum',
	   'Accept Payment' => 'Accept Payment',
	   'Date' => 'Date',
	   'Total Payment' => 'Total Payment',
	   'Recalculate' => 'Recalculate',
	   'Payment' => 'Payment',
	   'Received On Acct' => 'Received On Acct',
	   'Action' => 'Action',
	   'Payment' => 'Payment',
	   'Print Receipt' => 'Print Receipt',
	   'Payment Completed' => 'Payment Completed',
	   'Failed' => 'Failed',
	   'Receipt Number' => 'Receipt Number',
	   'Payee' => 'Payee',
	   'Error' => 'Error',
	   'Balance Due' => 'Balance Due',
	   'No Unpaid Bills Found' => 'No Unpaid Bills Found',
	   'Type' => 'Type',
	   'Continue' => 'Continue',
	   'Another' => 'Another',
	   'Description' => 'Description',
	   'Pay On Account' => 'Pay On Account',
	   'Pay Particular Charges' => 'Pay Particular Charges',
	   'Type' => 'Type',
	   'Paper Size' => 'Paper Size',
	   'Font Size' => 'Font Size',
	   'Letter' => 'Letter',
	   'Legal' => 'Legal',
	   'A4' => 'A4',
	   'A5' => 'A5',
	   'Save' => 'Save',

	  );


my $self = 'payment.pl';

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

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

my @time = localtime(time);
my $year = $time[5] + 1900;
my $month = $time[4] + 1;
my $currdate = "$year-$month-$time[3]";

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


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


# Print Start of HTML Document.
my $title = $lex{Payment};

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


# Load jQuery
print qq{<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>\n};


print qq{$chartype\n</head><body onload="document.forms[0].elements[1].focus()" };
print qq{style="padding-top:1em;">\n};

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


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

} elsif ( $arr{page} == 1 ) {
    selectStudent( $arr{student} );

} elsif ( $arr{page} == 2 ) {
    getTransType( $arr{studnum} );

} elsif ( $arr{page} == 3 and $arr{paytype} eq 'roa' ) {
    getROA( $arr{studnum} );

} elsif ( $arr{page} == 3 and $arr{paytype} eq 'pay' ) {
    getPay( $arr{studnum} );

} elsif ( $arr{page} == 4 ) {
    if ( $arr{submit} eq $lex{Recalculate} ) { # recalculating...
	getPay( $arr{studnum} );
    } else {
	acceptPayment();
    }
}



#---------------
sub getTransType { # get type of transaction (roa or pay)
#---------------

    my $studnum = shift;

    # Get student name.
    my $sth = $dbh->prepare("select lastname, firstname from studentall where studnum = ?");
    $sth->execute( $studnum );
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    my ($lastname, $firstname) = $sth->fetchrow;

    # Get student transactions
    # paid_id is null until full payment made.

    my $sth = $dbh->prepare("select id, total, trans_type from fees_jrl where studnum = ? and 
      paid_id is null and (trans_type = 'chg' or trans_type = 'roa') order by trans_date");
    # FIX: remove the transtype selection later
 
    $sth->execute( $studnum );
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

    while ( my ($id, $total, $type) = $sth->fetchrow ) {
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	if ( $type eq 'roa' ) {
	    push @trans, $id;
	} else {
	    push @pay, $id;
	}
    }
    push @trans, @pay; # put the roa transactions at start of the array.


    print qq{<h1>$lex{Payment} $lex{Type}</h1>\n};

    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="studnum" value="$studnum">\n};
    print qq{<input type="hidden" name="page" value="3">\n};
    print qq{<table cellpadding="4" cellspacing="0" border="1">\n};

    print qq{<tr><td class="bra">$lex{Student}</td>\n};
    print qq{<td>$firstname $lastname ($arr{studnum})</td></tr>\n};


    # Loop through all transactions.
    $sth = $dbh->prepare("select total, name, description, trans_type 
       from fees_jrl where id = ?");
    my ($currowing, $tval, $tpay, $totalpay);
    my $balancedue = 0;
    
    foreach my $id ( @trans )  {

	$sth->execute( $id );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my ($tval, $name, $description, $type) = $sth->fetchrow;

	$balancedue += $tval;

	print qq{<tr style="background-color:#DDD;"><td class="ra">};
	if ( $name ) { print qq{<i>$name</i>}; }
	if ( $name and $description ) { print qq{ - }; }
	if ( $description ) { print $description; }
	print qq{</td>\n};

	print qq{<td class="la">$tval</td></tr>\n};

    }


    # Show Balance Due
    $balanceduefmt = format_number( $balancedue, 2,2);
    print qq{<tr><td class="bra">$lex{'Balance Due'}</td><td>};
    print qq{$balanceduefmt</td></tr>\n};

    # Now show either Received on Account or Charge Payment
    print qq{<tr><td colspan="2"><b>$lex{Payment} $lex{Type}</b>: };
    print qq{<input type="radio" name="paytype" value="roa">$lex{'Pay On Account'}\n};
    print qq{&nbsp;&nbsp;<input type="radio" name="paytype" value="pay">$lex{'Pay Particular Charges'}\n};
    print qq{</td></tr>\n};

    print qq{<tr><td colspan="2" class="cn"><input type="submit" name="submit" value="$lex{Continue}"></td>\n};

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

    exit;

} # End of getTransType



#---------
sub getROA { # get roa payment values
#---------

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

    my $studnum = shift;

    # Get student name.
    my $sth = $dbh->prepare("select lastname, firstname from studentall where studnum = ?");
    $sth->execute( $studnum );
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    my ($lastname, $firstname) = $sth->fetchrow;

    # Get student transactions
    # paid_id is null until full payment made.

    my $sth = $dbh->prepare("select id, total, trans_type from fees_jrl where studnum = ? and 
      paid_id is null and (trans_type = 'chg' or trans_type = 'roa') order by trans_date");
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    $sth->execute( $studnum );
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

    while ( my ($id, $total, $type) = $sth->fetchrow ) {
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	if ( $type eq 'roa' ) {
	    push @trans, $id;
	} else {
	    push @pay, $id;
	}
    }
    push @trans, @pay; # put the roa transactions at start of the array.


    print qq{<h1>$lex{'Received On Acct'} $lex{Payment}</h1>\n};

    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="studnum" value="$studnum">\n};
    print qq{<input type="hidden" name="page" value="4">\n};
    print qq{<input type="hidden" name="paytype" value="roa">\n};

    print qq{<table cellpadding="4" cellspacing="0" border="1">\n};

    print qq{<tr><td class="bra">$lex{Student}</td>\n};
    print qq{<td>$firstname $lastname ($arr{studnum})</td></tr>\n};

    # Loop through all transactions.
    $sth = $dbh->prepare("select total, name, description, trans_type 
       from fees_jrl where id = ?");
    my ($currowing, $tval, $tpay, $totalpay);
    my $balancedue = 0;
    
    foreach my $id ( @trans )  {

	$sth->execute( $id );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my ($tval, $name, $description, $type) = $sth->fetchrow;

	$balancedue += $tval;

	print qq{<tr style="background-color:#DDD;"><td class="bra">};
	if ( $name ) { print qq{<i>$name</i>}; }
	if ( $name and $description ) { print qq{ - }; }
	if ( $description ) { print $description; }
	print qq{</td>\n};

	print qq{<td class="la">$tval</td></tr>\n};

    }

    # Show Balance Due
    $balanceduefmt = format_number( $balancedue, 2,2);
    print qq{<tr><td class="bra">$lex{'Balance Due'}</td><td>};
    print qq{$balanceduefmt</td></tr>\n};

    # Get Payment Value
    print qq{<tr><td class="bra">$lex{Payment}</td><td>};
    print qq{<input type="text" name="payval" size="8"></td></tr>\n};

    # Get Date, Payee.
    print qq{<tr><td class="bra">$lex{Date}</td>\n};
    print qq{<td><input type="text" name="date" size="11" value="$currdate"></td></tr>\n};

    print qq{<tr><td class="bra">$lex{Payee}</td>\n};
    print qq{<td><input type="text" name="payee" size="25" value="$arr{payee}"></td></tr>\n};

    print qq{<tr><td colspan="2"><b>$lex{Description}</b><br><textarea name="description" rows="2" cols="60">\n};
    print qq{</textarea></td></tr>\n};

    print qq{<tr><td colspan="2" class="cn"><input type="submit" name="submit" value="$lex{Save}"></td>\n};

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

    print qq{<script type="text/javascript">
    \$('form').submit( function(){
      \$(':submit',this).attr('disabled','disabled' );
    });
    </script>\n};

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

    exit;

} # End of getROA



#---------
sub getPay { # get payment values
#---------

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

    my $studnum = shift;

    # Get student name.
    my $sth = $dbh->prepare("select lastname, firstname from studentall where studnum = ?");
    $sth->execute( $studnum );
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    my ($lastname, $firstname) = $sth->fetchrow;


    my ( @trans, $recalcmode );
    if ( $arr{page} == 4 ) { # We are doing a recalc
	$recalcmode = 1; # turn on recalc mode
	delete $arr{page};
    }


    # Get student transactions
    # paid_id is null until full payment made.

    my $sth = $dbh->prepare("select id, total, trans_type from fees_jrl where studnum = ? and 
      paid_id is null and (trans_type = 'chg' or trans_type = 'roa') order by trans_date");
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    $sth->execute( $studnum );
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    while ( my ($id, $total, $type) = $sth->fetchrow ) {
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	if ( $type eq 'roa' ) {
	    push @trans, $id;
	} else {
	    push @pay, $id;
	}
    }
    push @trans, @pay; # put the roa transactions at start of the array.


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

    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="studnum" value="$studnum">\n};
    print qq{<input type="hidden" name="page" value="4">\n};
    print qq{<input type="hidden" name="paytype" value="pay">\n};

    print qq{<table cellpadding="4" cellspacing="0" border="1">\n};

    print qq{<tr><td class="bra">$lex{Student}</td>\n};
    print qq{<td>$firstname $lastname ($arr{studnum})</td></tr>\n};

    # Get Date, Payee.
    if ( $recalcmode ) { $currdate = $arr{date}; }
    print qq{<tr><td class="bra">$lex{Date}</td>\n};
    print qq{<td><input type="text" name="date" size="11" value="$currdate"></td></tr>\n};

    print qq{<tr><td class="bra">$lex{Payee}</td>\n};
    print qq{<td><input type="text" name="payee" size="25" value="$arr{payee}"></td></tr>\n};

    print qq{<tr><td colspan="2"><b>$lex{Description}</b>\n};
    print qq{<input type="text" name="description" size="60" };
    print qq{value="$arr{description}"></td></tr>\n};

    # Loop through all transactions.
    $sth = $dbh->prepare("select total, name, description, trans_type 
       from fees_jrl where id = ?");
    my ($currowing, $tval, $tpay, $totalpay);
    my $balancedue = 0;

    
    foreach my $id ( @trans )  {

	$sth->execute( $id );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my ($tval, $name, $description, $type) = $sth->fetchrow;

	$balancedue += $tval;

	print qq{<tr style="background-color:#DDD;"><td class="bra">};
	if ( $name ) { print qq{<i>$name</i>}; }
	if ( $name and $description ) { print qq{ - }; }
	if ( $description ) { print $description; }
	print qq{</td>\n};

	print qq{<td class="la">};

	#if ( $type eq 'roa' ) {
#	    print qq{<input type="hidden" name="$id" value="$tval">$tval\n};
#	    $totalpay += $tval;
#	} else {
	# Checked is on unless a recalc and no $arr{id} value

	my $chk = q{checked = "checked"};
	if ( $recalcmode and not $arr{$id} ) { $chk = ''; }
	if ( $chk ) { $totalpay += $tval; }
	print qq{$tval <input type="checkbox" name="$id" value="1" $chk>\n};
	

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

    }

    # Show Balance Due
    $balanceduefmt = format_number( $balancedue, 2,2);
    print qq{<tr><td class="bra">$lex{'Balance Due'}</td><td>};
    print qq{$balanceduefmt</td></tr>\n};

    # Show Total Payment
    $totalpayfmt = format_number( $totalpay, 2,2);
    print qq{<tr><td class="bra">$lex{'Total Payment'}</td>};
    print qq{<td style="font-size:130%;font-weight:bold;">$totalpayfmt</td></tr>\n};


    print qq{<tr><td class="cn"><input type="submit" name="submit" };
    print qq{value="$lex{'Recalculate'}"></td>\n};

    print qq{<td class="cn"><input type="submit" name="submit" id="submit" };
    print qq{value="$lex{'Accept Payment'}"></td></tr>\n};

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


    print qq{<script type="text/javascript">
    \$('form').submit( function(){
      \$('#submit',this).attr('disabled','disabled' );
    });
    </script>\n};


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

    exit;

} # End of getPay




#----------------
sub acceptPayment {
#----------------

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

    # delete unneeded hash elements.
    delete $arr{submit};
    delete $arr{page};

    # Passed: studnum, date, paytype, payee, description and ids of each of the unpaid transactions.
    # foreach my $key (sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }

    # remove other elements (5) to leave only record id's of the
    # unpaid transactions (some selected by paytype, otherwise all
    # will be selected later by roa section.

    my $studnum = $arr{studnum};
    delete $arr{studnum};
    my $date = $arr{date};
    delete $arr{date};

    my $payee = $arr{payee};
    delete $arr{payee};
    my $paytype = $arr{paytype};
    delete $arr{paytype};
    my $description = $arr{description};
    delete $arr{description};

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


    my ($payid, $balance); 

    if ( $paytype eq 'pay' ) {

	# Loop through records and check for overpayment
	my $failflag; # if an overpayment, fail

	my $sth = $dbh->prepare("select total from fees_jrl where id = ?");

	# Loop through all passed id's
	my $payment;
	foreach my $id ( sort keys %arr ) {
	    $sth->execute( $id );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    my $total = $sth->fetchrow;
	    $payment += $total;
	}

	# Fail if over payment or zero payment
	if ( $payment <= 0 ) { # Error: overpaid on a transaction
	    print qq{<p><b>$lex{Payment} $lex{Error}</b>: $payment</p>\n};
	    print qq{</body></html>\n};
	    exit;
	}

	# timetag is used to identify the added field.
	my $timetag = time();
	# print qq{Timetag: $timetag<br>\n};

	# Add a payment record to the fees_jrl table: studnum, date,
	# payment and id strings and total.

	# Get Receipt Number
	my $receiptnumber = getReceiptNumber();

	
	$sth = $dbh->prepare("insert into fees_jrl 
          ( studnum, trans_date, trans_type, name, description, total, receipt ) 
           values( ?,?,?,?,?,?,?)");
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	$sth->execute( $studnum, $date, 'pay', $lex{Payment}, $timetag, -$payment, $receiptnumber ); 
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }


	# Get the id for this new added record. (this student, this date, this time)
	$sth = $dbh->prepare("select id from fees_jrl  where trans_date = ? and 
          studnum = ? and trans_type = 'pay' and description = ?");
	$sth->execute($date, $studnum, $timetag );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	$payid = $sth->fetchrow;


	# Update the payment description; remove time. Update paid_id
	$sth = $dbh->prepare("update fees_jrl set description = ?, paid_id = $payid where id = $payid");
	
	# remove any parenthesis, and put together
	$description =~ s/\(|\)/ /g;
	my $desc = "$description ($lex{Payee}: $payee)";

	$sth->execute( $desc ); # update description, paid_id.


	# Now mark the records paid... (skip receipt update for the roa transactions since already done.
	my $sth = $dbh->prepare("update fees_jrl set paid_id = $payid where id = ?");
	my $sth1 = $dbh->prepare("update fees_jrl set receipt = $receiptnumber where id = ?");
	my $sth2 = $dbh->prepare("select trans_type from fees_jrl where id = ?");
	
	foreach my $id ( keys %arr ) { 
	    # skip the receipt update on roa types (since set by prev payment)

	    # Set Paid_id value (ie. item is paid)
	    $sth->execute( $id );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

	    # Get Type 
	    $sth2->execute( $id );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    my $type = $sth2->fetchrow;

	    if ( $type ne 'roa' ) { # set the recipt number
		$sth1->execute( $id );
		if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    }
	}



    } elsif ( $paytype eq 'roa' ) { # create an roa record.


	my $receiptnumber = getReceiptNumber();

	my $name = $lex{'Received On Acct'};
	$description =~ s/\(/ /g;
	$description =~ s/\)/ /g;
	$description = $description. ' ('. $lex{Payee}. ": $payee)";


	# Add a roa record to the fees_jrl table:
	my $sth = $dbh->prepare("insert into fees_jrl 
         ( studnum, trans_date, trans_type, name, description, total,receipt ) 
         values(?,?,?,?,?,?,? )");

	$sth->execute($studnum, $date,'roa', $name, $description , -$arr{payval}, $receiptnumber );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

	# Now get the id for this record for link below
	$sth = $dbh->prepare("select id from fees_jrl where trans_date = ? and 
          studnum = ? and trans_type = 'roa' and receipt = ?");
	$sth->execute($date, $studnum, $receiptnumber );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	$payid = $sth->fetchrow;


	# Now check outstanding balance and see if this pays off the balance
	# If so then set paid_id to indicate paid off.

	$sth = $dbh->prepare("select id, total, trans_type from fees_jrl where studnum = ?
           and paid_id is NULL");
	$sth->execute( $studnum );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

	my @ids = ();
	while ( my ($id, $total,$transtype )  = $sth->fetchrow ) {
	    if ( $transtype eq 'pay' ) { next; } #skip pay types since old code not set paid_id
	    push @ids, $id;
	    $balance += $total;
	}

	# print qq{<br>Payment:$arr{payval} Bal:$balance<br>", @ids, "\n};

	if ( not $balance ) { # now have paid off the bill
	    
	    # Now mark the records paid... (skip receipt update for the roa transactions since already done.
	    my $sth = $dbh->prepare("update fees_jrl set paid_id = $payid where id = ?");
	    my $sth1 = $dbh->prepare("update fees_jrl set receipt = $receiptnumber where id = ?");
	    my $sth2 = $dbh->prepare("select trans_type from fees_jrl where id = ?");
	
	    foreach my $id ( @ids ) {

		# Set Paid_id value (ie. item is paid)
		$sth->execute( $id );
		if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

		# Get Type 
		$sth2->execute( $id );
		if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
		my $type = $sth2->fetchrow;

		if ( $type ne 'roa' ) { # if NOT roa set the recipt number
		    $sth1->execute( $id );
		    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
		}
	    }

	    # Mark the final payment record as a 'pay' type to avoid the zero balance problem.
	    $sth = $dbh->do("update fees_jrl set trans_type = 'pay' where id = $payid");

	 } # End of if no balance (ie. paid off )


    } else { # Error: no such pay type.

	print qq{$lex{Error}: $lex{Type}:$paytype<br>\n};
	print qq{</body></html>\n};
	exit;
    }


    print qq{<h1>$lex{'Payment Completed'}</h1>};


    print qq{<form action="receipt.pl" method="post">\n};
    print qq{<input type="hidden" name="page" value="5">\n};
    print qq{<input type="hidden" name="$payid" value="1">\n};

    print qq{<p>$lex{Type} <select name="type"><option>PDF</option><option>HTML</option></select>\n};

    print qq{&nbsp;&nbsp;$lex{'Paper Size'} };
    $defaultpapersize =~ s/paper//; # strip out word paper so lex works; from admin.conf
    my $defpaper = ucfirst( $defaultpapersize );
    print qq{<select name="papersize"><option>$lex{$defpaper}</option>\n};
    my @sizes = qw(Letter A4 A5 Legal);
    foreach my $size ( @sizes ) {
	if ( $size eq $defpaper ) { next; }
	print qq{<option value="$size">$lex{$size}</option>};
    }
    print qq{</select>};

    # Font Size
    print qq{&nbsp;&nbsp;$lex{'Font Size'} };
    print qq{<select name="fontsize">\n};
    if ( $g_fontsize ) { print qq{<option>$g_fontsize</option>\n};}
    print qq{<option>10pt</option><option>11pt</option><option>12pt</option></select>\n };
    print qq{<input type="submit" value="$lex{'Print Receipt'}"></p>};


    # Another Payment
    print qq{<p>[ <a href="$self">$lex{Another} $lex{Payment}</a> ]</p>\n};

    exit;

} # End of AcceptPayment.



#----------------
sub selectStudent {
#----------------

    my $student = shift;

    print qq{<h1>$lex{'Payments'}</h1>\n};

    # Setup the Search
    if ($student =~ /\d+/) {  # we have a student number
	$sth = $dbh->prepare("select lastname, firstname, studnum from studentall 
          where studnum = ?");
	$sth->execute( $student );

    } else { # we have words possibly with a comma
	($lastname,$firstname)  = split /\,/, $student;
	$firstname =~ s/^\s*//;
	$lastname =~ s/^\s*//;
	if ($lastname and $firstname){ # both entered.
	    $sth = $dbh->prepare("select  lastname, firstname, studnum from studentall 
             where lastname = ? and firstname = ?");
	    $sth->execute( $lastname, $firstname );

	} elsif ($lastname and not $firstname){ # only lastname (no comma)
	    if (length($lastname) == 2){ # search by initials: fi, li.
		my $fi = substr($lastname,0,1). '%'; 
		my $li = substr($lastname,1,1). '%';
		$sth = $dbh->prepare("select lastname, firstname, studnum from studentall 
                 where lastname $sql{like} ? and firstname $sql{like} ?");
		$sth->execute( $li, $fi );

	    } else {
		$sth = $dbh->prepare("select lastname, firstname, studnum from studentall 
                  where lastname = ? order by firstname");
		$sth->execute( $lastname );
	    }
	} else { # print an error....
	    showSearchForm();
	    print qq{</body></html>\n};
	    exit;
	}

    } # Last Else
    # We should now have a $sth defined.

    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    my $rows = $sth->rows;

    if ( $rows < 1 ) { 
	print qq{<h1>$lex{'No Student(s) Found'}</h1>\n};
	showSearchForm();
	print qq{</body></html>\n}; 
	exit; 
    }

    # Prepare to search for unpaid bills
    my $sth1 = $dbh->prepare("select id from fees_jrl where studnum = ? and 
         paid_id is null and (trans_type = 'chg' or trans_type = 'roa')");


    # Table Header
    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
    print qq{<tr><th>$lex{Student}</th><th>$lex{Action}</th></tr>\n};


    while ( my ($lastname, $firstname, $studnum) = $sth->fetchrow ) {

	print qq{<tr><td>$firstname $lastname ($studnum)</td><td>\n};

	# check for unpaid bills
	$sth1->execute( $studnum );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $id = $sth1->fetchrow;
	if ( not $id ) { 
	    print qq{$lex{'No Unpaid Bills Found'}</td></tr>\n};
	    next; 
	}  # skip if no charges found.


	print qq{<form action="$self" method="post">\n};
	print qq{<input type="submit" value="$lex{'Accept Payment'}">\n};

	print qq{<input type="hidden" name="page" value="2">\n};

	print qq{<input type="hidden" name="studnum" value="$studnum">\n};
	print qq{</form></td></tr>\n};

    }

    print qq{</table>\n};
    
    showSearchForm();
    
    print qq{</body></html>\n};

    exit;

}



#----------------
sub showSearchForm {
#----------------

    print qq{<div style="padding:1em 0.2em;">\n};
    print qq{<b>$lex{Student} $lex{Search}</b><br>\n};

    print qq{<form action="$self" method="post" style="display:inline;">\n};
    print qq{<input type="submit" value="$lex{Search}">\n};
    print qq{<input type="text" name="student" size="30"><br>\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{$lex{Student} ($lex{'Last,First/Last/Initials/Studnum'} )\n};
    print qq{</form></div>\n};

    exit;

}



#-------------------
sub getReceiptNumber {
#-------------------

    use Fcntl qw(:DEFAULT :flock);

    # Get receipt number and update file.
    my $res = sysopen( RNUM, "../../etc/receiptnumber", O_RDWR | O_CREAT );
    if ( not $res ) {
	print qq{Sysopen $lex{Error}, $lex{'Receipt Number'}: $!<br>\n};
	die "Sysopen $lex{Error}, $lex{'Receipt Number'}: $!\n";
    }


    flock(RNUM,LOCK_EX);

    my $recnum = <RNUM> || 0;
    chomp $recnum;
    seek(RNUM,0,0) or die "Rewind $lex{Failed}: $lex{'Receipt Number'}: $!\n";
    truncate(RNUM,0) or die "Truncate $lex{Failed}: $lex{'Receipt Number'}: $!\n";

    my $recnum = $recnum + 1;
    print RNUM $recnum or die "Write $lex{Failed}: $lex{'Receipt Number'}: $!\n";
    close RNUM or die "Close $lex{Failed}: $lex{'Receipt Number'}: $! \n";

    return $recnum;

}
