#! /usr/bin/perl
#  Copyright 2001-2018 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',
	   'Show Withdrawn' => 'Show Withdrawn',


	   );

my $self = 'cmaRpt11.pl';

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

my @strands = qw(P N SS SP);
my %strandnames = ('P' => 'Patterns and Relations', 
		   'N' => 'Numbers and Operations',
		   'SS' => 'Shape and Space',
		   'SP' => 'Stats and Prob'
    );


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} 11 - $schoolname";
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};
print qq{$chartype\n</head><body style="padding:1em 5em;">\n};

print qq{<div>[ <a href="$homepage">$lex{Main}</a> ]</div>\n};
print qq{<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: grade, homeroom, schoolyear;

    my $yearcount = 2;
    
#    print qq{School Year - $schoolyear<br>\n};
    my ($prev,$curr) = split('-', $schoolyear);
    my @years;
    push @years, $curr;
    for my $t (1..$yearcount ) {
	my $yr = $curr - $t;
	push @years, $yr;
    }

#    print "Years @years<br>\n";

    
    my $studenttable = 'studentall';

    # Get all students in the CMA system;
    my %studs;
    my $sth = $dbh->prepare("select distinct studnum from mathca_scores");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $studnum = $sth->fetchrow ) {
	$studs{$studnum} = 1;
    }
	

    # Load student data
    my (%students, %sort);
    my $sth = $dbh->prepare("select lastname, firstname, grade, homeroom from $studenttable where studnum = ?");
    foreach my $studnum ( keys %studs ) {
	$sth->execute( $studnum );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

	my $ref = $sth->fetchrow_hashref;
	$students{$studnum} = $ref;
	$sort{"$ref->{lastname}$ref->{firstname}$studnum"} = $studnum;
    } # we now have all students in %students - $students{$studnum} = $ref;

    
    print qq{<h3>$currdate</h3>\n};


=head    
    # Build outcomes data structure
    my %outcomes; # lists outcomes.
    my %odesc; # outcomes description.

    my $sth = $dbh->prepare("select * from mathca_outcomes");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $ref = $sth->fetchrow_hashref ) {
	my %r = %$ref;

	my $oid = $r{oid};
	my $grade = $r{grade};

	my ($cat, $seq)  = split(/\./, $oid);
	$cat =~ s/$grade$//; # remove grade

#	print qq{OID:$oid GR:$grade CAT:$cat SEQ:$seq DESC:$r{odesc}<br>\n};

	$outcomes{$grade}{$cat}{$seq} = $oid;
	$odesc{$oid} = $r{odesc};

    } # Done building data structure of outcomes as above; (oid like N7.1)
=cut


    # Load Data structure ( $data{studnum}{strand}{schoolyear}{count/sum} = 1
    my $sth = $dbh->prepare("select * from mathca_scores where studnum = ?");
    foreach my $studnum ( keys %studs ) {
	$sth->execute( $studnum );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	while ( my $ref = $sth->fetchrow_hashref ) {
	    my %r = %$ref;
	    # Get the strand
	    my $strand;
	    if ( $r{outcome} =~ m/(P|N|SS|SP)/ ) {
		$strand = $1;
	    } else {
		print qq{<p>ERROR: Strand not found: $r{outcome}</p>\n};
	    }

	    $data{$studnum}{$strand}{$r{schoolyear}}{count}++;
	    $data{$studnum}{$strand}{$r{schoolyear}}{sum} += $r{score};
	    
	}
    }

#    use Data::Dumper;
#    print Dumper %sort;
#    exit;

    
    my $count;
    print qq{<table cellspacing="0" cellpadding="3" border="1">\n};
    
    foreach my $key ( sort keys %sort ) {
	my $studnum = $sort{$key};
	my %s = %{ $students{$studnum}};

	if ( $count % 15 == 0 ) { # table header row
	    print qq{<tr><th></th>}; # strand names row
	    foreach my $strand ( @strands ) {
		my $colspan = @years;
		print qq{<th colspan="$colspan">$strandnames{$strand}</th>};
	    }
	    print qq{</tr>\n};

	    # years row
	    print qq{<tr><th>Name (Grade)</th>};
	    foreach my $strand ( @strands ) {
		foreach my $year ( @years ) {
		    print qq{<th>$year</th>};
		}
	    }
	    print qq{</tr>\n};
	}
	$count++;

	if ( $s{lastname} ) {
	    print qq{<tr><td><b>$s{lastname}</b>, $s{firstname} ($s{grade})</td>\n};
	} else {
	    print qq{<tr><td style="color:red;">No Name Found for: $studnum</td>\n};
	}

	foreach my $strand ( @strands ) {
	    foreach my $year ( @years ) {
		my $count = $data{$studnum}{$strand}{$year}{count};
		my $sum = $data{$studnum}{$strand}{$year}{sum};
		my $avg;
		if ( $count ) {
		    $avg = round( $sum / $count, 2);
		}
		
		print qq{<td class="cn">$avg</td>};
	    }
	}
	
    } # end of student loop

    print qq{</table>\n};

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

    exit;

} # end of showReport



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

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

    # Get 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;

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


    # Start Form
    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">\n};


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

    # OR
    print qq{<tr><td colspan="2" style="text-align:center;">$lex{OR}</td></tr>\n};


    # Select Homeroom
    print qq{<tr><td class="bra">$lex{'Select by'} $lex{Homeroom}</td>};
    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};


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

    # Withdrawn
    print qq{<tr><td class="bra">$lex{'Show Withdrawn'}</td>};
    print qq{<td><input type="checkbox" name="showwithdrawn" value="1"></td></tr>\n};


=head
    # Sort Order
    print "<tr><td class=\"ra\">$lex{'Sort by'}</td>";
    print "<td><select name=\"sortorder\">";
    print "<option value=\"grade\">$lex{Grade}</option>";
    print "<option value=\"homeroom\">$lex{Homeroom}</option>";
    print "<option value=\"name\">$lex{Name}</option>";
    print "</select></td>";
    print "<td></td></tr>\n";
=cut


    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;

}

