#!/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',
	   'View' => 'View',
	   'Math' => 'Math',
	   'Name' => 'Name',
	   'Date' => 'Date',
	   'Author' => 'Author',
	   'Scores' => 'Scores',
	   'Score' => 'Score',
	   'Age' => 'Age',
	   'Grade' => 'Grade',
	   'No Records Found' => 'No Records Found',
	   'Continue' => 'Continue',
	   'Select' => 'Select',
	   'Students' => 'Students',
	   'Check' => 'Check',
	   'Homeroom' => 'Homeroom',
	   'Grade' => 'Grade',
	   'Blank=All' => 'Blank=All',
	   'Edit' => 'Edit',
	   'Tests' => 'Tests',
	   'Delete' => 'Delete',
	   'Start Date' => 'Start Date',
	   'End Date' => 'End Date',
	   'Equivalent' => 'Equivalent',
	   'Next Page' => 'Next Page',
	   'No Blanks Allowed' => 'No Blanks Allowed',
	   'Student' => 'Student',
	   'Period' => 'Period',
	   'Date' => 'Date',

	   );

use DBI;
use CGI;

my $self = 'mathTestView.pl';
my $editscript = 'mathTestEdit.pl';
my $deletescript = 'mathTestDelete.pl';

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

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


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

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


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


# Page Header
my $title = qq{$lex{View} $lex{Math} $lex{Scores}};
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$tchcss" type="text/css">\n};


if ( not $arr{page} ) { # calendar popup.
    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};
    showTests();
} 


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

    # Find Tests by Student Group
    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" };
    print qq{style="padding:0.5em;border:1px solid gray;">\n};

    print qq{<tr><td class="ra">$lex{Select} $lex{Students}\n};
    print qq{</td><td class="la"><select name="groupname">};
    print qq{<option value="grade">$lex{Grade}</option>\n};
    print qq{<option value="homeroom">$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 class="ra">$lex{Check} $lex{'Next Page'}</td>\n};
    print qq{<td><input type="checkbox" name="chk" value="1">\n};
    print qq{</td></tr>\n};

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

    print qq{<tr><td class="ra">$lex{'End Date'}</td><td><input type="text" };
    print qq{name="enddate" id="edate" size="10" value="$currdate">};
    print qq{<button type="reset" id="end_trigger">...</button></td></tr>\n};


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

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

    print qq{<script type="text/javascript">
     Calendar.setup({
        inputField     :    "sdate", 
        ifFormat       :    "%Y-%m-%d",
        button         :    "start_trigger",
        singleClick    :    false,
        step           :    1
    });

    Calendar.setup({
        inputField     :    "edate",
        ifFormat       :    "%Y-%m-%d",
        button         :    "end_trigger",
        singleClick    :    false,
        step           :    1
    });
   </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;
    if ( $arr{chk} ) {
	$chk = 'CHECKED';
    }
    delete $arr{chk};

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

    my $select;
    if ( $groupvalue ) { # we're picking a group
	if ( $arr{groupname} eq '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; }

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

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

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

    my $sth1 = $dbh->prepare("select count(*) from math_fstep where studnum = ?");
    
    print qq{<tr><th>$lex{Student}</th><th>$lex{Tests}</th><th></th></tr>\n};

    while ( my ( $lastname, $firstname, $studnum ) = $sth->fetchrow ) {
	
	$sth1->execute( $studnum );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $count = $sth1->fetchrow;

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

    }

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

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

    exit;

} # end of selectStudents



#------------
sub showTests {
#------------

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

    my $startdate = $arr{startdate};
    my $enddate = $arr{enddate};
    delete $arr{startdate};
    delete $arr{enddate};


    # Searching by Student Number

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

    # sort by name.
    my %sort = ();
    foreach my $studnum ( keys %arr ) { 
	$sth1->execute( $studnum );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my ( $lastname, $firstname ) = $sth1->fetchrow;
	$sort{"$lastname$firstname$studnum"} = $studnum;
    }


    my $first = 1;

    print qq{<style>td.blue { background-color:blue;color:white; }\n};
    print qq{td.red { background-color:#F00;color:white; }</style>\n};

    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
    print qq{<tr><th>$lex{Name}</th><th>$lex{Age}</th><th>$lex{Grade}</th>\n};
    print qq{<th>$lex{Score}</th><th>$lex{Period}</th><th>$lex{Date}</th>\n};
    print qq{<th>$lex{Author}</th><th></th><th></th></tr>\n};

    foreach my $key ( sort keys %sort ) {

	my $studnum = $sort{$key};

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


	# Display Existing Tests (if any)
	my $sth = $dbh->prepare("select * from math_fstep
         where studnum = ? and to_days( tdate ) >= to_days( '$startdate' ) 
         and to_days( tdate ) <= to_days( '$enddate') order by tdate, id");


	$sth->execute( $studnum );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	while ( my $ref = $sth->fetchrow_hashref ) {

	    $first = 0;

	    my ($yr,$mo) = split(/:/, $ref->{tage});
	    my $age = $yr. 'y'. $mo. 'm';
	    
	    my $score = $ref->{tphase};
	    my $val = $score_AgeRange{ $score };
	    my ($min, $max) = split( /-/, $score_AgeRange{$score} );

	    my $color;
	    if ( $yr < $min ) { $color = 'blue'; }
	    if ( $yr > $max ) { $color = 'red'; }

	    print qq{<tr><td class="la"><b>$lastname</b>, $firstname</td>\n};
	    print qq{<td class="cn">$age</td>\n};
	    print qq{<td class="cn">$ref->{tgrade}</td>\n};
	    print qq{<td class="la $color">$ref->{tphase}</td>\n}; # $min $max removed
	    print qq{<td class="la">$ref->{tseason}</td>\n};
	    print qq{<td class="la">$ref->{tdate}</td>\n};
	    print qq{<td>$ref->{tauthor}</td>\n};

	    # Edit Button
	    print qq{<td><form action="$editscript" method="post" target="_blank" };
	    print qq{style="display:inline;">\n};
	    print qq{<input type="hidden" name="testid" value="$ref->{id}">\n};
	    print qq{<input type="submit" value="$lex{Edit}">\n};
	    print qq{</form></td>\n};

	    # Delete Button
	    print qq{<td><form action="$deletescript" method="post" target="_blank" };
	    print qq{style="display:inline;">\n};
	    print qq{<input type="hidden" name="testid" value="$ref->{id}">\n};
	    print qq{<input type="submit" value="$lex{Delete}">\n};
	    print qq{</form></td>\n};

	    print qq{</tr>\n\n};


	} # end of student loop.

	if ( $first ) {
	    print qq{<div style="font-weight:bold;">};
	    print qq{$lex{'No Records Found'}</div>\n};
	}

    } # end of student number loop

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

}
