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

#  This file is part of Open Admin for Schools.


my %lex = ('Main' => 'Main',
	   'Error' => 'Error',
	   'Add' => 'Add',
	   'Score' => 'Score',
	   'Student' => 'Student',
	   'Continue' => 'Continue',
	   'Save' => 'Save',
	   'Homeroom' => 'Homeroom',
	   'Select' => 'Select',
	   'Record' => 'Record',
	   
	   );

use DBI;
use CGI;
use Time::JulianDay;

my $self = 'atpBalfwd.pl';

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

my @time = localtime(time);
my $year = $time[5] + 1900;
my $month = $time[4] + 1;
my $day = $time[3];
if ( length $month == 1 ) { $month = '0'. $month; }
if ( length $day == 1 ) { $day = '0'. $day; }
my $currdate = "$year-$month-$day";

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

my $userid = $ENV{'REMOTE_USER'};

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


print $q->header( -charset, $charset );


# Page Header
my $title = qq{$lex{Add} Balance Forward Values};

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

print qq{$chartype\n</head><body style="padding:1em 2em;">\n};
print qq{[ <a href="$tchpage">$lex{Main}</a> ] $userid \n};
print qq{<h1>$title</h1>\n};


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

}  elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    enterBalFwd();

}  elsif ( $arr{page} == 2 ) {
    delete $arr{page};
    writeBalFwd();
} 


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

    # Get the homeroom students of this teacher
    
    # Get Homeroom
    my @homerooms;
    my $sth = $dbh->prepare("select distinct homeroom from student where homeroom is not NULL and homeroom != ''");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $homeroom = $sth->fetchrow ) {
	push @homerooms, $homeroom;
    }
    @homerooms = sort {$a <=> $b} @homerooms;


    # Get Teacher Name
    my $sth = $dbh->prepare("select firstname, lastname from staff where userid = ?");
    $sth->execute($userid);
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    my ($fn,$ln) = $sth->fetchrow;
    print qq{<h3>$fn $ln</h3>\n};
    

    # Get the Year-Month for entry.
    my ($y,$m,$d) = split('-', $schoolstart); # loaded from admin.conf file
    my @yrmo; # ordered by year-month
    foreach my $m (9..12) { # do fall
	push @yrmo, qq{$y-$m};
    }
    $y++; # increment year
   
    foreach my $m (1..6) { # do fall
	push @yrmo, qq{$y-$m};
    }

    my $hrcount = scalar @homerooms;
    
    #print qq{<div>HR:@homerooms - $hrcount</div>\n};
    #print qq{<div>YR-MO:@yrmo</div>\n};
    
    # Start Form
    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" style="border:1px solid gray;padding:0.5em;">\n};
    print qq{<caption>Please Select Month and Homerooms</caption>\n};


    # Homeroom
    print qq{<tr><td class="bra" style="vertical-align:top;">Homeroom</td>\n};
    print qq{<td>};
    foreach my $hr ( sort {$a <=> $b} @homerooms ) {
	print qq{<input type="checkbox" name="$hr" value="1"> $hr<br>\n};
    }
    print qq{</td></tr>\n};

    # Horizontal Rule
    print qq{<tr><td colspan="2"><hr></td></tr>\n};
    
    # Year-Month Select
    print qq{<tr><td class="bra" style="vertical-align:top;">Year-Month</td>};
    print qq{<td class="la">};
    foreach my $yrmo ( @yrmo ) {
	my ($y,$m) = split('-', $yrmo);
	print qq{<input type="radio" name="yrmo" value="$yrmo"> $month[$m], $y<br>\n};
    }

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

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

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

    exit;

} # end of showStartPage


