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

#  This file is part of Open Admin for Schools.

my %lex = ('Main' => 'Main',
	   'Error' => 'Error',
	   'Add Reading Tests' => 'Add Reading Tests',
	   'Student' => 'Student',
	   'Reading Level' => 'Reading Level',
	   'Continue' => 'Continue',
	   'Category' => 'Category',	   
	   'Name' => 'Name',
	   'Save' => 'Save',
	   'Score' => 'Score',
	   'Test Date' => 'Test Date',
	   'Values must be from 1-4' => 'Values must be from 1-4',
	   'No User Id' => 'No User Id',
	   'No Password' => 'No Password',
	   'Please Log In' => 'Please Log In',
	   'Grade' => 'Grade',
	   'Homeroom' => 'Homeroom',
	   'Select' => 'Select',
	   'Blank=All' => 'Blank=All',
	   'Check' => 'Check',
	   'Record Exists' => 'Record Exists',
	   'Edit Record' => 'Edit Record',
	   'Required' => 'Required',
	   'Only' => 'Only',
	   'No Blanks Allowed' => 'No Blanks Allowed',
	   'Skipping' => 'Skipping',
	   'Next Page' => 'Next Page',
	   'Absences' => 'Absences',

	   );

use DBI;
use CGI;
use Cwd;

my @fields = ('shortvowels','digraphs','vce','longerwords','endspellpat','rctrlvowels','longvowelteams',
	      'othervowels','dipsilent','suffixprefix','addaffix');

my %fieldtext = ('shortvowels' => 'Short Vowels','digraphs' => 'Digraphs','vce' => 'VCe',
		 'longerwords' => 'Longer Words','endspellpat' => 'Ending Spelling Patterns',
		 'rctrlvowels' => 'R-Controlled Vowels','longvowelteams' => 'Long Vowel Teams',
		 'othervowels' => 'Other Vowels','dipsilent' => 'Diphthongs &amp; Silent Letters',
		 'suffixprefix' => 'Suffixes &amp; Prefixes','addaffix' => 'Additional Affixes');


my %exceptions = ( 'moved' => 'Moved', 'attendance' => 'Persistent Absences',
		   'altprog' => 'Alternate Program', 'other' => 'Other' );
my @exceptions = ( 'moved', 'attendance', 'altprog', 'other');


