#! /usr/bin/perl
#  Copyright 2001-2015 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',
	   'Continue' => 'Continue',
	   'Homeroom' => 'Homeroom',
	   'Grade' => 'Grade',
	   'Select by' => 'Select by',
	   'Error' => 'Error',
	   'Sort by' => 'Sort by',
	   'Name' => 'Name',

	   'Common Math Assessment' => 'Common Math Assessment',
	   'Report' => 'Report',
	   'OR' => 'OR',
	   'No Selection' => 'No Selection',
	   'School Year' => 'School Year',
	   'Schools' => 'Schools',
	   'Select' => 'Select',

	   );

my $self = 'cmaRpt5.pl';  # was central report 2a.

use DBI;
use CGI;
use Cwd;

my  $configpath = '../../..';
if ( getcwd() =~ /tcgi/ ){ # we are in tcgi
    $configpath = '../..';
}

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


my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $iddst) = localtime(time);
$year = $year + 1900;
$wday++; $mon++;
my $currdate = "$dow[$wday], $month[$mon] $mday, $year";


# Get current dir so know what CSS to display;
if ( getcwd() =~ /tcgi/ ){ # we are in tcgi
    $css = $tchcss;
    $homepage = $tchpage;
}


my $q = CGI->new;
my %arr = $q->Vars;
print $q->header( -charset, $charset );

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




my $title = "$lex{'Common Math Assessment'} $lex{Report} 5 (Central Report 2a)";
print "$doctype\n<html><head><title>$title</title>\n";
print "<link rel=\"stylesheet\" href=\"$css\" type=\"text/css\">\n";
print "$chartype\n</head><body style=\"padding:1em 5em;\">\n";
print "<div>[ <a href=\"$homepage\">$lex{Main}</a> ]</div>\n";

print "<h1>$title</h1>\n";


if ( not $arr{page} ) {
    showStartPage();

} elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    showReport();
}


#-------------
sub showReport {
#-------------

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

    # Passed: $arr{schoolyear};

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

    foreach my $grade  ( @grades ) {

	my %data; # holds all data $data{studnum}{outcome}{prepost} = score;
	my %outcomes; # lists outcomes.
	my %tdates; # store test dates for outcomes and pre/post  $tdates{outcome}{pretest/posttest};

	# Get this grade's data
	my $sth1 = $dbh->prepare("select studnum, prepost, outcome, score, tdate from mathca_scores
           where schoolyear = ? and tgrade = ?");
	$sth1->execute( $arr{schoolyear}, $grade );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	
	my $first = 1;
	while ( my ($studnum, $prepost, $outcome, $score, $tdate) = $sth1->fetchrow ) {
	    $outcomes{$outcome} = 1;
	    $data{$studnum}{$outcome}{$prepost} = $score;
	    $tdates{$outcome}{$prepost} = $tdate;
	    $first = 0;
	}
	if ( $first ) { # no data 
	    print qq{<h3>Grade $grade - No Data</h3>\n};
	    next; # grade;
	}


	# Arrange Score Data for Grade.
	my %scoredata;
	my @students = keys %data;
	foreach my $studnum ( @students ) {
	    foreach my $outcome ( keys %outcomes ) {
		my $prescore = $data{$studnum}{$outcome}{'pretest'};
		if ( not $prescore ) { 
		    $scoredata{$outcome}{'pretest'}{'missing'}++;
		} else {
		    $scoredata{$outcome}{'pretest'}{$prescore}++;
		}

		my $postscore = $data{$studnum}{$outcome}{'posttest'};
		if ( not $postscore ) { 
		    $scoredata{$outcome}{'posttest'}{'missing'}++;
		} else {
		    $scoredata{$outcome}{'posttest'}{$postscore}++;
		}
	    }
	}


	# print the data structure as a table;
	print qq{<table cellpadding="3" cellspacing="0" border="1" style="margin:0.4em;">\n};
	print qq{<caption><span style="font-size:120%;font-weight:bold;">Grade $grade</span>&nbsp;&nbsp;\n};
	print qq{<span style="text-align:right;">M=Missing Score</span></caption>\n};
	
	# header section.
	print qq{<tr><th></th><th>M</th>};
	for my $s (1..4) { print qq{<th>$s</th>}; }

#	foreach my $outcome ( sort keys %outcomes ) {
#	    my $predate = $tdates{$outcome}{'pretest'};
#	    my $postdate = $tdates{$outcome}{'posttest'};
#	    print qq{<th title="Pre:$predate Post:$postdate">$outcome</th>};
#	}
	print qq{</tr>\n};

	my %totals; # count of total scores: $totals{score} = count;

	foreach my $outcome ( sort keys %outcomes ) {

	    # pretest row
	    print qq{<tr><td>$outcome Pretest</td>\n};
	    print qq{<td>$scoredata{$outcome}{'pretest'}{'missing'}</td>\n}; # missing
	    $totals{'0'} += $scoredata{$outcome}{'pretest'}{'missing'};
	    for my $s (1..4) {
		print qq{<td>$scoredata{$outcome}{'pretest'}{$s}</td>\n}; # score counts
		$totals{$s} += $scoredata{$outcome}{'pretest'}{$s};
	    }
	    print qq{</tr>\n};

	    # posttest row
	    print qq{<tr><td>$outcome Posttest</td>\n};
	    print qq{<td>$scoredata{$outcome}{'posttest'}{'missing'}</td>\n}; # missing
	    $totals{'0'} += $scoredata{$outcome}{'posttest'}{'missing'};
	    for my $s (1..4) {
		print qq{<td>$scoredata{$outcome}{'posttest'}{$s}</td>\n}; # score counts
		$totals{$s} += $scoredata{$outcome}{'posttest'}{$s};
	    }
	    print qq{</tr>\n};
		
	}


	# now do the totals row
	print qq{<tr style="background-color:#DDD;"><td>Total</td>};
	for my $s (0..4) {
	    print qq{<td>$totals{$s}</td>};
	}
	print qq{</tr>\n};

	print qq{</table><p></p>\n};
    } # end of grade loop

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

    exit;


} # end of showReport



#----------------
sub showStartPage { # Entry Values for Custom Script
#----------------

    my @schoolyears;

    # Get School Years
    $sth = $dbh->prepare("select distinct schoolyear from mathca_scores");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $yr = $sth->fetchrow ) {
	push @schoolyears, $yr;
    }
    @schoolyears = reverse sort @schoolyears;


    print "<form action=\"$self\" method=\"post\">\n";
    print "<input type=\"hidden\" name=\"page\" value=\"1\">\n";

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


    # School Year
    print qq{<tr><td class="bra">$lex{'School Year'}</td>};
    print qq{<td><select name="schoolyear">\n};
    foreach my $yr ( @schoolyears ) {
	print qq{<option>$yr</option>\n};
    }
    print qq{</select></td></tr>\n};

    print qq{<tr><td class="ra"><input type="submit" value="$lex{Continue}"></td></tr>\n};
    print qq{</table>\n};
    print qq{</form></body></html>\n};

    exit;

}

