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

#  This file is part of Open Admin for Schools.

my %lex = ('Main' => 'Main',
	   'Error' => 'Error',
	   'Reading Report' => 'Reading Report',
	   'Reading Level' => 'Reading Level',
	   'Name' => 'Name',
	   'Date' => 'Date',
	   'Student' => 'Student',
	   'No Students Found' => 'No Students Found',
	   'Last,First/Last/Initials/Studnum' => 'Last,First/Last/Initials/Studnum',
	   'Search' => 'Search',
	   'No Tests Found' => 'No Tests Found',
	   'Tot' => 'Tot',
	   'Start Date' => 'Start Date',
	   'End Date' => 'End Date',
	   'Test' => 'Test',
	   'EGr' => 'EGr',
	   'Continue' => 'Continue',
	   'Level' => 'Level',
	   'Sort Order' => 'Sort Order',
	   'New to Old' => 'New to Old',
	   'Old to New' => 'Old to New',
	   
	   
	   );

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

my $self = 'readRptStudent.pl';

my $defaultStartDate = '2017-08-01';  # get ALL years data

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

eval require "../../etc/admin.conf";
if ( $@ ) {
    print $lex{Error}. " $self: $@<br>\n";
    die $lex{Error}. "$self: $@\n";
}


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


# Get current dir so know what CSS to display and shift settings.
my $tcgiurl = 'tcgi-bin';
if ( getcwd() !~ /tcgi/ ) { # we are in cgi
    $tchcss = $css;
    $tchpage = $homepage;
    $tchdownloaddir = $downloaddir;
    $tchwebdownloaddir = $webdownloaddir;
    $tcgiurl = 'cgi-bin';
}


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


# IEP Database
my ($sy,$ey) = split('-', $schoolyear);
$sy =~ s/20//;
$ey =~ s/20//;
        
my $iepdbase = qq{iep$sy$ey};
my $dsniep = "DBI:$dbtype:dbname=$iepdbase";
my $dbhiep = DBI->connect($dsniep,$guser,$gpassword);
    
# Normal Database
my $dsn = "DBI:$dbtype:dbname=$dbase";
my $dbh = DBI->connect($dsn,$user,$password);

# Page Header
my $title = qq{$lex{Student} $lex{'Reading Report'}};

print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$tchcss" 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,dra) {
  winName=window.open('/$tcgiurl/reading/showhelp.pl?id=' + type + '&dt=' + dra,'helpWindow',
  'height=300,width=700,screenX=100,screenY=100,resizeable');
  winName.focus();
}
</script>
$chartype\n</head><body style="padding:1em 2em;">\n};

print qq{[ <a class="alt" href="$tchpage">$lex{Main}</a> };
if ( getcwd() !~ /tcgi/ ) { # we are in cgi
    print qq{| <a href="/ssp.html" style="color:blue;">SSP</a>\n};
}
print qq{]\n};

print qq{<h1 style="text-align:left;margin:0;padding:0.2em;">};
print qq{<span style="font-size:80%;">$lex{Student} $lex{'Reading Report'}</span>};
print qq{ $schoolname <span style="font-size:80%;">}. fmtDate($currdate). qq{</span></h1>\n};

print qq{<div style="font-weight:bold;margin:1em;">IEP Database $iepdbase</div>\n};

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


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

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

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


#----------
sub fmtDate {
#----------
    my ( $year, $mon, $day ) = split '-', shift;
    return qq{$year-$s_month[$mon]-$day};
}


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

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

    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};

    
    my ($studnum) = @_;
    
    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" };
    print qq{style="padding:0.5em;border:1px solid gray;">\n};

    print qq{<tr><td class="ra">$lex{Student} ($lex{'Last,First/Last/Initials/Studnum'})</td>\n};
    print qq{<td class="la"><input type="text" name="student" size="30" value="$studnum"></td></tr>\n};

    print qq{<tr><td class="ra">$lex{'Start Date'}</td><td class="la"><input type="text" };
    print qq{name="startdate" id="sdate" size="10" value="$schoolstart">};
    print qq{<button type="reset" id="start_trigger">...</button>\n};
    print qq{</td></tr>\n};

    print qq{<tr><td class="ra">$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};

    print qq{<tr><td class="ra">$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};

    
    print qq{<tr><td></td><td class="la"><input type="submit" value="$lex{Search}"></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;

} # end of showStartPage


