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

#  This file is part of Open Admin for Schools.

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 = 'cmaRpt3.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";
    exit $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} 3";
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 $schoolyear = $arr{schoolyear};

    my ( %stotal, %total, %gtotal);

    my @grades;
    my $homeroom;
    
    if ( $arr{grade} ) { # just do a single grade;
	push @grades, $arr{grade};
    }
	
=head    } else { # do all grades
        my $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 ) {
	    if ( $gr eq 'PK' ) { next; } # skip PK
	    push @grades, $gr;
	}
    }
    @grades = sort {$a <=> $b} @grades;
=cut

    elsif ( $arr{homeroom} ) { # just do that homeroom; find their grades.

	$homeroom = $arr{homeroom};

        my $sth = $dbh->prepare("select distinct grade from student where homeroom = ? and
	   grade is not NULL and grade != ''");
	$sth->execute( $homeroom );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	while ( my $gr = $sth->fetchrow ) {
	    if ( $gr eq 'PK' ) { next; } # skip PK
	    push @grades, $gr;
	}
    } else {
	print qq{<h3>Missing Grade or Homeroom</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    
    # Build Outcomes selection
    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};
#	print qq{OID:$oid<br>};

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

#	print qq{Grade:$grade CAT:$cat SEQ:$seq<br><br>\n};

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

    } # Done building data structure.

    my %outcount; # outcomes count for each grade;
    foreach my $gr ( sort  keys %outcomes ) {
	foreach my $cat (sort keys %{ $outcomes{$gr} } ) {
	    foreach my $seq ( sort keys %{$outcomes{$gr}{$cat} }) {
		$outcount{$gr}++;
#		print "GR:$gr CAT:$cat SEQ:$seq VAL:$outcomes{$gr}{$cat}{$seq}<br>\n";
	    }
	}
    }
    
    foreach my $gr ( sort  keys %outcount ) {
	print qq{<div>GR:$gr Count:$outcount{$gr}</div>\n};
    }

    
    
    # get the students in the homeroom, split up by grade, possibly
    my %students; # students{grade}{studnum} = 1;
    if ( $homeroom ) {
	my $sth = $dbh->prepare("select studnum,grade from student where homeroom = ?");
	$sth->execute( $homeroom );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	while ( my ($studnum,$grade) = $sth->fetchrow ) {
	    $students{$grade}{$studnum} = 1;
	}
    } elsif ( $arr{grade} ) {
	my $sth = $dbh->prepare("select studnum,grade from student where grade = ?");
	$sth->execute( $arr{grade} );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	while ( my ($studnum,$grade) = $sth->fetchrow ) {
	    $students{$grade}{$studnum} = 1;
	}
    }

# Testing Data
#    foreach my $key (sort keys %students ) {
#	foreach my $key1 (sort keys %{ $students{$key}} ) {
#	    print qq{K:$key K1:$key1 VAL:$students{$key}{$key1}<br>\n};
#	}
#    }

    
    my $sth = $dbh->prepare("select * from mathca_scores where schoolyear = ? and tgrade = ?");

    foreach my $grade ( @grades ) {

	# Now build a structure for this grade
	my %strandcount;  # $catcount{category} = number in this category.
	foreach my $cat ( sort keys %{ $outcomes{$grade} } ) {
	    foreach my $seq ( sort keys %{ $outcomes{$grade}{$cat} } ) {
		if ( $seq > $strandcount{$cat} ) { $strandcount{$cat} = $seq; }
	    }
	}
	
	# Now Select the records for each grade
	$sth->execute( $schoolyear, $grade );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

	while ( my $ref = $sth->fetchrow_hashref ) {
	    my %r = %$ref;
	    if ( not $students{$grade}{ $r{studnum} } ) { next; } # skip if not a student of interest
	    
	    $data{$grade}{ $r{outcome} }{ $r{prepost} }{'sum'} += $r{score};
	    $data{$grade}{ $r{outcome} }{ $r{prepost} }{'count'}++;
	    if ( $r{score} >= 3 and $r{prepost} eq 'posttest' ) {
		$data{$grade}{ $r{outcome} }{ $r{prepost} }{'pass'}++;
	    }
	} # data for a single grade


	print qq{<h3>Grade $grade - Total Outcomes $outcount{$grade}</h3>\n};

	my $first = 1;

	foreach my $strand ( @strands ) {
	    if ( $strandcount{$strand} ) { # print IF we have that strand in this grade
		foreach my $idx ( 1..$strandcount{$strand} ) {
		    my $oid = $strand. $grade. q{.}. $idx;

		    if ( $data{$grade}{$oid} ) { # print a line for this

			if ( $first ) {
			    # Table Heading
			    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
			    print qq{<tr><th>Strand</th><th>Outcome</th><th>Pre Avg</th><th>Post Avg</th>};
			    print qq{<th>Count</th><th>Pass</th><th>Percent at<br>Grade Level</th></tr>\n};
			    $first = 0;
			}


			print qq{<tr><td>$strandnames{$strand}</td>};
			print qq{<td>$oid &mdash; $odesc{$oid}</td>};
			
			my $preavg;
			if ( $data{$grade}{$oid}{'pretest'}{'count'} ) {
			    $preavg = format_number( $data{$grade}{$oid}{'pretest'}{'sum'} /
						     $data{$grade}{$oid}{'pretest'}{'count'} , 2);
			}
#			print qq{SUM: $data{$grade}{$oid}{'pretest'}{'sum'} 
		        #Count:$data{$grade}{$oid}{'pretest'}{'count'}<br>\n};

			my ($postavg, $passpercent);
			if ( $data{$grade}{$oid}{'posttest'}{'count'} ) {
			    $postavg = format_number( $data{$grade}{$oid}{'posttest'}{'sum'} /
						      $data{$grade}{$oid}{'posttest'}{'count'} , 2);
			    
			    $passpercent = format_number( $data{$grade}{$oid}{'posttest'}{'pass'} * 100 /
							  $data{$grade}{$oid}{'posttest'}{'count'} , 2);

			}

			
			print qq{<td>$preavg</td><td>$postavg</td><td>$data{$grade}{$oid}{'posttest'}{'count'}</td>};
			print qq{<td>$data{$grade}{$oid}{'posttest'}{'pass'}</td><td>$passpercent</td></tr>\n};

			# Now put values into summary structures
			# Strand Totals
			$stotal{$strand}{'count'} += $data{$grade}{$oid}{'posttest'}{'count'};
			$stotal{$strand}{'pass'} += $data{$grade}{$oid}{'posttest'}{'pass'};
			$stotal{$strand}{'sum'} += $data{$grade}{$oid}{'posttest'}{'sum'};

			$total{'count'} += $data{$grade}{$oid}{'posttest'}{'count'};
			$total{'pass'} += $data{$grade}{$oid}{'posttest'}{'pass'};
			$total{'sum'} += $data{$grade}{$oid}{'posttest'}{'sum'};

		    }
		}
	    }

	} # end of strand loop

	if ( $first ) {
	    print qq{<h3>No Records Found</h3>\n};
	} else {
	    print qq{</table>\n};
	}

    } # end of grade loop



    # Summary Section
    print qq{<h3>Summary Results</h3>\n};

    # Table Heading
    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
    print qq{<tr><th>Strand</th><th>Post Avg</th>};
    print qq{<th>Count</th><th>Pass</th><th>Percent at<br>Grade Level</th></tr>\n};

    foreach my $strand ( @strands ) {
	my ($strandavg, $passpercent);
	if ( $stotal{$strand}{'count'} ) {
	    $strandavg = format_number( $stotal{$strand}{'sum'} / $stotal{$strand}{'count'}, 2);
	    $passpercent = format_number( $stotal{$strand}{'pass'} * 100 / $stotal{$strand}{'count'}, 2);
	}

#	print qq{$strand SUM:$stotal{$strand}{'sum'} COUNT:$stotal{$strand}{'count'}<br>\n};

	print qq{<td>$strandnames{$strand}</td><td>$strandavg</td><td>$stotal{$strand}{'count'}</td>};
	print qq{<td>$stotal{$strand}{'pass'}</td><td>$passpercent</td></tr>\n};

    }

    # Total Line
    my ($totalavg, $passpercent);
    if ( $total{'count'} ) {
	$totalavg = format_number( $total{'sum'} / $total{'count'}, 2,2);
	$passpercent = format_number( $total{'pass'} * 100 / $total{'count'}, 2,2);
    }

    print qq{<tr style="background-color:#DDD;"><td>Total</td><td>$totalavg</td><td>$total{'count'}</td>};
    print qq{<td>$total{'pass'}</td><td>$passpercent</td></tr>\n};

    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 ) {
	if ( $gr > 9 ) { next; }
	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;



    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};


    # print qq{<div><input type="submit" value="$lex{Continue}"></div>\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 ) {
	print qq{<option>$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 qq{<tr><td class="ra">$lex{'Sort by'}</td>};
    print qq{<td><select name="sortorder">};
    print qq{<option value="grade">$lex{Grade}</option>};
    print qq{<option value="homeroom">$lex{Homeroom}</option>};
    print qq{<option value="name">$lex{Name}</option>};
    print qq{</select></td>};
    print qq{<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;

}

