#!/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 Reading Scores' => 'View Reading Scores',
	   'Reading Level' => 'Reading Level',
	   'Category' => 'Category',
	   'Name' => 'Name',
	   'Date' => 'Date',
	   'Author' => 'Author',
	   'Score' => 'Score',
	   'No Records Found' => 'No Records Found',
	   'Continue' => 'Continue',
	   'Select' => 'Select',
	   'Student' => 'Student',
	   'Chk' => 'Chk',
	   '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',

	   );

use DBI;
use CGI;
use Cwd;

my $self = 'readTestView.pl';
my $editscript = 'readTestEdit.pl';
my $deletescript = 'readTestDelete.pl';

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


# Get current dir so know what CSS to display and shift settings.
if ( getcwd() !~ /tcgi/ ) { # we are in cgi
    $tchcss = $css;
    $tchpage = $homepage;
    $tchdownloaddir = $downloaddir;
    $tchwebdownloaddir = $webdownloaddir;
}


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

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


# Page Header
my $title = $lex{'View Reading 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 fmtDate {
#----------

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



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

    # Get global reading levels.
    my %readinglevel;
    my @readinglevel;

    # Load DRA2/DRA3 recs
    foreach my $table ( 'read_level_dra2', 'read_level_dra3' ) {
	my $sth = $dbh->prepare("select distinct readlevel from $table
				where readlevel is not NULL");
	$sth->execute;
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	while ( my $rl = $sth->fetchrow ) {
	    $readinglevel{$rl} = 1;
	}
    }
    
    @readinglevel = sort { $a <=> $b } keys %readinglevel;

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


    # Find by Reading Level.
    print qq{<form action="$self" method="post"> \n};
    print qq{<input type="hidden" name="page" value="2">\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="bra">$lex{'Reading Level'}</td>\n};
    print qq{<td><select name="readlevel"><option></option>\n};
    foreach my $rl ( @readinglevel ) {
	print qq{<option>$rl</option>\n};
    }
    print qq{</select></td></tr>\n};

    print qq{<tr><td class="bra">$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="bra">$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}">\n};
    print qq{</td></tr>\n};
    print qq{</table></form><p></p>\n};


    # Find by Student Group
    my (@homerooms, @grades );
    my $sth = $dbh->prepare("select distinct homeroom from student");
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    while ( my $hr = $sth->fetchrow ) {
	push @homerooms, $hr;
    }

    $sth = $dbh->prepare("select distinct grade from student");
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    while ( my $gr = $sth->fetchrow ) {
	push @grades, $gr;
    }
    @grades = sort {$a <=> $b} @grades;

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

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



    print qq{<tr><td colspan="2" class="cn">OR</td></tr>\n};

    # Select Homeroom
    # 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="bra">$lex{Select} $lex{Homeroom}</td>\n};
    print qq{<td class="la"><select name="homeroom"><option></option>\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></td></tr>\n};

#    print qq{<tr><td class="bra">$lex{Select} $lex{Homeroom}</td>\n};
#    print qq{<td><select name="homeroom"><option></option>\n};
#    foreach my $hr ( @homerooms ) {
#	print qq{<option>$hr</option>\n};
#    }
#    print qq{</select></td></tr>\n};

    # print qq{<input type="text" name="groupvalue" size="10">$lex{'Blank=All'}</td></tr>\n};

    print qq{<tr><td class="bra">$lex{Chk} $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="bra">$lex{'Start Date'}</td><td><input type="text" };
    print qq{name="startdate" id="sdate2" size="10" value="$schoolstart">};
    print qq{<button type="reset" id="start_trigger2">...</button>\n};
    print qq{</td></tr>\n};

    print qq{<tr><td class="bra">$lex{'End Date'}</td><td><input type="text" };
    print qq{name="enddate" id="edate2" size="10" value="$currdate">};
    print qq{<button type="reset" id="end_trigger2">...</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
    });

     Calendar.setup({
        inputField     :    "sdate2",
        ifFormat       :    "%Y-%m-%d",
        button         :    "start_trigger2",
        singleClick    :    false,
        step           :    1
    });

    Calendar.setup({
        inputField     :    "edate2",
        ifFormat       :    "%Y-%m-%d",
        button         :    "end_trigger2",
        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 $chk;
    if ( $arr{chk} ) {
	$chk = 'CHECKED';
    }
    delete $arr{chk};

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


    my ($select, $value);
    if ( $arr{grade} ) {
	$select = 'where grade = ?';
	$value = $arr{grade};
    } elsif ( $arr{homeroom} ) {
	$select = 'where homeroom = ?';
	$value = $arr{homeroom};
    }

    my $sth = $dbh->prepare("select lastname, firstname, studnum from student
      $select order by lastname, firstname");
    if ( $select ) {
	$sth->execute( $value );
    } 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{<div><input type="submit" value="$lex{Continue}"></div>\n};
    
    print qq{<table cellpadding="3" cellspacing="0" border="0" };
    print qq{style="border:1px solid gray;padding:0.5em;margin:0.5em;">\n};

    my $sth1 = $dbh->prepare("select count(*) from read_test where studnum = ? and 
      to_days( tdate ) >= to_days( '$arr{startdate}' ) 
      and to_days( tdate ) <= to_days( '$arr{enddate}')");
    
    my $sth2 = $dbh->prepare("select count(*) from read_test where studnum = ?");

    print qq{<tr><th>$lex{Student}</th><th>$lex{Tests}</th><th></th></tr>\n};

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

	# Count of All Tests
	$sth2->execute( $studnum );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $overallcount = $sth2->fetchrow;

	print qq{<tr><td class="ra">$lastname, $firstname ($studnum)</td>\n};
	print qq{<td style="text-align:center;">$count / $overallcount</td><td>};
	print qq{<input type="checkbox" name="$studnum" value="1" $chk></td></tr>\n};
    }

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

    print qq{</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}; }

    # Load the reading library containing the scoreToGrade function.
    eval require "../../lib/libreading.pl";
    if ( $@ ) {
	print $lex{Error}. " $self: $@<br>\n";
	die $lex{Error}. "$self: $@\n";
    }

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


    if ( $arr{readlevel} ) { # search by reading level, current year.

	my $sth = $dbh->prepare("select * from read_test where readlevel = ? 
         and to_days( tdate ) >= to_days( '$startdate' ) 
         and to_days( tdate ) <= to_days( '$enddate') order by tdate desc, id");
	# Note: Later add a selection by current year as well...
	$sth->execute( $arr{readlevel} );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

	my $sth1 = $dbh->prepare("select lastname, firstname from studentall where studnum = ?");
	my $sth2 = $dbh->prepare("select category, name, score from read_test_score 
         where testid = ? order by seq");

	my $first = 1;

	while ( my ( $id, $studnum, $readlevel, $tdate, $tauthor ) = $sth->fetchrow ) {

	    $first = 0;

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

	    print qq{div style="float:left;">\n};
	    
	    print qq{<div style="font-size:100%; font-weight:bold;">$firstname $lastname - };
	    print qq{$lex{'Reading Level'} $readlevel<br>\n};
	    print qq{$lex{Date} }. fmtDate($tdate). qq{ $lex{Author} $tauthor \n};


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

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

	    
	    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
	    print qq{style="margin-bottom:1em;margin:0.4em;">\n};
	    print qq{<tr><th>$lex{Category}</th><th>$lex{Name}</th>};
	    print qq{<th>$lex{Score}</th></tr>\n};

	    $sth2->execute( $id );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    
	    my $totalscore;
	    while ( my ( $category, $name, $score ) = $sth2->fetchrow ) {
		$totalscore += $score;
		print qq{<tr><td>$category</td><td>$name</td><td class="cn">$score</td></tr>\n};
	    }

	    my $equivgrade = scoreToGrade( $totalscore, $readlevel );
	    print qq{<tr><td colspan="2" style="text-align:right;font-weight:bold;">};
	    print qq{$lex{'Equivalent'} $lex{Grade}</td><td class="cn">$equivgrade</td></tr>\n};

	    print qq{</table></div>\n};  # end of floated div.

	}

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

	# End of Reading Level Search.

    } else { # Searching by Student Number

	my $sth1 = $dbh->prepare("select lastname, firstname from studentall where studnum = ?");
	my $sth2 = $dbh->prepare("select category, name, score from read_test_score 
         where testid = ? order by seq");

	my $first = 1;

	foreach my $studnum ( sort keys %arr ) {

	    # 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 id, readlevel, tdate, tauthor, tgrade 
              from read_test 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 ( $id, $readlevel, $tdate, $tauthor, $tgrade ) = $sth->fetchrow ) {

		$first = 0;
		
		print qq{<div style="float:left;">\n};
		
		print qq{<div style="font-size:100%;font-weight:bold;">$firstname $lastname };
		print qq{$lex{'Reading Level'} $readlevel<br>\n};
		print qq{$lex{Date} $tdate  $lex{Author} $tauthor\n};

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

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

		print qq{<table cellpadding="3" cellspacing="0" border="1" };
		print qq{style="margin-bottom:1em;margin:0.4em;">\n};
		print qq{<tr><th>$lex{Category}</th><th>$lex{Name}</th>};
		print qq{<th>$lex{Score}</th></tr>\n};

		$sth2->execute( $id );
		if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

		my $totalscore;
		while ( my ( $category, $name, $score ) = $sth2->fetchrow ) {
		    $totalscore += $score;
		    print qq{<tr><td>$category</td><td>$name</td><td class="cn">$score</td></tr>\n};
		}

		# if ( $readlevel >= 40 ) {
		    #$totalscore += $readlevel;
		    my $equivgrade = scoreToGrade( $totalscore, $readlevel );
		    print qq{<tr><td colspan="2" style="text-align:right;font-weight:bold;">};
		    print qq{$lex{'Equivalent'} $lex{Grade}</td><td class="cn">$equivgrade</td></tr>\n};
	        #}

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

	    }
	} # end of student loop.

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

    } # end of student number loop

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

}