#--------------
sub enterBalFwd {
#--------------

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

    my $yrmo = $arr{yrmo};
    delete $arr{yrmo};
    
    
    if ( not $yrmo or not %arr ) {
	print qq{<h3>$lex{Error}: Missing Value</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    my ($y,$m) = split('-', $yrmo);

    my @homerooms;
    foreach my $key (keys %arr ) {
	push @homerooms, $key;
    }
    @homerooms = sort {$a <=> $b} @homerooms;
    
    
    # Show Choices
    print qq{<p>Balance Forwards for <b>$month[$m]</b>, $y</p>\n}; 

    
    # Print Form Heading
    print qq{<form action="$self" method="post"> \n};
    print qq{<input type="hidden" name="page" value="2">\n};
    print qq{<input type="hidden" name="yrmo" value="$yrmo">\n};

    print qq{<div class="la"><input  class="btn-grn" type="submit" value="$lex{Save}"></div>\n};

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

    # load a balance forward value, if any
    my $sth1 = $dbh->prepare("select id, balfwd from atp_balfwd where yrmo = ? and studnum = ?");

    
    foreach my $hr ( sort {$a <=> $b} @homerooms ) {
	my $first = 1;
	$sth->execute( $hr );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	while ( my $ref = $sth->fetchrow_hashref ) {
	    my %r = %$ref;

	    if ( $first ) {
		print qq{<table cellpadding="3" cellspacing="0" border="1" style="float:left;margin:1em;">\n};
		print qq{<caption style="font-weight:bold;">Homeroom $hr</caption>\n};
		print qq{<tr><th>$lex{Student}</th><th>Balance<br>Forward</th></tr>\n};
		$first = 0;
	    }

	    # load a value, if any;
	    $sth1->execute( $yrmo, $r{studnum} );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    my ($id, $balfwd) = $sth1->fetchrow;
	    my $recname;
	    
	    if ( $id ) {
		$recname = qq{ID:$id};
	    } else { # no record yet
		$recname = $r{studnum};
	    }
	    
	    print qq{<tr><td><b>$r{lastname}</b>, $r{firstname} ($r{studnum})</td>};
	    print qq{<td><input type="text" name="$recname" value="$balfwd" style="width:6ch;"></td></tr>\n};
	}

	if ( not $first ) {
	    print qq{</table>\n};
	} else {
	    print qq{<h3>No Records Found for homeroom $hr</h3>\n};
	}
    }

    print qq{<div class="la" style="clear:left;"><input  class="btn-grn" type="submit" value="$lex{Save}"></div>\n};
    print qq{</form></body></html>\n};

    exit;

} # end of enterBalFwd


#---------------
sub writeBalFwd {
#---------------

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

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

    print qq{Year-Month: $yrmo<br>\n};
    
    foreach my $key ( keys %arr ) {

#	print qq{K:$key VAL:$arr{$key}<br>\n};
	
	my $studnum;
	my ($flag, $id) = split(':', $key);
	if ( $flag  ne 'ID' ) { # we have a record already
	    $studnum = $flag;
	}

	
	# Check for existing record for this student. If so, get record id
#	my $sth = $dbh->prepare("select id from atp_balfwd
#           where studnum = ? and yrmo = ?");
#	$sth->execute( $studnum, $yrmo );
#	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
#	my $id = $sth->fetchrow;
	
#	print qq{ID:$id SN:$studnum Tbl:$table YRMO:$yrmo<br>\n};

	my $sth1= $dbh->prepare("update atp_balfwd set balfwd = ? where id = ?");

	my $sth2 = $dbh->prepare("insert into atp_balfwd (userid, studnum, yrmo, balfwd)
           values ( ?, ?, ?, ? )");

	my $sth3= $dbh->prepare("delete from atp_balfwd where id = ?");

	if ( $id and not $arr{$key} ) { # delete the rec
	    $sth3->execute( $id ); 
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }

	} elsif ( $id ) { # update record

	    $sth1->execute( $arr{$key}, $id ); # $arr{$key} is the value.
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    
	} elsif ( $arr{$key} )  { # insert a record, if a value
	    $sth2->execute($userid, $studnum, $yrmo, $arr{$key});
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	}
    }

    print qq{<h3>Records Stored/Updated</h3>\n};
    print qq{</body></html>\n};

    exit;

} # end of writeScores
