#!/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',
	   'Name' => 'Name',
	   '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',
	   'Blank=All' => 'Blank=All',
	   'Edit' => 'Edit',
	   'Tests' => 'Tests',
	   'Delete' => 'Delete',
	   'Start Date' => 'Start Date',
	   'End Date' => 'End Date',
	   'Next Page' => 'Next Page',
	   'No Blanks Allowed' => 'No Blanks Allowed',
	   'Student' => 'Student',
	   'Date' => 'Date',
	   'Common Math Assessment' => 'Common Math Assessment',
	   'Type' => 'Type',
	   'Outcome' => 'Outcome',
	   'Year' => 'Year',

	   );

use DBI;
use CGI;

my $self = 'cmaView.pl';
my $editscript = 'cmaEdit.pl';
my $deletescript = 'cmaDelete.pl';

eval require "../../etc/admin.conf";
if ( $@ ) {
    print "$lex{Error}: $self: $@<br>\n";
    die "$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{'Common Math Assessment'}(CMA) $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();

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




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

    my $sth = $dbh->prepare("select distinct grade from student where 
			    grade is not NULL and grade != ''");
    $sth->execute;
    my @grades;
    while ( my $gr = $sth->fetchrow ) {
	push @grades, $gr;
    }
    @grades = sort { $a <=> $b } @grades;


    my $sth = $dbh->prepare("select distinct homeroom from student 
			    where homeroom is not NULL and homeroom != ''");
    $sth->execute;
    my @hroom;
    while ( my $hr = $sth->fetchrow ) {
	push @hroom, $hr;
    }
    @hroom = sort  @hroom;
    


    
    # 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="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 class="bra">OR $lex{Select} $lex{Homeroom}</td>\n};
    print qq{<td><select name="homeroom"><option></option>\n};
    foreach my $hr ( @hroom ) {
	print qq{<option>$hr</option>\n};
    }
    print qq{</select></td></tr>\n};
      

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

    print qq{</table></form>\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 $chk;
    if ( $arr{chk} ) {
	$chk = 'CHECKED';
    }
    delete $arr{chk};

    # Check for any Blanks
    if ( not $arr{grade} and not $arr{homeroom} ) {
	print qq{<h3>$lex{'No Blanks Allowed'}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    my $sth;
    if ( $arr{grade} ) {
	$sth = $dbh->prepare("select lastname, firstname, studnum from student
          where grade = ? order by lastname, firstname");
	$sth->execute( $arr{grade} );
	
    } else { # homeroom
	$sth = $dbh->prepare("select lastname, firstname, studnum from student
          where homeroom = ? order by lastname, firstname");
	$sth->execute( $arr{homeroom} );
    }

    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="5" cellspacing="0" border="0" };
    print qq{style="border:1px solid gray;margin:1em;padding:0.5em;">\n};




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

    
    print qq{<tr><th></th><th>$lex{Student}</th><th>Current<br>$lex{Tests}</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="cn">};
	if ( $count ) {
	    print qq{<input type="checkbox" name="$studnum" value="1" $chk>};
	}

	print qq{</td><td class="la"><b>$lastname</b>, $firstname ($studnum)</td>\n};
	print qq{<td class="cn">$count</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}; }

    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 = ?");
    my $sth2 = $dbh->prepare("select odesc from mathca_outcomes where oid = ?");

    # 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; } };
    print qq{td.red { background-color:#F00;color:white; }</style>\n};

    # Start the Form
    print qq{<form action="$editscript" method="post">\n};

    print qq{<div style="margin:0 0.5em;"><input type="submit" value="$lex{Edit}"></div>\n};
    
    # Table
    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
    print qq{<caption>Hover on <b>Outcome</b> to see Text version</caption>\n};
    print qq{<tr><th>$lex{Edit}</th><th>$lex{Name}</th><th>$lex{Age}</th><th>$lex{Grade}</th>\n};
    print qq{<th>$lex{Score}</th><th>$lex{Outcome}</th><th>$lex{Type}</th><th>$lex{Date}</th>\n};
    print qq{<th>$lex{Author}</th><th>$lex{Year}</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 mathca_scores
         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';
	    
	    # Get Outcome Text
	    $sth2->execute( $ref->{outcome} );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my $odesc = $sth2->fetchrow;

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

	    # Edit Checkbox.
	    print qq{<tr><td><input type="checkbox" name="$ref->{id}" value="1"></td>\n};

	    # Rest of Fields
	    print qq{<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="bcn">$ref->{score}</td>\n};
	    print qq{<td class="la" title="$odesc">$ref->{outcome}</td>\n};
	    print qq{<td class="la">$ref->{prepost}</td>\n};
	    print qq{<td class="la">$ref->{tdate}</td>\n};
	    print qq{<td>$ref->{tauthor}</td>\n};
	    print qq{<td>$ref->{schoolyear}</td>\n};

	    print qq{<td>[ <a href="$deletescript?testid=$ref->{id}">Delete</a> ]</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{</table>\n};
    print qq{<div style="margin:0.5em;"><input type="submit" value="$lex{Edit}"></div>\n};

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

}
