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

#  This file is part of Open Admin for Schools.

my %lex = ('Main' => 'Main',
	   'Error' => 'Error',
	   'Class Reading Report' => 'Class Reading Report',
	   'Reading Level' => 'Reading Level',
	   'Name' => 'Name',
	   'Date' => 'Date',
	   'Continue' => 'Continue',
	   'Homeroom' => 'Homeroom',
	   'Grade' => 'Grade',
	   'Blank=All' => 'Blank=All',
	   'No Students Found' => 'No Students Found',
	   'Show Only Latest Test' => 'Show Only Latest Test',
	   'Gr' => 'Gr',
	   'Levels' => 'Levels',
	   'Score' => 'Score',
	   'Start Date' => 'Start Date',
	   'End Date' => 'End Date',
	   'EGr' => 'EGr',
	   'Select by' => 'Select by',
	   'Sort Order' => 'Sort Order',
	   'New to Old' => 'New to Old',
	   'Old to New' => 'Old to New',
	   
	   );


# Grade => Start:End Reading Level
my %levelExpect = ( K => '0:3', 1 => '3:16', 2 => '16:28', 3 => '28:38', 4 => '40:50', 
		    5 => '50:60', 6 => '60:70', 7 => '70:80', 8 => '80:80' ); 


my %shortCategory = ( 'Oral Fluency' => 'OrFlu', 'Reading Engagement' =>'RdEg',
		      'Comprehension' => 'Comp', 'Printed Language Concepts' => 'pLgCcp');


my %seasondates = ('Spring' => {'start' => '01-01', 'end' => '03-31' },
		   'Summer' => {'start' => '05-15', 'end' => '06-30' },
		   'Fall' => {'start' => '09-01', 'end' => '10-31' }
    );


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

my $self = 'feederReadingView.pl';

my @time = localtime(time);
my $year = $time[5] + 1900;
my $month = $time[4] + 1;
my $currdate = "$year-$month-$time[3]";

# Get current dir so know what path for config files.
my $configpath;
my $teachermode;
my $jspath; # javascript path
if ( getcwd() =~ /tcgi/ ){ # we are in tcgi
    $teachermode = 1;
    $configpath = '..'; # go back one to get to etc.
    $jspath = 'tcgi-bin';
} else {
    $configpath = '../..'; # go back two to get to etc.
    $jspath = 'cgi-bin';
}

# only load password and userid
eval require "$configpath/etc/admin.conf.root";
if ( $@ ) {
    print $lex{Error}. ": $@<br>\n";
    die $lex{Error}. ": $@\n";
}

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



# Load Configuration Variables;
my $sth = $dbh->prepare("select id, datavalue from conf_system where filename = 'admin'");
$sth->execute;
if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
while (	my ($id, $datavalue) = $sth->fetchrow ) {
    eval $datavalue;
    if ( $@ ) {
	print "$lex{Error}: $@<br>\n";
	die "$lex{Error}: $@\n";
    }
}


# Load global user and password
# Load global user and password
if ( not -e "$globdir/global.conf" ) {
    print qq{Cannot read the global.conf file!\n};
    print qq{</body></html>\n};
    exit;
}

eval require "$globdir/global.conf";
if ( $@ ) {
    print qq{$lex{Error} $@<br>\n};
    die $lex{Error}. " $@<br>\n";
}

if ( $oldbase{$dbase} ) { # We are an onion lake school
    %dbase = %oldbase;
}



my $q = new CGI;
print $q->header; 
my %arr = $q->Vars;

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

