#!/usr/bin/perl
#  Copyright 2001-2021 Leslie Richardson

#  This file is part of Open Admin for Schools.

# Read Report - read all reading tests from all schools, calc the
# Equiv Grade and then compare to the actual grade and get a
# delta. Compile into per grade, per school and overall stats.

my %lex = ('Error' => 'Error',
	   'Main' => 'Main',
	   'Math' => 'Math',
	   'Start Date' => 'Start Date',
	   'End Date' => 'End Date',
	   'Date' => 'Date',
	   'Continue' => 'Continue',
	   'Schools' => 'Schools',
	   'Database' => 'Database',
	   'Reading' => 'Reading',
	   'Report' => 'Report',
	   'Global' => 'Global',
	   'Select' => 'Select',
	   'Split' => 'Split',
	   'Grade' => 'Grade',
	   'Current' => 'Current',
	   'Output' => 'Output',
	   'Combine failed on input' => 'Combine failed on input',
	   'Download CSV File' => 'Download CSV File',
	   'Test' => 'Test',
	   'Group' => 'Group',
	   'Division' => 'Division',
	   'Paper Size' => 'Paper Size',
	   'Letter' => 'Letter',
	   'Legal' => 'Legal',
	   'A4' => 'A4',
	   'Season' => 'Season',
	   'Seasons' => 'Seasons',
	   'Missing' => 'Missing',
	   'Weight' => 'Weight',
	   'Tests' => 'Tests',
	   );


my $self = 'mathRpt1.pl';

my $missing = qq{<span style="color:red;font-weight:bold;">$lex{Missing}</span>};
my @phases = qw(Emergent Matching Quantifying Partitioning Factoring Operating);
my %phaseval = qw(Emergent 1 Matching 2 Quantifying 3 Partitioning 4 Factoring 5 Operating 6);


# Maps Grades to Grade Divisions I, II, III, IV.
my %divmap = ( 'K' => 1, 1 => 1, 2 => 1, 3 => 1, 
	       4 => 2, 5 => 2, 6 => 2, 
	       7 => 3, 8 => 3, 9 => 3,
	       10 => 4, 11 => 4, 12 => 4 );


# use GD::Graph::bars;
# use GD::Graph::colour qw(:colours);
use DBI;
use CGI;
use Number::Format qw(:all);
use Time::JulianDay;
use Text::CSV_XS;
use Statistics::Basic qw(:all);

#use strict;

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


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


my @time = localtime(time);
my $year = $time[5] + 1900;
my $month = $time[4] + 1;
my $currdate = "$year-$month-$time[3]";
my $schyear = $year;
if ( $month < 7 ){ $schyear = $schyear - 1; }
my $prevyear = $schyear - 1;


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


# Script Heading Descriptor
my $title = qq{$lex{Math} $lex{Report} 1};

# Print Page Heading
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$tchcss" type="text/css">\n};

print qq{$chartype\n</head><body style="padding:0.4em 2em;">\n};
print qq{[ <a class="alt" href="$tchpage">$lex{Main}</a> ]\n};
print qq{<h1>$title</h1>\n};

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

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



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

    # Get the Test Seasons
    my %seasons = ();

    my $sth = $dbh->prepare("select distinct tseason from math_fstep 
      where tseason is not NULL and tseason != ''");
    $sth->execute;
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $season = $sth->fetchrow ) {
	$seasons{$season} = 1;
    }


    # Start the 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" };
    print qq{style="padding:0.5em;border:1px solid gray;">\n};


    # Get the Seasons
    print qq{<tr><td> </td></tr>\n};
    print qq{<tr><td class="bla">$lex{Select} $lex{Seasons}</td></tr>\n};
    foreach my $season ( sort keys %seasons ) { 
	print qq{<tr><td class="la">};
	print qq{<input type="checkbox" name="$season" value="2">\n};
	print qq{$season</td></tr>\n};
    }


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

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

    exit;

} # end of showStartPage



