#!/usr/bin/perl
#  Copyright 2001-2021 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 = ('Main' => 'Main',
	   'Error' => 'Error',
	   'Math' => 'Math',
	   'Add' => 'Add',
	   'Math Tests' => 'Math Tests',
	   'Student' => 'Student',
	   'Continue' => 'Continue',
	   'Name' => 'Name',
	   'Save' => 'Save',
	   'Date' => 'Date',
	   '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',
	   'Skipping' => 'Skipping',
	   'Next Page' => 'Next Page',
	   'Period' => 'Period',
	   'Students' => 'Students',
	   'Test' => 'Test',
	   'Missing Value' => 'Missing Value',
	   'Score' => 'Score',
	   'Record Exists' => 'Record Exists',
	   'Added' => 'Added',

	   );

use DBI;
use CGI;
use CGI::Session;


my $self = 'mathTestAdd.pl';

# Now loaded from config
# my @phases = qw(Emergent Matching Quantifying Partitioning Factoring Operating);
# my @seasons = qw(Sep-2012 Nov-2012 Apr-2013 Sep-2013 Nov-2013 Apr-2014 Sep-2014 Nov-2014);


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

eval require "./fsim.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);


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

# Get/Set  Session Values (a defined userid means it was passed)
if ( $arr{userid} ){ # we want to login, passed userid/password pair.

    # Check password/userid against database (-1 no user, -2 wrong password);
    my $error = checkPassword($arr{userid}, $arr{password}, $dbh);
    if ($error == -1){ print $q->header( -charset, $charset ); login($lex{'No User Id'}); }
    if ($error == -2){ print $q->header( -charset, $charset ); login($lex{'No Password'}); }

    $cookietime = checkCookieTime( $arr{duration} );

    # Set values for userid and logged_in in session
    $session->param( 'logged_in','1');
    $session->expire( 'logged_in', $cookietime );
    $session->param( 'userid',$arr{userid} );
    $session->param( 'duration',$cookietime );

    $userid = $arr{userid};


} else { # check logged_in value in session

    if ( not $session->param('logged_in') ){
	$userid = $session->param('userid');
        print $q->header( -charset, $charset );
        print qq{$lex{'Please Log In'}</body></html>\n}; 
        exit;
    }
    # Ok, we have a login. Values below we have in environment.

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

    if ( not ($duration =~ /\+/)) { # if not in +20m format, do so.
	$duration = checkCookieTime( $duration );
    }

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


} # End of check for logged_in value

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

# Session Setup End

# Page Header
my $title = "$lex{Add} $lex{'Math Tests'}";
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$tchcss" 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();
}


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

    print qq{<tr><td align="right">$lex{Test} $lex{Date}</td>\n};
    print qq{<td><input type="text" name="tdate" id="date" size="10" value="$currdate">\n};
    print qq{<button type="reset" id="start_trigger">...</button>\n};
    print qq{</td></tr>\n};


    print qq{<tr><td align="right">$lex{Test} $lex{Period}</td>\n};
    print qq{<td><select name="tseason"><option></option>\n};
    foreach my $season ( @seasons ) {
	print qq{<option>$season</option>\n};
    }
    print qq{</select></td></tr>\n};


    print qq{<tr><td align="right">$lex{Select} $lex{Students}\n};
    print qq{</td><td><select name="groupname">};
    print qq{<option>$lex{Grade}</option>\n};
    print qq{<option>$lex{Homeroom}</option>\n};
    print qq{</select>\n};
    print qq{<input type="text" name="groupvalue" size="10"> $lex{'Blank=All'}</td></tr>\n};

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

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

    print qq{</table></center>\n};
    print qq{</form></center>\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 qq{K:$key V:$arr{$key}<br>\n}; }    

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

    # Check for any Blanks
    foreach my $key ( sort keys %arr ) { 
	if ( not $arr{$key} ) {
	    print qq{<h3>$lex{'Missing Value'}: $key</h3>\n};
	    print qq{</body></html>\n};
	    exit;
	}
    }

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

    print qq{<div style="font-size:130%;"><b>$lex{Test} $lex{Date}</b> $arr{tdate}</div>\n};
    print qq{<div style="font-size:130%;"><b>$lex{Test} $lex{Period}</b> $arr{tseason}</div>\n};


    # 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="tseason" value="$arr{tseason}">\n};
    print qq{<input type="hidden" name="tdate" value="$arr{tdate}">\n};

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

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


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

	print qq{<tr><td class="la"><input type="checkbox" name="$studnum" value="1" $chk>\n};
	print qq{ <b>$lastname</b>, $firstname ($studnum)</td></tr>\n};

    }

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

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

    exit;

} # end of selectStudents



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

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

    my $tdate = $arr{tdate};
    delete $arr{tdate};
    my $tseason = $arr{tseason};
    delete $arr{tseason};
    # Now only student numbers left in hash...

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

    my %studnames = ();
    my %students = ();

    foreach my $studnum ( keys %arr ) {
	# Get Student Info
	$sth->execute( $studnum );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $studref = $sth->fetchrow_hashref;
	my $lastname = $studref->{lastname};
	my $firstname = $studref->{firstname};
	$studnames{"$lastname$firstname$studnum"} = $studnum;
	$students{$studnum} = $studref;

    }

#    use Data::Dumper;
#    print Dumper %students;

    # 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="tseason" value="$tseason">\n};
    print qq{<input type="hidden" name="tdate" value="$tdate">\n};

    print qq{<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>$lex{Score}</th></tr>\n};

    foreach my $key ( sort keys %studnames ) {

	my $studnum = $studnames{$key};

	# Get Student Name
	$sth->execute( $studnum );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my %rec = %{ $students{$studnum} };
	print qq{<tr><td class="ra"><b>$rec{lastname}</b>, $rec{firstname}</td>\n};
	print qq{<td class="la"><select name="$studnum"><option></option>\n};
	foreach my $phase ( @phases ) {
	    print qq{<option>$phase</option>\n};
	}
	print qq{</select></td></tr>\n};
    }

    print qq{</table><div class="la"><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 $tdate = $arr{tdate};
    delete $arr{tdate};
    my $tseason = $arr{tseason};
    delete $arr{tseason};
    # Now only student scores left in hash...

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

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

    foreach my $studnum ( keys %arr ) {

	my $score = $arr{$studnum};
	if ( not $score ) { next; }  # skip blank scores

	# Check for existing test for this student, this reading level, and this date.
	my $sth = $dbh->prepare("select count(*) from math_fstep where studnum = ? and tseason = ?");
	$sth->execute( $studnum, $tseason );
	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 %rec = %$studref;

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

                next;
	}

	my $age = calcAge( $rec{birthdate}, $tdate );

	# Insert a record.
	$sth = $dbh->prepare("insert into math_fstep  
          ( studnum, treatynum, tphase, tseason, tdate, tage, tauthor, tgrade) 
          values ( ?, ?, ?, ?, ?, ?, ?, ? )");
	 $sth->execute( $studnum, $rec{treaty}, $score, $tseason, $tdate, $age, $userid, $rec{grade} );
        if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }

	print qq{<div>$rec{firstname} $rec{lastname} $lex{Added}</div>\n};

    }

    print qq{<p>[ <a href="$self">$lex{Add} $lex{'Math Tests'}</a> |\n};
    print qq{<a href="$tchpage">$lex{Main}</a> ]</p>\n};
    print qq{</center></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 "$age:$month";

}
