#! /usr/bin/perl
#  Copyright 2001-2022 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 = 'cmaRpt1.pl';

use DBI;
use CGI;
use Cwd;


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} 1 - $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 qq{K:$key V:$arr{$key}<br>\n}; }
    # Passed: grade, homeroom, and schoolyear.

    # Show Withdrawn students?
    my $showwithdrawn;
    my $studtable = 'student';
    if ( $arr{showwithdrawn} ) {
	$studtable = 'studentall';
	$showwithdrawn = $arr{showwithdrawn};
    }
    delete $arr{showwithdrawn};
    
    
    if ( not $arr{grade} and not $arr{homeroom} ) {
	print qq{<h3>$lex{'No Selection'}</h3>\n};
	print qq{</body></html>\n};
	exit;
    } 

    if ( $arr{schoolyear} =~ m/\D/ ) {
	print qq{<h3>Format Error</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    
    my @grades;
    my $classname;
    if ( $arr{homeroom} ) { 
	my $sth = $dbh->prepare("select distinct grade from student where homeroom = ?");
	$sth->execute( $arr{homeroom} );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	while ( my $gr = $sth->fetchrow ) {
	    push @grades, $gr;
	}
	$classname = "Homeroom $arr{homeroom}";
    } else {
	push @grades, $arr{grade};
	$classname = "Grade $arr{grade}";
    }

    print qq{<h3>$classname &ndash;  $arr{schoolyear}</h3>\n};

    
    # Student Name;
    my $sth1 = $dbh->prepare("select lastname, firstname, homeroom from $studtable where studnum = ?");
    my $sth2 = $dbh->prepare("select count(*) from studentwd where studnum = ?");
    
    
    foreach my $grade ( sort @grades ) {

	my $sth = $dbh->prepare("select * from mathca_scores where schoolyear = ? and tgrade = ?");
	$sth->execute( $arr{schoolyear}, $grade );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

	my %data; # holds all data $data{studnum}{outcome}{prepost} = score;
	my %students;  # provides order of students
	my %outcomes; # lists outcomes.
	my %names;
	
	my %tdates; # store test dates for outcomes and pre/post  $tdates{outcome}{pretest/posttest};

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

	    # Get Name, Homeroom
	    $sth1->execute( $r{studnum} );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    my ( $lastname, $firstname, $homeroom ) = $sth1->fetchrow;
	    if ( $arr{homeroom} and $homeroom ne $arr{homeroom} ) { next; }
	    if ( not $lastname ) { next; } # skip withdrawn kids.

	    
	    my $studnum = $r{studnum};
	    $students{"$lastname$firstname$studnum"} = $studnum; # sorted list. 
	    $names{$studnum} = qq{<b>$lastname</b>, $firstname};
	    

	    $outcomes{ $r{outcome} } = 1;
	    $data{ $r{studnum} }{ $r{outcome} }{ $r{prepost} } = $r{score};
	    $tdates{ $r{outcome} }{ $r{prepost} } = $r{tdate};
	    
	}


	print qq{<div style="font-size:120%;font-weight:bold;margin-top:0.5em;">Grade $grade</div>\n};

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


	# header section.
	print qq{<tr><th></th>};
	foreach my $outcome ( sort keys %outcomes ) {
	    my $predate = $tdates{$outcome}{'pretest'};
	    my $postdate = $tdates{$outcome}{'posttest'};
	    print qq{<th title="Pre:$predate Post:$postdate">$outcome</th>};
	}
	print qq{</tr>\n};


	foreach my $key ( sort keys %students ) {
	    my $studnum = $students{$key};

	    # Check if a withdrawn student;
	    my $wd;
	    if ( $showwithdrawn ) {
		$sth2->execute( $studnum );
		if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
		if ( my $count = $sth2->fetchrow ) {
		    $wd = qq{<span style="color:red;font-weight:bold;">WD</span>\n};
		}
	    }
	    
	    print qq{<tr><td>$wd $names{$studnum}</td>\n};
	    
	    foreach my $outcome ( sort keys %outcomes ) {
		
		my $pretest = $data{$studnum}{$outcome}{'pretest'};
		my $posttest = $data{$studnum}{$outcome}{'posttest'};

		
		# Check for Exceptions
		if ( not $pretest ) {
		    # Get Date of test to match against ssp_exceptions entry
		    my $tdate = $tdates{$outcome}{'pretest'};
		    
		    my $sth2 = $dbh->prepare("select * from ssp_exceptions
                      where ssptype = 'cma' 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{$outcome}{'posttest'};

		    my $sth2 = $dbh->prepare("select * from ssp_exceptions
                      where ssptype = 'cma' 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>};
	    }
	    
	    print qq{</tr>\n};
	}

	print qq{</table>\n};
	print qq{<div>M = Missing Entry; E = Missing Entry, Exception reason added</div>\n};

    } # end of Grade Loop
	

    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;


    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 ) {
	print qq{<option>$yr</option>\n};
    }
    print qq{</select></td></tr>\n};

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

}
