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

#  This file is part of Open Admin for Schools.

# Based on cma Rpt1a from central site.


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 = 'ilangLocalRpt1.pl';


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

eval require "../../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 $dsn = "DBI:$dbtype:dbname=$dbase";
my $dbh = DBI->connect($dsn,$user,$password);
$dbh->{mysql_enable_utf8} = 1;


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} 1";
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 qq{K:$key V:$arr{$key}<br>\n}; }

    my @grades;
    my $sth = $dbh->prepare("select distinct tgrade from cree_scores
          where schoolyear = ?");
    $sth->execute( $arr{schoolyear} );
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $grade = $sth->fetchrow ) {
	push @grades, $grade;
    }
    @grades = sort {$a <=> $b} @grades;


    

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

    foreach my $grade ( @grades ) {
	
	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( $arr{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;
		    
		}
	    
		# Check for Exceptions
		if ( not $pretest ) {
		    # Get Date of test to match against ssp_exceptions entry
		    my $tdate = $tdates{$scoremonth}{'pretest'};
		    
		    my $sth2 = $dbh->prepare("select * from ssp_exceptions
                  where ssptype = 'cree' and tdate = ? and studnum = ?");
		    $sth2->execute($tdate, $studnum);
		    my $ref = $sth2->fetchrow_hashref;
		
		    if ( not $ref ) {
			$pretest = qq{<span style="color:red;" title="$tdate Missing Entry; No Exception">M</span>};
		    } else { # display the exception
			$pretest = qq{<span style="color:blue;" title="$tdate Exception:$ref->{reasoncode}">E</span>};
		    }
		}

		if ( not $posttest ) {
		    # Get Date of test to match against ssp_exceptions entry
		    my $tdate = $tdates{$scoremonth}{'posttest'};

		    my $sth2 = $dbh->prepare("select * from ssp_exceptions
                      where ssptype = 'cree' and tdate = ?");
		    $sth2->execute($tdate);
		    my $ref = $sth2->fetchrow_hashref;

		    if ( not $ref ) {
			$posttest = qq{<span style="color:red;" title="$tdate Missing Entry; No Exception">M</span>};
		    } else { # display the exception
			$posttest = qq{<span style="color:blue;" title="$tdate Exception:$ref->{reasoncode}">E</span>};
		    }
		}

		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
	

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

    print qq{<h3>Overall Averages $totpreavg / $totpostavg</h3>\n};
    
    print qq{</body></html>\n};

    exit;


} # end of showReport


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

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

    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="1">\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

