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

#  This file is part of Open Admin for Schools.

# Add writing test scores to the write_scores table.


my %lex = ('Main' => 'Main',
	   'Error' => 'Error',
	   'Students' => 'Students',
	   'Continue' => 'Continue',
	   'Save' => 'Save',
	   'Select' => 'Select',
	   'Check' => 'Check',
	   'Next Page' => 'Next Page',
	   'Required' => 'Required',
	   'Test Date' => 'Test Date',

	   );


use DBI;
use CGI;
use Cwd;

my $self = 'wrAdd.pl';

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

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


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

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

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

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

my $mycss = $css;
if ( getcwd() =~ /tcgi/ ){ # we are in cgi
    $mycss = $tchcss;
}

# Page Header
my $title = qq{Add Writing Tests};
print qq{$doctype\n<html><head><title>$title</title>\n}; 
print qq{<link rel="stylesheet" href="$mycss" type="text/css">\n};

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="$tchpage">$lex{Main}</a> ]\n};
print qq{<h1>$title</h1>\n};

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

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

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


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

    # Get Grades
    my (%grades, %homerooms);
    my $sth = $dbh->prepare("select distinct grade from student 
	where grade != '' and grade is not NULL");
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    while ( my $gr = $sth->fetchrow ) {
	$grades{$gr} = 1;
    }
    my @grades = sort { $a <=> $b } keys %grades;

    # Homerooms
    my $sth = $dbh->prepare("select distinct homeroom from student 
	where homeroom != '' and homeroom is not NULL");
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    while ( my $hr = $sth->fetchrow ) {
	$homerooms{$hr} = 1;
    }
    my @homerooms = sort { $a <=> $b } keys %homerooms;

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

    print qq{<tr><td class="bra">$lex{'Test Date'}</td>\n};
    print qq{<td><input type="text" name="date" id="date" size="10">\n};
    print qq{<button type="reset" id="start_trigger">...</button>\n};
    print qq{(yyyy-mm-dd)</td></tr>\n};

    # Students - Grade
    print qq{<tr><td class="bra">$lex{Select} $lex{Students}</td><td></td></tr>\n};
    print qq{<tr><td class="ra">Grade</td><td><select name="grade"><option></option>};
    foreach my $grade ( @grades ) {
	print qq{<option>$grade</option>\n};
    }
    print qq{</select> <b>or</b></td></tr>\n};

    # Select Homeroom
    my $sth = $dbh->prepare("select lastname, firstname from staff s, staff_multi sm 
			    where s.userid = sm.userid and field_name = 'homeroom' 
			    and field_value = ?");

    print qq{<tr><td class="ra">Homeroom</td><td>};
    print qq{<select name="homeroom"><option></option>};
    foreach my $hr ( @homerooms ) {
	$sth->execute($hr);
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my ($lastname, $firstname) = $sth->fetchrow;
	my $hrname = $hr;
	if ( $lastname ) { $hrname = "$hr - $firstname $lastname"; }
	
	print qq{<option value="$hr">$hrname</option>\n};
    }
    print qq{</select></td></tr>\n};

    # Check Next Page
#    print qq{<tr><td class="bra">$lex{Check} $lex{'Next Page'}</td>\n};
#    print qq{<td><input type="checkbox" name="chk" value="checked">\n};
#    print qq{</td></tr>\n};    

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

    print qq{</table>\n};
    print qq{</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 
    });
   </script>\n};

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

    exit;

} # end of showStartPage