#-------------
sub selectMath {
#-------------

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

    foreach my $season ( sort keys %arr ) {

	my %seasondata = ();

	print qq{<h3>$schoolname &ndash; $season</h3>\n};

	my @students = ();
	my $sth = $dbh->prepare("select distinct studnum from math_fstep");
	$sth->execute;
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	while ( my $studnum = $sth->fetchrow ) {
	    push @students, $studnum;
	}
	
	if ( not @students ) {
	    print qq{<h3>No Student Tests Found</h3>\n};
	    next;
	}


	# Now loop through all students printing results; setup queries first
	my $sth1 = $dbh->prepare("select tphase, tgrade from math_fstep
              where studnum = ? and tseason = ? order by tdate desc");
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

	my $sth2 = $dbh->prepare("select lastname, firstname from studentall where studnum = ?");	
	
	my %seasondata = ();
	my %colsummary = ();
	my @errors;
	
	foreach my $studnum ( @students ) {
		
	    # Get Tests
	    $sth1->execute( $studnum, $season );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    
	    my $trows = $sth1->rows;
	    
	    # if $onlylatest, limit to 1 test
	    # if ( $onlylatest and $trows > 1 ) { $trows = 1; } 
	    if ( $trows > 1 ) { $trows = 1; }

	    for ( 1 .. $trows ) {

		my ( $tphase, $tgrade ) = $sth1->fetchrow;
		#if ( $tgrade eq '1 ' ) { # catch wonky grades
		# print qq{STUDENT:$studnum<br>};
		#}

		if ( not $tphase or not $tgrade ) {
		    $sth2->execute( $studnum );
		    my ( $lastname, $firstname ) = $sth2->fetchrow;
		    if ( not $tphase ) { $tphase = $missing; }
		    my $error = qq{<div><b>$lex{Error}</b>: $lastname, $firstname ($studnum) }.
		    qq{- $lex{Grade}:$tgrade Score: $tphase</div>\n};
		    push @errors, $error;
		    next;
		}

		$seasondata{$tgrade}{$tphase}++; 
		$overall{$tgrade}{$tphase}++;
		$colsummary{$tphase}++;
		    
	    }

	} # end of student loop

	# Skip if no tests in this season
	if ( not %seasondata ) { 
	    print qq{<h3>No tests in this Season</h3>\n};
	    next; 
	}

	# Display Season Data
	# Now Printing Grade Level Output
	print qq{<table cellspacing="0" cellpadding="3" border="1">\n};

	# Table Heading
	print qq{<tr><th></th>};
	print qq{<th colspan="6">Percentage of Students vs Math Level Category</th>};
	print qq{<th colspan="2"> </th></tr>\n};

	# Print Phases
	print qq{<tr><th>$lex{Grade}</th>\n};
	foreach my $phase ( @phases ) {
	    print qq{<th>$phase</th>};
	}
	print qq{<th>#$lex{Tests}</th><th>Avg</th></tr>\n};

	# Print Phase Weights
	print qq{<tr><th>$lex{Weight}</th>\n};
	foreach my $phase ( @phases ) {
	    print qq{<th>$phaseval{$phase}</th>};
	}
	print qq{<th></th><th></th></tr>\n};

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

	    print qq{<tr><td>$grade</td>};

	    my $total;
	    foreach my $key ( keys %{ $seasondata{$grade} } ) {
		$total += $seasondata{$grade}{$key}
	    }

	    # Print Phases
	    my $gradetotal; # for average calc; contains total of count * phase val for all phases
	    foreach my $phase ( @phases ) {
		my $percent;
		if ( $total ) {
		    $percent = $seasondata{$grade}{$phase} / $total * 100;
		    $percent = round($percent, 2);
		    $gradetotal += ( $seasondata{$grade}{$phase} * $phaseval{$phase});
		    # print qq{Phase:$phase Count:$seasondata{$grade}{$phase} };l
		    # print qq{GradeTotal:$gradetotal<br>\n};
		} else { $percent = 0; }
		print qq{<td>$percent };
		if ( $seasondata{$grade}{$phase} ) {
		    print qq{ ($seasondata{$grade}{$phase})};
		}
		print qq{</td>\n};
	    }

	    # Do EQ Grade Average
	    my $avg;
	    if ( $total ) {
		$avg = $gradetotal / $total;
	    } else { $avg = 0; }
	    
	    $avg = round($avg, 2);
	    print qq{<td>$total</td><td>$avg</td>};
	    print qq{</tr>\n};

	    # Division Line
	    if ( $grade == 3 or $grade == 6 or $grade == 9 ) { # print division line
		my ($startgrade, $endgrade,$division);
		if ( $grade == 3 ) { $startgrade = 1;$endgrade = 3; $division = 1; };
		if ( $grade == 6 ) { $startgrade = 4;$endgrade = 6; $division = 2; };
		if ( $grade == 9 ) { $startgrade = 7;$endgrade = 9; $division = 3; };
		
		print qq{<tr style="background-color:#EEE;"><td><b>Division $division</b></td>};

		my ($divtotal,$divavgtotal,%cols); # get total count, total weighted 
		    
		for my $grade ($startgrade..$endgrade) {
		    foreach my $phase ( @phases ) {
			my $count = $seasondata{$grade}{$phase};
			$divtotal += $count;
			$cols{$phase} += $count;
			$divavgtotal += ( $count * $phaseval{$phase} );
			# print qq{Count:$count Tot:$divtotal AvgTot:$divavgtotal<br>\n};
		    }
		}
		    

		# Print Phases
		foreach my $phase ( @phases ) {
		    my $percent;
		    if ( $divtotal ) {
			$percent = $cols{$phase} / $divtotal * 100;
			$percent = round($percent, 2);
		    } else { $percent = 0; }
		    print qq{<td>$percent};
		    if ( $cols{$phase} ) {
			print qq{ ($cols{$phase})</td>};
		    }
		    print qq{</td>\n};
		}

		# Do EQ Grade Average
		my $avg;
		if ( $divtotal ) {
		    $avg = $divavgtotal / $divtotal;
		} else { $avg = 0; }
		
		$avg = round($avg, 2);
		print qq{<td>$divtotal</td><td>$avg</td>};
		print qq{</tr>\n};
		
	    } #  End of division row

	} # end of grade (rows)


	# Summary Row
	print qq{<tr style="background-color:#DDD;"><td>Summary</td>};

	my ($total,$avgtotal); # get total count, total weighted 
	    
	foreach my $key ( keys %colsummary ) {
	    $total += $colsummary{$key};
	    $avgtotal += ( $colsummary{$key} * $phaseval{$key} );
	}

	# Print Phases
	foreach my $phase ( @phases ) {
	    my $percent;
	    if ( $total ) {
		$percent = $colsummary{$phase} / $total * 100;
		$percent = round($percent, 2);
	    } else { $percent = 0; }
	    print qq{<td>$percent};
	    if ( $colsummary{$phase} ) {
		print qq{ ($colsummary{$phase})</td>};
	    }
	    print qq{</td>\n};
	}
	
	# Do EQ Grade Average
	my $avg;
	if ( $total ) {
	    $avg = $avgtotal / $total;
	} else { $avg = 0; }
	
	$avg = round($avg, 2);
	print qq{<td>$total</td><td>$avg</td>};
	print qq{</tr>\n};
	# End of summary row


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

	# Print Errors if any.
	foreach my $error ( @errors ) { 
	    print $error;
	}
		

    } # end of season loop

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