# Page Header
my $title = qq{$lex{'Class Reading Report'} - $schoolname};
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">
<style type="text/css">
th.fs6{font-size:60%;}
td.r { background-color:#822;color:white;font-size:120%;font-weight:bold; }
td.y { background-color:#BB1;color:white;font-size:120%;font-weight:bold; }
td.b { background-color:#228;color:white;font-size:120%;font-weight:bold; }
td.g { background-color:#282;color:white;font-size:120%;font-weight:bold; }
a {color:white; }
a.alt {color:blue; }
</style>\n};


print qq{<script language="javascript" type="text/javascript">
function showhelp(type) {
  winName=window.open('/$jspath/reading/showhelp.pl?id=' + type,'helpWindow',
  'height=300,width=700,screenX=100,screenY=100,resizeable');
  winName.focus();
}
</script>
$chartype\n</head><body style="padding:1em 6em 0 0.5em;margin:1em;">\n};


# Show Grade and Reading Levels Expected.
print qq{<div style="position:absolute;top:0;right:0;">\n};
print qq{<table cellspacing="0" cellpadding="3" border="1">\n};
print qq{<tr><th>$lex{Gr}</th><th>$lex{'Levels'}</th></tr>\n};
foreach my $key ( sort keys %levelExpect ) {
    my ($start, $end ) = split(':', $levelExpect{$key} );
    if ( $start == '0' ) { $start = 'A'; }
    print qq{<tr><td>$key</td><td>$start &ndash; $end</td></tr>\n};
}
print qq{</table></div>\n};

print qq{[ <a href="$homepage" class="alt">$lex{Main}</a> \n};
if ( not $teachermode ) {
    print qq{| <a href="/ssp.html" class="alt">SSP</a> \n};
}
print qq{]\n<h1 style="text-align:left;margin:0;padding:0.5em;">$title</h1>\n};


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

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

} elsif ( $arr{page} == 2) {
    delete $arr{page};
    showReport();
} 


#----------
sub fmtDate {
#----------

    my ( $year, $mon, $day ) = split '-', shift;
    return "$year-$s_month[$mon]-$day";
}


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

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

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

    my $startdate = $arr{startdate};
    my $enddate = $arr{enddate};
    #    my $sortorder = $arr{sortorder}; # can only desc;
    my $sortorder = 'desc';
    my $onlylatest = $arr{onlylatest};
    
    
    # Load the reading library containing the scoreToGrade / showReadingLevel
    eval require "../../lib/libreading.pl";
    if ( $@ ) {
	print $lex{Error}. " $self: $@<br>\n";
	die $lex{Error}. "$self: $@\n";
    }

    
    my $studtable = 'studentwd';
    if ( $arr{showall} ) {
	$studtable = 'studentall';
    }


    my ($select,$selectvalue);  # value of homeroom or grade
    my %studname;
    my %ReadingLevel;

    # Feeder School Name
    print qq{<div style="font-size:120%;font-weight:bold;">$dbase{$arr{db}}</div>\n};

    
    # Display Group of students (or entire school)
    print qq{<h3 style="text-align:left;font-size:120%;margin:0;padding:0.3em;">};
    
    if ( $arr{grade} ) {
	print qq{$lex{Grade} $arr{grade}};
	$selectvalue = $dbh->quote($arr{grade});
	$select = "where grade = $selectvalue";

    } elsif  ( $arr{homeroom} ) { # not used here.

	print qq{$lex{Homeroom} $arr{homeroom}};
	$selectvalue = $dbh->quote( $arr{homeroom} );
	$select = "where homeroom = $selectvalue";

    } else {
	print qq{All Grades\n};
    }


    # Get Teacher Name if a homeroom # not used.
    if ( $arr{homeroom} ) {
	my $sth = $dbh->prepare("select lastname, firstname from staff as s, staff_multi as sm
          where sm.userid = s.userid and field_name = 'homeroom' and field_value = ?");
        $sth->execute( $arr{homeroom} );
        if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my ( $lastname, $firstname ) = $sth->fetchrow;
	print qq{ &ndash; $firstname $lastname};
    }


    # Display Dates;
    print qq{<br>$lex{'Start Date'} $startdate | $lex{'End Date'} $enddate\n};

    print qq{</h3>\n}; # finish description line

    
    # Get students in this homeroom or grade.
    my (%sort, %studname );
    my $sth = $dbh->prepare("select studnum, lastname, firstname from $studtable $select");
    $sth->execute;
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my ($studnum,$lname,$fname ) = $sth->fetchrow ) {
	$sort{"$lname$fname$studnum"} = $studnum;
	$studname{$studnum} = qq{<b>$lname</b>, $fname};
    }

    
    # Find any student tests
    my $sth = $dbh->prepare("select * from read_test where studnum = ? and
			    to_days(tdate) >= to_days('$startdate') and 
			    to_days(tdate) <= to_days('$enddate') ");
    

    # Loop over all student tests.
    my $first = 1;
    my (%readDra, %notests);
    foreach my $key ( sort keys %sort ) {
	my $studnum = $sort{$key};
	$sth->execute($studnum);
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	while ( my $ref = $sth->fetchrow_hashref ) {
	    $first = 0;
	    if ( not $ref ) { # no tests in this time period
		$notests{$studnum} = 1;
		next; # student
	    }
	    my %r = %$ref;  # will also have bktype here... fiction or nonfiction.
	    if ( not $r{dratype} ) { $r{dratype} = 2; }
	    if ( not defined $r{bktype} ) {  # for older tests without a book type
		if ( $r{readlevel} eq '16N' or $r{readlevel} eq '28N' or $r{readlevel} eq '38N' ) {
		    $r{bktype} = 'nonfiction';
		} else {
		    $r{bktype} = 'fiction';
		}
	    }
	    $readDra{ $r{readlevel} }{ $r{bktype} }{ $r{dratype} }{ $studnum } = 1;
	    
#	    print "RL:$r{readlevel} BK:$r{bktype} DRA:$r{dratype} SN:$studnum<br>\n";
	} # end of loop for single student.
    } # end of all students

    
#    use Data::Dumper;
#    print Dumper %readDra;
    
    foreach my $rl ( sort {$a <=> $b} keys %readDra ) {
	foreach my $bktype ( sort keys %{ $readDra{$rl} } ) {
	    foreach my $dratype ( sort keys %{ $readDra{$rl}{$bktype} } ) {
		my @temp = keys %{ $readDra{$rl}{$bktype}{$dratype}};  # @temp are the students

#		print qq{RL:$rl DRA:$dratype BK:$bktype Order:$sortorder ST: @temp<br>\n};
		
		showReadingLevel( $rl, $onlylatest, \@temp, $startdate, $enddate,
				  $sortorder, $dratype, $bktype, $dbh );
	    }
	}
    }

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


    exit;

}



#----------------
sub selectSchool { 
#----------------

    if (not @g_FeederSchools ) {
	print qq{<h3>No Feeder Schools Found</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    print qq{<h3>Select Feeder School</h3>\n};

    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    
    foreach my $db ( @g_FeederSchools ) {
	print qq{<div><input type="radio" name="db" value="$db">$dbase{$db}</div>\n};
    }

    print qq{<p><input type="submit" value="Continue"></p>\n};
    print qq{</form>\n};
    
    print qq{</body></html>\n};
    
    exit;

}

    

#---------------
sub selectGroup {
#---------------
    
    # foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }
    # passed db to view.

    # Setup for Date Entry
    print qq{<link rel="stylesheet" type="text/css" media="all" };
    print qq{href="/js/calendar-blue.css" title="blue">\n};
    print qq{<script type="text/javascript" src="/js/calendar.js"></script>\n};
    print qq{<script type="text/javascript" src="/js/lang/calendar-en.js"></script>\n};
    print qq{<script type="text/javascript" src="/js/calendar-setup.js"></script>\n};


   
    print qq{<h3>Feeder School - $dbase{$arr{db}}</h3>\n};

    
    my $dbtype = 'mysql';
    my $dsn = "DBI:$dbtype:dbname=$arr{db}";
    my $dbh = DBI->connect($dsn,$guser,$gpassword);
    
    
    my @grades;

    # Get Grades
    $sth = $dbh->prepare("select distinct grade from studentall 
      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;


    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="$arr{db}">\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 class="la"><select name="grade"><option value=""></option>\n};
    foreach my $gr ( @grades ) {
	print qq{<option>$gr</option>\n};
    }
    print qq{</select> $lex{'Blank=All'}</td></tr>\n};

    
    # Select Starting/Ending Date
    print qq{<tr><td class="bra">$lex{'Start Date'}</td><td class="la"><input type="text" };
    print qq{name="startdate" id="sdate" size="10" value="">};
    print qq{<button type="reset" id="start_trigger">...</button>\n};
    print qq{ Previous Year Start?</td></tr>\n};

    print qq{<tr><td class="bra">$lex{'End Date'}</td><td class="la"><input type="text" };
    print qq{name="enddate" id="edate" size="10" value="$currdate">};
    print qq{<button type="reset" id="end_trigger">...</button></td></tr>\n};

    # Sort Order
#    print qq{<tr><td class="bra">$lex{'Sort Order'}</td>\n};
#    print qq{<td class="la"><select name="sortorder">};
#    print qq{<option value="descending">$lex{'New to Old'}</option>\n};
#    print qq{<option value="ascending">$lex{'Old to New'}</option></select></td></tr>\n};

    # Show Only Latest
    print qq{<tr><td class="bra">$lex{'Show Only Latest Test'}</td>\n};
    print qq{<td class="la"><input type="checkbox" name="onlylatest" value="1" checked="checked">\n};
    print qq{</td></tr>\n};
    
    # Show All Students
    print qq{<tr><td class="bra">Show Current Students Also</td>};
    print qq{<td class="la"><input type="checkbox" name="showall" value="1">};
    print qq{ Default is Withdrawn Students</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>\n};

    print qq{<script type="text/javascript">
     Calendar.setup({
        inputField     :    "sdate", 
        ifFormat       :    "%Y-%m-%d",
        button         :    "start_trigger",
        singleClick    :    false,
        step           :    1
    });

    Calendar.setup({
        inputField     :    "edate",
        ifFormat       :    "%Y-%m-%d",
        button         :    "end_trigger",
        singleClick    :    false,
        step           :    1
    });
    </script>\n};


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

    exit;

}