my $self = 'ufliTestAdd.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 Placement Tests - UFLI};
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};
    selectStudents();

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

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

} elsif ( $arr{page} == 4 ) {
    delete $arr{page};
    writeExceptions();
}



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

    # Get Grades, Homerooms
    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;

    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};

    # Test Date
    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="ra" colspan="2">$lex{Select} $lex{Student} - Use Ctrl Key for Multiple</td></tr>\n};
    print qq{<tr><td class="bra">Grade</td><td><select name="grade" multiple>};
    foreach my $grade ( @grades ) {
	print qq{<option>$grade</option>\n};
    }
    print qq{</select> <b>or</b></td></tr>\n};

    # Students - Homerooms
    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="bra">Homeroom</td><td>};
    print qq{<select name="homeroom" multiple>\n};
    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>\n};
    print qq{ $lex{'Blank=All'}</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 };
	    print qq{<span style="font-size:120%;">$lex{Required}</span></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, @grades, @homerooms, @groups);
    if ( $arr{grade} ) { # we're picking a group
	@grades = $q->multi_param(grade);
	$groupname = qq{Grade};
	$sth = $dbh->prepare("select lastname, firstname, studnum, grade, homeroom from student
          where grade = ? order by lastname, firstname");
	@groups = @grades;
    } elsif ( $arr{homeroom} ) {
	@homerooms = $q->multi_param(homeroom);
	$groupname = qq{Homeroom};
	$sth = $dbh->prepare("select lastname, firstname, studnum, grade, homeroom from student
          where homeroom = ? order by lastname, firstname");
	@groups = @homerooms;
    } else { # everyone
	$sth = $dbh->prepare("select lastname, firstname, studnum from student
          order by lastname, firstname");
	$groupname = qq{Entire School};
	@groups = ('All');
    }

    
    
#    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{<div><input type="submit" value="$lex{Continue}"></div>\n};

    foreach my $grp ( @groups ) {
	if ($grp eq 'All' ) {
	    $sth->execute;
	} else {
	    $sth->execute($grp);
	}
    
	print qq{<table cellpadding="3" cellspacing="0" border="0" };
	print qq{style="border:1px solid gray;margin:0.5em;padding:0.5em;float:left;">\n};
    
	print qq{<td colspan="3"><b>Test</b> - Add Test Score / <b>Absent</b> - };
	print qq{Add Reason for Absence</td></tr>\n};

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

	while ( my ( $lastname, $firstname, $studnum, $grade, $homeroom ) = $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{</table>\n};
    }
    
    print qq{<div style="clear:left;"><input type="submit" value="$lex{Continue}"></div>\n};

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

    exit;

} # end of selectStudents



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

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

    
    print qq{<table border="0" style="margin-bottom:1em;">\n};
    print qq{<tr><td class="ra">Date</td><td class="bla">}. fmtDate($date). qq{</td></tr>\n};
    print qq{</table>\n};
    
    my $sth = $dbh->prepare("select lastname, firstname, grade from student where studnum = ?");
    my @absent;
    my @students;
    my %students;
    # Extract the absences
    foreach my $key ( keys %arr ) {
	my ($flag, $id ) = split(':', $key);
	if ( $flag eq 'ABS' ) {
	    push @absent, $id;
	    delete $arr{$key};
	} else {
	    $sth->execute( $key );
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	    my ( $ln, $fn, $gr) = $sth->fetchrow;
	    $students{"$ln$fn$key"} = $key;
	}
    }

    # sort students by name
    foreach my $key ( sort keys %students ) {
	push @students, $students{$key};
    }


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

    foreach my $studnum ( @absent ) {
	print qq{<input type="hidden" name="ABS:$studnum" value="$studnum">\n};
    }


    my $first = 1;

    my $count = 0;
    foreach my $studnum ( @students ) {

	if ( $first ) {
	    print qq{<div class="la"><input type="submit" value="$lex{Save}"></div>\n};
	    $first = 0;
	}


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

	
	# Print Table Header and Heading values
	print qq{<table cellpadding="3" cellspacing="0" border="1" style="float:left;margin:0.5em;">\n};
	print qq{<caption style="margin-left:0.5em;font-weight:bold;font-size:120%;color:#083;">};
	print qq{$firstname $lastname</caption>\n};

	foreach my $field ( @fields ) {
	    print qq{<tr><td class="bra">$fieldtext{$field}</td>};
	    print qq{<td><input type="text" name="$studnum:$field" style="width:2ch;"></td></tr>\n};
	}
    
	print qq{</table>\n};

	$count++;
	if ( $count % 3 == 0 ) {
	    print qq{<div style="clear:left;"></div>\n};
	}
	

    }

    if ( $first ) { # no student tests, could be absences
	if ( @absent ) {
	    print qq{<h3 class="la"><input type="submit" };
	    print qq{value="$lex{Continue} to $lex{Absences}"></h3>\n};

	} else { # No students, no absences. Stop
	    print qq{<h3>$lex{'No Students Found'}</h3>\n};
	    print qq{</body></html>\n};
	    exit;
	}

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

    exit;

}


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

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

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

=head    
    # 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};
=cut    

    # Extract the absences
    my @absent;
    foreach my $key ( keys %arr ) {
	my ($flag, $id ) = split(':', $key);
	if ( $flag eq 'ABS' ) {
	    push @absent, $id;
	    delete $arr{$key};
	} 
    }

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


    my %data;
    foreach my $key ( sort keys %arr ) {
	if ( not $arr{$key} ) { next; }
	my ($studnum,$field) = split(':', $key);
	$data{$studnum}{$field} = $arr{$key};
    }


#    foreach my $studnum ( sort keys %data ) {
#	foreach my $field ( sort keys %{ $data{$studnum}} ) {
#	    print qq{<div>$studnum / $field / $data{$studnum}{$field}</div>\n};
#	}
#    }
    # we now have data in %data hash.

    my $sth2 = $dbh->prepare("select lastname, firstname, grade from studentall3 where studnum = ?");

    foreach my $studnum ( keys %data ) {

	# Check for existing test for this student and this date.
	my $sth = $dbh->prepare("select id from fp_ufli_test where studnum = ? and tdate = ? and tauthor = ?");
	$sth->execute( $studnum, $date, $userid );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $id = $sth->fetchrow;

	   
	# Get Student Name, Grade
	$sth2->execute( $studnum );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my ($lastname, $firstname, $grade ) = $sth2->fetchrow;

	if ( $id ) { # we've already written this record..

	    print qq{<h3>$lex{'Record Exists'}\n};
	    print qq{ / $firstname $lastname ($studnum) / };
	    print qq{$lex{'Test Date'}: $tdate / <b>$lex{Skipping}</h3>\n};
	    next;
	}

	my (@fields, @values, @qst );
	foreach my $fld ( sort keys %{ $data{$studnum}} ) {
	    push @fields, $fld;
	    push @values, $data{$studnum}{$fld};
	    push @qst, '?';
	}

	# add additional fields
	push @fields, studnum;
	push @values, $studnum;
	push @qst, '?';

	push @fields, tdate;
	push @values, $date;
	push @qst, '?';

	push @fields, tauthor;
	push @values, $userid;
	push @qst, '?';

	push @fields, tgrade;
	push @values, $grade;
	push @qst, '?';

	my $fields = join(',',@fields );
	my $qst = join(',',@qst);
			  
	# Write the record 
	my $sth = $dbh->prepare("insert into fp_ufli_test ( $fields ) values($qst)");
	$sth->execute( @values );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }

	print qq{<div>Record added for <b>$firstname $lastname</b> grade $grade</div>\n};
    
    }

    
    # Add SSP Exceptions for absent students
    my $sth = $dbh->prepare("select lastname, firstname, grade from studentall where studnum = ?");

    my $first = 1;
    foreach my $studnum ( @absent ) {

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

	if ( $first ) {
	    # Print Form Heading
	    print qq{<form action="$self" method="post"> \n};
	    print qq{<input type="hidden" name="page" value="4">\n};
	    print qq{<input type="hidden" name="tdate" value="$date">\n};
	    
	    # Table
	    print qq{<p></p><div class="la"><input type="submit" value="$lex{Save}"></div>\n};
	    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
	    print qq{<tr><th>$lex{Student}</th><th>Reasons for No Student Score</th></tr>\n};
	    $first = 0;
	}

	print qq{<tr><td class="bra">$r{firstname} $r{lastname}</td>};
	print qq{<td class="la">};
	foreach my $key ( @exceptions ) {
	    print qq{<input type="radio" name="EX:$studnum" value="$key">$exceptions{$key}<br>\n};
	}
	print qq{<span style="font-size:80%;">If Other, Please Specify</span> <input type="text" };
	print qq{size="60" name="OTHER:$studnum"></td></tr>\n};

    }

    if ( not $first ) { 
	print qq{</table>\n};
	print qq{<div class="la"><input type="submit" value="$lex{Save}"></div>\n};
	print qq{</form>\n};

    } else {
	print qq{<p>[ <a href="$tchpage">$lex{Main}</a> ]</p>\n};
    }

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

    exit;
}



#------------------
sub writeExceptions {
#------------------

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

    my $sth1 = $dbh->prepare("select * from studentall where studnum = ?");

    foreach my $key ( keys %arr ) {

	my ($type, $studnum ) = split(':', $key);

	if ( $type eq 'OTHER' ) { next; } # skip all 'Other' values.

	my $othercode = qq{OTHER:$studnum};
	my $reasonother = $arr{$othercode};
	my $reason = $arr{$key};


	# Check for existing record
	my $sth = $dbh->prepare("select count(*) from ssp_exceptions where studnum = ? and 
           tdate = ? and ssptype = ?");
	$sth->execute( $studnum, $tdate, 'dra' );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $count = $sth->fetchrow;

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

	if ( $count ) { # we've already written this record..
	    print "<div><b>$lex{'Record Exists'}</b>\n";
	    print "- $rec{firstname} $rec{lastname} ($studnum)";
	    print "<b>$lex{Test} $lex{Date}:</b> $tdate -<b>$lex{Skipping}</h3>\n";

	    next;
	}

	my $age = calcAge( $r{birthdate}, $tdate );
	my $treatynum = $r{treaty};
	if ( not $treatynum ) { $treatynum = $r{provnum}; }

	# Insert a record.
	$sth = $dbh->prepare("insert into ssp_exceptions
          ( studnum, treatynum, ssptype, tdate, tauthor, tgrade, tage, reasoncode, reasonother ) 
          values ( ?, ?, ?, ?, ?, ?, ?, ?, ? )");
	 $sth->execute( $studnum, $treatynum, 'FP-UFLI', $tdate, $userid, $r{grade}, $age, 
			$reason, $reasonother );
        if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }

	print qq{<div><b>$r{firstname} $r{lastname}</b> Exception Record Added</div>\n};

    }

    print qq{<p>[ <a href="$self">$title</a> |\n};
    print qq{<a href="$tchpage">$lex{Main}</a> ]</p>\n};
    print qq{</body></html>\n};

    exit;

} # end of writeExceptions



#----------
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};

}


#----------
sub fmtDate {
#----------

    my ( $year, $mon, $day ) = split '-', shift;
    return "$s_month[$mon] $day, $year";
}
