#! /usr/bin/perl
#  Copyright 2001-2014 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',
	   'Start Date' => 'Start Date',
	   'End Date' => 'End Date',
	   'Check All' => 'Check All',

	   );

my $self = 'cmaRpt7.pl';

my %strandmap = ('N' => 'Number',
		 'P' => 'Patterns and Relations',
		 'SS' => 'Shape and Space',
		 'SP' => 'Statistics and Probability');


use DBI;
use CGI;
use Cwd;
use Number::Format qw(:all);


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 $q = new CGI;
print $q->header( -charset, $charset );
my %arr = $q->Vars;


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

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


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


my $title = "$lex{'Common Math Assessment'} $lex{Report} 7 (Central Report 5)";
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"; }

    my $schoolyear = $arr{schoolyear};
    delete $arr{schoolyear};


    # Load all outcomes (objectives) at top of loop, one time.
    my %outcomes;
    my %strands;  # {grade}{strand}{seq} = oid;


    my %summary;
    my $outcomeload = 1;


	if ( $outcomeload ) { # load from this database
	    my $sth = $dbh->prepare("select oid, odesc from mathca_outcomes");
	    $sth->execute;
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    while ( my ($oid, $odesc ) = $sth->fetchrow ) {
		my ($val, $seq) = split('\.', $oid);
		my $tempgr = $val;
		$tempgr =~ s/N|P|SS|SP//g; # strip strands to leave grade.
		$val =~ s/[0-9]|K//g; # strip the digit (the grade).
		$outcomes{$oid}{'desc'} = $odesc;
		$outcomes{$oid}{'strand'} = $val;
		$outcomes{$oid}{'seq'} = $seq;

		$strands{$tempgr}{$val}{$seq} = $oid;
		
	    }
	    $outcomeload = 0;
	}

	print qq{<h3>$alldbase{$dbase}</h3>\n};
	my %score;

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

	my $first = 1;

	$sth = $dbh->prepare("select * from mathca_scores where schoolyear = ?");
	$sth->execute( $schoolyear );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	while ( my $ref  = $sth->fetchrow_hashref ) {

	    my %r = %$ref;
	    $first = 0;

	    # Don't need  Gender
	    #$sth1->execute( $r{studnum} );
	    #if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    # my ($ln, $fn, $gender ) = $sth1->fetchrow;


	    $score{ $r{tgrade} }{$r{outcome} }{ $r{prepost} }{'count'}++;
	    $score{ $r{tgrade} }{$r{outcome} }{ $r{prepost} }{'sum'} += $r{score};

	    $summary{ $r{tgrade} }{ $r{outcome} }{ $r{prepost} }{'count'}++;
	    $summary{ $r{tgrade} }{ $r{outcome} }{ $r{prepost} }{'sum'} += $r{score};

	}


	if ( $first ) { # no records from this school
	    print qq{<div>No records from $alldbase{$dbase}</div>\n};

	} else { # print out the record

	    print qq{<table cellspacing="0" cellpadding="3" border="1">\n};
	    print qq{<tr><th>Grade</th><th>Strand</th><th title="Outcomes Done">Outc Done<br>Pre/Post</th>};
	    print qq{<th>Pretest<br>Average</th><th>Posttest<br>Average</th><th>Diff</th></tr>\n};


	    foreach my $grade ( sort {$a <=> $b} keys %strands ) {
		foreach my $strand ( sort keys %{ $strands{$grade} } ) {

		    my ($preaverage, $precount, $presum, $postaverage, $postcount, $postsum);

		    # Loop over each objective/outcome
		    foreach my $seq ( sort keys %{ $strands{$grade}{$strand} } ) {

			my $outcome = $strands{$grade}{$strand}{$seq};

			$precount += $score{$grade}{$outcome}{'pretest'}{'count'};
			$presum += $score{$grade}{$outcome}{'pretest'}{'sum'};

			$postcount = $score{$grade}{$outcome}{'posttest'}{'count'};
			$postsum = $score{$grade}{$outcome}{'posttest'}{'sum'};

		    }


		    if  ( $precount ) {
			$preaverage =  format_number( $presum / $precount, 2) ;
		    }
		    if  ( $postcount ) {
			$postaverage =  format_number( $postsum / $postcount, 2) ;
		    }

		    # print "PRE:$precount - $presum, POST: $postcount - $postsum<br>";


		    my $diff;
		    if ( $preaverage and $postaverage ) {
			$diff = format_number($postaverage - $preaverage, 2);
		    }

		    print qq{<tr><td>$grade</td><td>$strandmap{$strand} ($strand)</td>};
		    print qq{<td>$precount / $postcount</td><td>$preaverage</td>};
		    print qq{<td>$postaverage</td><td>$diff</td></tr>\n};

		    } # strand loop
		} # grade loop

	    print qq{</table>\n};

	} # end of else.

    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;

}
