#!/usr/bin/perl
#  Copyright 2001-2019 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; version 2 of 
#  the License, only.


my %lex = ('Please Log In' => 'Please Log In',
	   'Error' => 'Error',
	   'View' => 'View',
	   'Fees' => 'Fees',
	   'Main' => 'Main',
	   'Date' => 'Date',
	   'Description' => 'Description',
	   'Type' => 'Type',
	   'Amount' => 'Amount',
	   'Grade' => 'Grade',
	   'Homeroom' => 'Homeroom',
	   'Name' => 'Name',
	   'Receipt' => 'Receipt',
	   'Id' => 'Id',
	   'No Records Found' => 'No Records Found',
	   'Paid' => 'Paid',
	   'Unpaid' => 'Unpaid',
	   'Balance' => 'Balance',
	   'Continue' => 'Continue',
	   'Start Date' => 'Start Date',

	   );


my $self = 'viewfees.pl';


use DBI;
use CGI;
use CGI::Session;
use Time::JulianDay;
use Number::Format qw(:all);

my $q = new CGI;
my %arr = $q->Vars;

# Get Julian Day value for start date
my $startjd = julian_day( split('-', $startdate));

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


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

# Set Page Title
my $title = "$lex{View} $lex{Fees}";


# Get Session
my $session = new CGI::Session("driver:$dbtype;serializer:FreezeThaw",
 undef,{Handle => $dbh}) or die CGI::Session->errstr;

if ( not $session->param('logged_in') ){

    $userid = $session->param('userid');
    print $q->header( -charset, $charset );
    print qq{$doctype\n<html><head><title>$title</title>\n};
    print qq{<link rel="stylesheet" href="$parcss" type="text/css">\n};
    print qq{$chartype\n</head><body style="padding: 1em 2em;">\n};
    print qq{<h1>$title</h1>\n};

    print qq{<form action="plogin.pl" method="post" style="padding:0 2em;">\n};
    print qq{<input type="hidden" name="script" value="$self">\n};
    print qq{<input type="hidden" name="userid" value="$userid">\n};
    print qq{<input type="submit" value="$lex{'Please Log In'}">\n};
    print qq{</form>\n};

    exit;
}

# Redo with Read Only User.
$dbh = DBI->connect($dsn,$rouser,$ropassword);

my $userid = $session->param('userid');
my $duration = $session->param('duration');

$session->expire('logged_in', $duration );
print $session->header( -charset, $charset );


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

if ( not $arr{page} ) {
    print qq{<link rel="stylesheet" type="text/css" media="all" };
    print qq{href="/js/calendar-blue.css" title="blue">\n};
    print qq{<script type="text/javascript" src="/js/calendar.js"></script>\n};
    print qq{<script type="text/javascript" src="/js/lang/calendar-en.js"></script>\n};
    print qq{<script type="text/javascript" src="/js/calendar-setup.js"></script>\n};
}

print qq{$chartype\n</head><body style="padding: 1em 2em;">\n};

print qq{[ <a href="$parpage">$lex{Main}</a> ]\n};
print qq{<h1>$title</h1>\n};

if ( not $arr{page} ) {
    showStartPage();
    
} elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    showTransactions( $userid, $startdate );
}



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


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

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


    # Start Date
    print qq{<tr><td class="bra">$lex{'Start Date'}</td><td class="la">\n};
    print qq{<input type="text" id="date" name="date" size="10" value="$schoolstart">\n};
    print qq{<button type="reset" id="start_trigger">...</button></td></tr>\n};

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

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

    print qq{<script type="text/javascript">
     Calendar.setup({
        inputField     :    "date", // id of the input field
        ifFormat       :    "%Y-%m-%d", // format of the input field
        button         :    "start_trigger", // trigger for the calendar (button ID)
        singleClick    :    false,        // double-click mode
        step           :    1             // show all years in drop-down boxes 
    }) };

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

    exit;

} # end of showStartPage




#-------------------
sub showTransactions {
#-------------------


    my ($studnum, $startdate) = @_;

    # strip any nondigits
    $startdate =~ s/\D//g;
    my ($yr,$mo,$da) = unpack("A4,A2,A2",$startdate);
    $startdate = "$yr-$mo-$da";
    # print qq{Startdate: $stardate<br>\n};

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


    # Setup Queries.
    my $sth1 = $dbh->prepare("select id, trans_date, trans_type, name, description, total, 
      paid_id, receipt from fees_jrl
      where studnum = ? 
      order by trans_date, id");
#and to_days(trans_date) >= to_days('$startdate') 

    my $sth2 = $dbh->prepare("select sum(total) from fees_jrl where studnum = ?");
    my $sth3 = $dbh->prepare("select count(*) from fees_jrl where paid_id is NULL and studnum = ?");


    print qq{<div style="padding:1em 1em 0.5em 1em;"><b>$firstname $lastname</b> ($studnum)};
    print qq{&nbsp;&nbsp;$lex{Grade}: $grade&nbsp;&nbsp;};
    if ( $homeroom ) { print qq{$lex{Homeroom}: $homeroom\n}; }


    # Check for error with zero balance and some unmarked paid_id values.
    $sth2->execute( $studnum );
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
    my $balance = $sth2->fetchrow;
    my $pcount;
    if ( $balance == 0 ) { # check for blank paid_id
	$sth3->execute( $studnum );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	$pcount = $sth3->fetchrow;
    }

    if ( $pcount ) { # if we have zero balance and some unmarked paid_id fields, show form
	print qq{<form action="transed.pl" method="post" style="display:inline">\n};
	print qq{<input type="hidden" name="studnum" value="$studnum">\n};
	print qq{<input type="submit" value="Fix Record"></form>\n};
    }

    print qq{</div>\n};

    # Find  student transactions.
    $sth1->execute( $studnum );
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }

    my $first = 1;
    my $balance;

    while ( my ( $id, $trans_date, $trans_type, $name, 
		 $description, $total, $paid_id, $receipt ) = $sth1->fetchrow ) {

	if ( $transactmode eq $lex{Unpaid} ) {
	    if ( $trans_type eq 'pay' or $paid_id )  { next; }
	}

	if ( $first ) {

	    # Print Table Header
	    print qq{<table border="1" cellpadding ="3" cellspacing="0">\n};

	    print qq{<tr><th>$lex{Id}</th><th>$lex{Date}</th><th>$lex{Type}</th>};
	    print qq{<th>$lex{Name}</th><th>$lex{Description}</th><th>$lex{Amount}</th>\n};
	    print qq{<th>$lex{Paid} $lex{Id}</th><th>$lex{Receipt}</th></tr>\n};
	    $first = 0;
	}
 
	$balance += $total;

	my $transjd = julian_day( split('-',$trans_date));
	if ( $transjd < $startjd ) { next; }

	print qq{<tr><td>$id</td><td>$trans_date</td><td>$trans_type</td>};
	print qq{<td>$name</td><td>$description</td>\n};
	print qq{<td>$total</td><td>$paid_id</td><td>$receipt</td></tr>\n};
    }


    if ( $first ) {
	print qq{<p><span style="border:1px solid gray;padding:0.4em;">};
	print qq{$lex{'No Records Found'}</span></p>\n};

    } else {
	# Show Balance Due
	my $balanceduefmt = format_number( $balance, 2,2);
	print qq{<tr style="font-weight:bold;font-size:130%;"><td colspan="5" style="text-align:right;">};
	print qq{<b>$lex{Balance}</b></td><td>$balanceduefmt</td><td></td><td></td></tr>\n};
    }

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

    exit;

}