#----------------
sub selectStudent {
#----------------

    my $student = $arr{student};

    # Setup the Search
    if ($student =~ /\d+/) {  # we have a student number
	$studnum = $student;
	$sth = $dbh->prepare("select lastname, firstname, studnum from studentall
           where studnum = ?");
	$sth->execute( $studnum );

    } else { # we have words hopefully with a comma
	($lastname,$firstname)  = split /\,/, $student;
	$firstname =~ s/^\s*//;
	$lastname =~ s/^\s*//;
	if ($lastname and $firstname){ # both entered.
	    $sth = $dbh->prepare("select lastname, firstname, studnum 
              from studentall where lastname = ? and firstname = ?
              order by lastname, firstname");
	    $sth->execute( $lastname, $firstname );
	} elsif ( $lastname and not $firstname ){ # only lastname (no comma)
	    if (length($lastname) == 2){ # search by initials: fi, li.

		$fi = substr($lastname,0,1); 
		$li = substr($lastname,1,1);
		$fi .= '%';
		$li .= '%';
		$sth = $dbh->prepare("select lastname,firstname, studnum from studentall
                   where lastname $sql{like} ? and firstname $sql{like} ?
                   order by lastname, firstname");
		$sth->execute( $li, $fi );
	    } else {
		$sth = $dbh->prepare("select lastname, firstname, studnum 
                 from studentall where lastname = ? 
                 order by lastname, firstname");
		$sth->execute( $lastname );
	    }
	} else {
	    $sth = $dbh->prepare("select lastname, firstname, studnum 
              from studentall order by lastname, firstname");
	}
    } # Last Else

    if ( $DBI::errstr ) { print $lex{Error}. ": $DBI::errstr"; die $DBI::errstr; }
    my $first = 1;
    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
    print qq{<tr><th>$lex{Name}</th><th>$lex{Test}</th><th></th></tr>\n};

    my $sth1 = $dbh->prepare("select count(*) from read_test 
      where studnum = ? and to_days( tdate ) >= to_days( '$arr{startdate}' ) 
      and to_days( tdate ) <= to_days( '$arr{enddate}')");
    

    # Loop through each found student.

    while ( my ( $lastname, $firstname,$studnum ) = $sth->fetchrow ) {

	$sth1->execute( $studnum );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my $testcount = $sth1->fetchrow;

	# Check if they have an IEP
	my $iepflag;
	my $sth3 = $dbhiep->prepare("select count(*) from special where school = '$dbase' and studnum = ?");
	$sth3->execute($studnum);
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my $count = $sth3->fetchrow;
	if ( $count ) {
	    $iepflag = q{<span style="color:blue;">IEP</span>};
	}

	
	print qq{<tr><td style="text-align:right;">$iepflag $firstname <strong>$lastname</strong>};
	print qq{ ($studnum)</td><td>$testcount</td><td>\n};
	if ( $testcount ) {
	    print qq{<form action="$self" method="post">\n};
	    print qq{<input type="hidden" name="page" value="2">\n};
	    print qq{<input type="hidden" name="startdate" value="$arr{startdate}">\n};
	    print qq{<input type="hidden" name="enddate" value="$arr{enddate}">\n};
	    print qq{<input type="hidden" name="sortorder" value="$arr{sortorder}">\n};
	    print qq{<input type="hidden" name="studnum" value="$studnum">\n};
	    print qq{<input type="submit" value="$lex{Continue}"></form>\n};
	}
	print qq{</td></tr>\n};
	$first = 0;

    }

    if ( $first ) { # no students
	print qq{<tr><td colspan="2">$lex{'No Students Found'}</td></tr>\n};
	print qq{</table></div><p></p>\n};
	showStartPage();
    } else {
	print qq{</table></body></html>\n};
    }

    exit;

} # end of selectStudent



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

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

    # Load the reading library containing the scoreToGrade fn and showReadingLevel
    eval require "../../lib/libreading.pl";
    if ( $@ ) {
	print $lex{Error}. " $self: $@<br>\n";
	die $lex{Error}. "$self: $@\n";
    }

    
    # if only passed the studnum from class report, do current year data
    if ( not $arr{startdate} ) {
	# $arr{startdate} = $schoolstart;
	
	$arr{startdate} = $defaultStartDate;  # get ALL years data
	
    }
    if ( not $arr{enddate} ) {
	$arr{enddate} = $currdate;
    }
    if ( not $arr{sortorder} ) {
	$arr{sortorder} = 'descending';
    }

    
    my $studnum = $arr{studnum};

    
    # Get Student Name
    my $sth = $dbh->prepare("select lastname, firstname from studentall where studnum = ?");
    $sth->execute( $studnum );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    my ( $lastname, $firstname ) = $sth->fetchrow;

    my $iepflag;

    # Check if they have an IEP
    my $sth3 = $dbhiep->prepare("select count(*) from special where school = '$dbase' and studnum = ?");
    $sth3->execute($studnum);
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    my $count = $sth3->fetchrow;
    if ( $count ) {
	$iepflag = q{<span style="color:blue;">IEP</span>};
    }

    
    print qq{<h3 style="text-align:left;font-size:120%;margin:0;padding:0.3em;">};
    print qq{$iepflag $firstname $lastname ($studnum)</h3>\n};
    
    my $sth1 = $dbh->prepare("select distinct readlevel, dratype, bktype, 
			     cast( readlevel as signed int) as newrl from read_test 
			     where studnum = ? order by newrl desc"); 
    $sth1->execute( $studnum );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    
    my $first = 1;

    # Check for tests at this reading level in this date range.
    my $sth2 = $dbh->prepare("select count(*) from read_test where studnum = ? 
			     and readlevel = ? and dratype = ? and 
			     to_days( tdate ) >= to_days('$arr{startdate}') and
			     to_days( tdate ) <= to_days( '$arr{enddate}') ");


    while ( my ( $readlevel,$dratype,$bktype ) = $sth1->fetchrow ) {

	# check for tests in date range (at this read level for this dratype).
	$sth2->execute( $studnum, $readlevel, $dratype );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my $count = $sth2->fetchrow;

	if ( $count ) { # if we have some tests...
	    $first = 0;
	    my @students; # although only a single student in this case.
	    push @students, $studnum;

	    showReadingLevel( $readlevel, 0,  \@students , $arr{startdate}, $arr{enddate},
			      $arr{sortorder}, $dratype, $bktype, $dbh ); 
	}
    } # reading level, dratype
    
    if ( $first ) {
	print qq{<h3>$lex{'No Tests Found'}</h3>\n};
    }

    showStartPage(); # always allow for change/update
    print qq{</body></html>\n};

    exit;

}
