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

#  This file is part of Open Admin for Schools.

# Based on cma Rpt1a from central site.
# Show data from all schools in a single table with overall at the end.


my %lex = ('Main' => 'Main',
	   'Continue' => 'Continue',
	   'Homeroom' => 'Homeroom',
	   'Grade' => 'Grade',
	   'Select by' => 'Select by',
	   'Error' => 'Error',
	   'Sort by' => 'Sort by',
	   'Name' => 'Name',
	   'Report' => 'Report',
	   'OR' => 'OR',
	   'No Selection' => 'No Selection',
	   'School Year' => 'School Year',
	   'Select' => 'Select',
	   'School' => 'School',

	   );

my $self = 'ilangRpt2.pl';

my $startgrade = 2;
my $endgrade = 6;


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

eval require "../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";


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


my $title = "Indigenous Languages $lex{Report} 2";
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();
}
    
#} elsif ( $arr{page} == 2 ) {
#    delete $arr{page};
#    showReport();
#}


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

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

    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
    print qq{<tr><th>School</th><th>Pre/Post Averages</th></tr>\n};

    my %sort;
    foreach my $db ( keys %arr ) {
	$sort{"$alldbase{$db}$db"} = $db;
    }
     
    my ($gtotprecount, $gtotpostcount, $gtotpresum, $gtotpostsum);
    
   
    foreach my $key ( sort keys %sort ) {
	my $dbase = $sort{$key};

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

#	print qq{<h2>$alldbase{$dbase}</h2>\n};


	my ($totprecount, $totpostcount, $totpresum, $totpostsum);

	foreach my $grade ( $startgrade..$endgrade ) { # defined at top of script.
	
	    my ($gprecount, $gpostcount, $gpresum, $gpostsum);
	
	    $sth = $dbh->prepare("select lastname, firstname, studnum from student
              where grade = ? order by lastname, firstname");
	    $sth->execute( $grade );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	

	    my %data; # holds all data $data{studnum}{month}{prepost} = score;
	    my @students;  # provides order of students
	    my %scoremonth; # lists the scoremonth values
	    my %names; # store student names;
	    my %tdates; # store test dates for scoremonth and pre/post  $tdates{scoremonth}{pretest/posttest};

	    while ( my $ref = $sth->fetchrow_hashref ) {
		my %r = %$ref;

		my $studnum = $r{studnum};
		push @students, $studnum; 
		$names{$r{studnum}} = "<b>$r{lastname}</b>, $r{firstname}";

		# Get this student's data
		my $sth1 = $dbh->prepare("select prepost, scoremonth, score, tdate from cree_scores
                 where schoolyear = ? and studnum = ? order by tdate");
		$sth1->execute( $schoolyear, $studnum );
		if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    
		while ( my ($prepost, $scoremonth, $score, $tdate) = $sth1->fetchrow ) {
		    $scoremonth{$scoremonth} = 1;
		    $data{$studnum}{$scoremonth}{$prepost} = $score;
		    $tdates{$scoremonth}{$prepost} = $tdate;
		}
	    }

	    if ( not %data ) {
#		print qq{<div style="margin:0.3em;">No Data Found - Grade $grade</div>\n};
		next; # grade
	    }
    

	    # print the data structure as a table;
#	    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
#	    print qq{<caption>Pretest / Posttest (Hover on Score Month to see Dates)</caption>\n};

	# header section.
#	print qq{<tr><th>Grade $grade</th>};
	    my $colcount;
	    foreach my $scoremonth ( sort {$a <=> $b} keys %scoremonth ) {
		my $predate = $tdates{$scoremonth}{'pretest'};
		my $postdate = $tdates{$scoremonth}{'posttest'};
		#	    print qq{<th title="Pre:$predate Post:$postdate">$s_month[$scoremonth]</th>};
		$colcount++;
	    }
#	print qq{<th>Average</th></tr>\n};
	    $colcount++; # due to name column
    
#	print qq{<colgroup><col span="$colcount" class="cn"><col style="background-color:#DDD;"></colgroup>\n}; 
    

	    foreach my $studnum ( @students ) {
#	    print qq{<tr><td>$names{$studnum}</td>\n};
		my ($precount, $postcount, $presum, $postsum);
	
		foreach my $scoremonth ( sort {$a <=> $b} keys %scoremonth ) {
		    my $pretest = $data{$studnum}{$scoremonth}{'pretest'};
		    my $posttest = $data{$studnum}{$scoremonth}{'posttest'};

		    if ( $pretest ) {
			$precount++;
			$presum += $pretest;

			$gprecount++;
			$gpresum += $pretest;
		    
			$totprecount++;
			$totpresum += $pretest;
		
		    }
		    if ( $posttest ) {
			$postcount++;
			$postsum += $posttest;
		    
			$gpostcount++;
			$gpostsum += $posttest;

			$totpostcount++;
			$totpostsum += $posttest;
			
		    }

#		    print qq{<td>$pretest/$posttest</td>};
		}

		my ($preavg, $postavg);
		if ( $precount ) {
		    $preavg = round($presum / $precount, 1);
		}
		if ( $postcount ) {
		    $postavg = round($postsum / $postcount, 1);
		}
		if ( $preavg or $postavg ) {
#		    print qq{<td class="cn">$preavg/$postavg</td></tr>\n};
		} else {
#		    print qq{<td></td></tr>\n};
		}

	    } # end of student loop


	    # Do Grade Average
	    my ($gpreavg, $gpostavg);
	    if ( $gprecount ) {
		$gpreavg = round($gpresum / $gprecount, 1);
	    }
	    if ( $gpostcount ) {
		$gpostavg = round($gpostsum / $gpostcount, 1);
	    }

#	print qq{<tr><td class="ra" style="background-color:#CCC;" colspan="$colcount">Grade $grade Average</td>\n};
#	print qq{<td class="bcn">$gpreavg / $gpostavg</td></tr>\n};
#	print qq{</table><div>M = Missing Entry; E = Missing Entry, Exception reason added</div>\n};
#	print qq{</p></p>\n};
	
	} #end of grade loop

#	print "PRE:$totprecount $totpresum  POST:$totpostcount $totpostsum<br>\n";

	# Do total 
	my ($totpreavg, $totpostavg);
	if ( $totprecount ) {
	    $totpreavg = round($totpresum / $totprecount, 1);
	}
	if ( $totpostcount ) {
	    $totpostavg = round($totpostsum / $totpostcount, 1);
	}

	
	if ( $totprecount ) {
	    $gtotprecount += $totprecount;
	    $gtotpresum += $totpresum;
	}
	if ( $totpostcount ) {
	    $gtotpostcount += $totpostcount;
	    $gtotpostsum += $totpostsum;
	}

	print qq{<tr><td>$alldbase{$dbase}</td><td>$totpreavg / $totpostavg</td></tr>\n};

    } # end of dbase loop

    # Print Overall Average for all schools
    my ($gtotpreavg, $gtotpostavg);
    if ( $gtotprecount ) {
	$gtotpreavg = round($gtotpresum / $gtotprecount, 1);
    }
    if ( $gtotpostcount ) {
	$gtotpostavg = round($gtotpostsum / $gtotpostcount, 1);
    }

    print qq{<tr><td colspan="2" class="bla" style="background-color:#DDD;">All School Average $gtotpreavg / $gtotpostavg</td></tr>\n};
    
    print qq{</table>\n};
    print qq{</body></html>\n};

    exit;


} # end of showReport



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

    my %schoolyears;

       
    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};
    print qq{<tr><th>School</th><th>Records</th></tr>\n};

    print qq{<tr><td class="bla">$lex{Select} $lex{School}</td></tr>\n};
    foreach my $db ( sort keys %alldbase ) {

	my $dsn = "DBI:$dbtype:dbname=$db";
	my $dbh = DBI->connect($dsn,$guser,$gpassword);

	my $sth = $dbh->prepare("select count(*) from cree_scores");
	$sth->execute;
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my $count = $sth->fetchrow;
	if ( $count ) {
	    $checked = qq{checked="checked"};
	} else {
	    $checked = '';
	}

	$sth = $dbh->prepare("select distinct schoolyear from cree_scores");
	$sth->execute;
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	while (my $yr = $sth->fetchrow ) {
	    $schoolyears{$yr} = 1;
	}

	print qq{<tr><td class="la">};
	print qq{<input type="checkbox" name="$db" value="1" $checked>\n};
	print qq{$alldbase{$db} ($db)</td><td class="bcn">$count</td></tr>\n};

    }

    print qq{<tr><td colspan="2">&nbsp;</td></tr>\n};

    # School Year
    print qq{<tr><td class="bla" colspan="2">$lex{'School Year'}};
    print qq{ <select name="schoolyear">\n};
    foreach my $yr ( sort keys %schoolyears ) {
	my $prevyear = $yr - 1;
	print qq{<option value="$yr">$prevyear-$yr</option>\n};
    }
    print qq{</select></td></tr>\n};

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

    exit;

}


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

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

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

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



    my (@homerooms, @grades, @schoolyears );
=head
    # 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;
=cut

    # Get School Years
    $sth = $dbh->prepare("select distinct schoolyear from cree_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 qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="2">\n};
    print qq{<input type="hidden" name="db" value="$dbase">\n};


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

=head
    # 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> Blank=All</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>Blank=All</td></tr>\n};
=cut

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

} # end of selectStudents