#----------------
sub selectStudents {
#----------------

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

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

    # Check for any Blanks in date
    if ( not $arr{date} ) {
	print qq{<h3>Date <b>$lex{Required}</b></h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    
    # Check for messed up Date Format
    my $errorflag;
    if ( $arr{date} =~ m/\// ) { # slashes rather than hyphens
	$errorflag = 1;
    } else {
	my ($y,$m,$d) = split('-', $arr{date});
	if ( not $m or ( $m < 1 or $m > 12 )) { $errorflag = 1; }
	if ( not $d or ( $d < 1 or $d > 31 )) { $errorflag = 1; }
    }
    if ( $errorflag ) {
	# print qq{<div>Year:$y Month:$m Day:$d</div>\n};
	print qq{<h3>$lex{'Test Date'} $lex{Error}: $arr{date}</h3>\n};
	print "</body></html>\n";
	exit;
    }

    my ($sth, $groupname);
    if ( $arr{grade} ) { # we're picking a group
	$sth = $dbh->prepare("select lastname, firstname, studnum from student
          where grade = ? order by lastname, firstname");
	$sth->execute( $arr{grade} );
	$groupname = qq{Grade $arr{grade}};
	
    } elsif ( $arr{homeroom} ) {
	$sth = $dbh->prepare("select lastname, firstname, studnum from student
          where homeroom = ? order by lastname, firstname");
	$sth->execute( $arr{homeroom} );
	$groupname = qq{Homeroom $arr{homeroom}};
	
    } else { # everyone
	$sth = $dbh->prepare("select lastname, firstname, studnum from student
          order by lastname, firstname");
	$sth->execute;
    }
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }


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

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

    print qq{<tr><td class="ra"><input type="submit" value="$lex{Continue}"></td></tr>\n};
#    print qq{<td colspan="2"><b>Test</b> - Add Test Score<br>};
#    print qq{<b>Absent</b> - Add Reason for Absence</td></tr>\n};

    print qq{<tr><th>Test</th><th>$groupname</th></tr>\n};

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

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

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

    exit;

} # end of selectStudents



#-------------
sub enterTests {
#-------------

    # foreach my $key ( sort keys %arr ) { print "K:$key V:$arr{$key}<br>\n"; }
    
    # Check for any Blanks in date
    if ( not $arr{date} ) {
	print qq{<h3>Date <b>$lex{Required}</b></h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    
    # Check for messed up Date Format
    my $errorflag;
    if ( $arr{date} =~ m/\// ) { # slashes rather than hyphens
	$errorflag = 1;
    } else {
	my ($y,$m,$d) = split('-', $arr{date});
	if ( not $m or ( $m < 1 or $m > 12 )) { $errorflag = 1; }
	if ( not $d or ( $d < 1 or $d > 31 )) { $errorflag = 1; }
    }
    if ( $errorflag ) {
	# print qq{<div>Year:$y Month:$m Day:$d</div>\n};
	print qq{<h3>$lex{'Test Date'} $lex{Error}: $arr{date}</h3>\n};
	print "</body></html>\n";
	exit;
    }

    my $date = $arr{date};
    delete $arr{date};
    # Done with date

    print qq{<h3>Date: $date</h3>\n};


    
    my ($sth, $groupname);
    if ( $arr{grade} ) { # we're picking a group
	$sth = $dbh->prepare("select lastname, firstname, studnum, grade from student
          where grade = ? order by lastname, firstname");
	$sth->execute( $arr{grade} );
	$groupname = qq{Grade $arr{grade}};
	
    } elsif ( $arr{homeroom} ) {
	$sth = $dbh->prepare("select lastname, firstname, studnum, grade from student
          where homeroom = ? order by lastname, firstname");
	$sth->execute( $arr{homeroom} );
	$groupname = qq{Homeroom $arr{homeroom}};
	
    } else { # Error... NOT everyone
	print qq{<h3>Missing Grade or Homeroom</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    
    # 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="date" value="$date">\n};


    # Save
    print qq{<div style="margin:0.3em;"><input type="submit" value="$lex{Save}"></div>\n};

    
    # Print Table Header and Heading values
    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
    print qq{<caption style="font-weight:bold;">Enter Writing Score 1-4<br>};
    print qq{Single Decimals allowed (2.8)</caption>\n};
    print qq{<tr><th>Student</th><th>Score</th></tr>\n};

    
    while ( my ( $lastname, $firstname, $studnum, $grade ) = $sth->fetchrow ) {
	print qq{<tr><td><b>$lastname</b>, $firstname (Gr $grade)</td>};
	print qq{<td class="cn"><input type="text" name="$studnum" style="width:3ch;" maxlength="3"></td></tr>\n};
    }

    print qq{</table>\n};
    print qq{<div style="margin:0.3em;"><input type="submit" value="$lex{Save}"></div>\n};

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

    exit;

}


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

    # foreach my $key ( sort keys %arr ) { print "K:$key V:$arr{$key}<br>\n"; }
    
    my $date = $arr{date};
    delete $arr{date};
    # Now only student scores left in hash

    # strip any missing scores (ie. blanks)
    foreach my $studnum ( sort keys %arr ) {
	if ( not $arr{$studnum} ) { # no score
	    delete $arr{$studnum};
	}
    }

    # Check for any values outside of range 1-4, and text characters
    foreach my $studnum ( sort keys %arr ) {
	if ( ($arr{$studnum} =~ m/[0-9]/) and ( $arr{$studnum} > 4 or $arr{$studnum} < 1 )) {
	    print qq{<h3>Score $arr{$studnum} is outside of allowed range (1-4)</h3>\n};
	    print qq{</body></html>\n};
	    exit;
	}
	if ( $arr{$studnum} =~ m/[a-zA-Z]/ ) {
	    print qq{<h3>$arr{$studnum} contains non-numeric values</h3>\n};
	    print qq{</body></html>\n};
	    exit;
	}
    }	

    
    # Get full student record
    my $sth1 = $dbh->prepare("select * from student where studnum = ?");

    
    # Check for existing record with same date and student.
    my $sth = $dbh->prepare("select count(*) from write_scores where studnum = ? and tdate = ?");
    foreach my $studnum ( sort keys %arr ) {
	$sth->execute( $studnum, $date);
	my $count = $sth->fetchrow;
	if ( $count ) {
	    # Get Name
	    $sth1->execute($studnum);
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    my $ref = $sth1->fetchrow_hashref;
	    my %r = %$ref;
	    
	    print qq{<h3>Record exists for $date for student $r{firstname} $r{lastname} ($studnum)</h3>\n};
	    print qq{</body></html>\n};
	    exit;
	}
    }
    
    # foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }

    
    # Get Season from Date
    my ($y,$m, $d) = split( '-', $date );
    my $season = 'Undefined';

    if ( $m == 9 or $m == 10 ) { # September, October - Fall (Sept 1 - Oct 31 );
	$season = qq{$y-Fall};

    } elsif ( $m == 1 or $m == 2 or $m == 3  ) { # Spring Jan 1 to March 31
	$season = qq{$y-Spring};
	
    } elsif ( $m == 6 or ($m == 5 and $d >= 15 ) ) { # Summer May 15 to June 30
	$season = qq{$y-Summer};
    }
    # Otherwise season is undefined.
    print qq{<h3>Season $season - $date</h3>\n};


    
    # Write the test record
    my $sth = $dbh->prepare("insert into write_scores
    	 ( studnum, tdate, tauthor, tgrade, tage, score, season ) 
         values ( ?, ?, ?, ?, ?, ?, ?) ");

    
    foreach my $studnum ( keys %arr ) {

	my $score = $arr{$studnum};
	
	# Get Student Record
	$sth1->execute( $studnum);
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $ref = $sth1->fetchrow_hashref;
	my %r = %$ref;

	# Get age.
	my $age = calcAge($r{birthdate}, $currdate);
	
	$sth->execute( $studnum, $date, $userid, $r{grade}, $age, $score, $season );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	print qq{<div>Score $score Added for $r{firstname} $r{lastname} ($studnum)</div>\n};
	
    }

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

    exit;
}


#----------
sub calcAge {
#----------

    # Passed (birthdate, $currdate)
    my ( $birthdate, $currdate ) = @_;
    my ($byear,$bmonth,$bday) = split /-/,$birthdate;
    my ($cyear,$cmonth,$cday) = split /-/,$currdate;
    my $age = $cyear - $byear;
    my $month = $cmonth - $bmonth;
    #print qq{BD: $birthdate CD: $currdate Age: $age MO:$month<br>\n";

    if ($cmonth < $bmonth){
	$month = $month + 12;
	if ($cday < $bday){ $month--;}
	$age--;
    }
    elsif ($cmonth == $bmonth and $cday < $bday){
	$age--; 
	$month = 11;
    } elsif ($cmonth > $bmonth and $cday < $bday) {
	$month--;
    }

    if ( $age < 0 or $age > 100 ) { $age = 0; $month = 0; }

    return qq{$age:$month};

}


