#! /usr/bin/perl 
#  Copyright 2001-2021 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.


use DBI;
use CGI;

my %lex = ('Teacher' => 'Teacher',
	   'Main' => 'Main',
	   'Timetables' => 'Timetables',
	   'Timetable' => 'Timetable',
	   'Cannot open tex file' => 'Cannot open tex file',
	   'View/Download' => 'View/Download',
	   'View Log File' => 'View Log File',
	   'Select' => 'Select',
	   'Lastname, Firstname' => 'Lastname, Firstname',
	   'Homeroom, Lastname, Firstname' => 'Homeroom, Lastname, Firstname',
	   'Grade, Lastname, Firstname' => 'Grade, Lastname, Firstname',
	   'Band, Lastname, Firstname' => 'Band, Lastname, Firstname',
	   'Sort by' => 'Sort by',
	   'Grade' => 'Grade',
	   'Homeroom' => 'Homeroom',
	   'Continue' => 'Continue',
	   'No Staff Found' => 'No Staff Found',
	   'Error' => 'Error',
	   'Blank=All' => 'Blank=All',
	   'Term' => 'Term',
	   'Period' => 'Period',
	   'Day' => 'Day',
	   'Separate with Spaces' => 'Separate with Spaces',
	   'Terms' => 'Terms',
	   'Font Size' => 'Font Size',
	   'Paper Size' => 'Paper Size',
	   'Letter' => 'Letter',
	   'Legal' => 'Legal',
	   'A4' => 'A4',
	   'Missing' => 'Missing',
	   
	);

# maxchars and field info passed into page 1.
#my $maxchars = 10; # maximum characters for subject description (if not small desc field)
#my $descfield = 'smdesc'; # either smdesc or description value

#my $logowidth = '20mm';
#my $logofile = 'schoollogo.jpg';

my $self = "rptStaffTtb.pl";


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


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

my $q = new CGI;
print $q->header( -charset, $charset );
my %arr = $q->Vars;



# print page header
my $title = qq{$lex{Teacher} $lex{Timetables} 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>\n};
print qq{[ <a href="$homepage">$lex{Main}</a> | \n};
print qq{<a href="$schpage">$lex{Timetable}</a> ]\n};
print qq{<h1>$title</h1>\n};

if ( not $arr{page} ) {
    showStartPage();
    
} else {
    delete $arr{page};
    showReport();
}



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

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

    my %staffnames; # global

    if ( not $arr{term} ) {
	print qq{<h3>No Terms</h3>\n};
	print qq{</body></html>\n};
	exit;
    }
    
    my @terms = split(/\s+/, $arr{term});
    delete $arr{term};
    print qq{<div style=font-weight:bold;font-size:120%;">Terms:@terms</div>\n};

    my @staff = keys %arr;
    
    my @skipped = prTimetable( \@staff, \@terms ); # print Timetables

    if ( @skipped ) {
	print qq{<h3>$lex{Missing} $lex{Timetable}</h3>\n};
	print @skipped, qq{<br>\n};
    }

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

}
    


#--------------
sub prTimetable {
#--------------

    my ($staffref, $termref) = @_;
    my @terms = @$termref;
    my @staff = @$staffref;

    my @skipped;

#    my $includeLocation = $arr{includeLocation};
#    my $includeSubjsec = $arr{includeSubjsec};
#    my $includeStudcount = $arr{includeStudcount};

#    delete $arr{includeLocation};
#    delete $arr{includeSubjsec};
#    delete $arr{includeStudcount};

    my (%sort, %staffname );
    my $sth = $dbh->prepare("select lastname, firstname from staff where userid  = ?");
    
    foreach my $userid ( @staff ) {
	$sth->execute( $userid );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my ($ln,$fn) = $sth->fetchrow;
	$sort{"$ln$fn$userid"} = $userid;
	$staffname{$userid} = qq{<b>$ln</b>, $fn};
    }

    
    foreach my $key ( sort keys %sort ) {
	my $userid = $sort{$key};
	
	# Get staff info
	my $sth = $dbh->prepare("select * from staff where userid = ?");
	$sth->execute( $userid );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my $ref = $sth->fetchrow_hashref;
	my %r = %$ref;

	# Check for a timetable, all terms.
	my $skipflag = 1;
	foreach my $term ( @terms ) {
	    my $sth = $dbh->prepare("select count(t.subjsec) from subject s, schedat t 
				    where s.teacher = ? and  startrptperiod <= '$term' and 
				    endrptperiod >= '$term' and s.subjsec = t.subjsec");

	    $sth->execute( $userid );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my $tcount = $sth->fetchrow;
	    if ( $tcount ) { # timetable count means we have entries for this term, at least.
		$skipflag = 0;
	    }
	}

	if ( $skipflag ) {  # no timetable (and courses) for these staff members.
	    push @skipped, "$r{firstname} $r{lastname}<br>";
	    next;
	}


	# Setup for Get Subject Information
	my $sth2 = $dbh->prepare("select description, smdesc, location, teacher, grade
          from subject where subjsec = ?");

	my $sth3 = $dbh->prepare("select count(distinct studnum) from eval where subjcode = ?");


	print qq{<h2>$r{sal} $r{firstname} $r{lastname}</h2>\n};
	
	foreach my $term ( @terms ) {
	
	    # Get their courses this term;
	    $sth = $dbh->prepare("select * from subject where teacher = ? and 
              startrptperiod <= '$term' and endrptperiod >= '$term'");
	    $sth->execute( $userid );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    
	    # Clean up global on later interations.
	    foreach my $key ( keys %timetable ) {
		delete $timetable{$key};
	    }

	    my %timetable; # timetable{period}{day}{subjsec} = 1
	    my $maxdays = 0;

	    my $sth1 = $dbh->prepare("select day, period from schedat
              where term = ? and subjsec = ? order by day, period");

	    my %periodmap; # stores the mapping values for period times;

	    # loop through all courses this term for this teacher.
	    while ( my $ref  = $sth->fetchrow_hashref ) { 
		my %s = %$ref;
		my $subjsec = $s{subjsec};
		$periodmap{ $g_PeriodMap{$s{grade}} } = 1; # the key has the map value.

		# load each timetable record for this subject.
		$sth1->execute( $term, $subjsec ) ;
		if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
		while ( my ( $day, $period ) = $sth1->fetchrow ) {
		    if ( $day > $maxdays ) { $maxdays = $day; }
		    push @{ $timetable{$period}{$day} }, $subjsec; # more than one course possible
		}
	    }

	    # Setup Period Times (into %periodTime{$period} = combined value.
	    my @vals = keys %periodmap;
	    my $mapvalue = pop @vals;
	    my %periodTime;
	    my %tempTime = %{ $g_PeriodTime{$mapvalue} };
	    foreach my $p ( keys %tempTime ) {
		my $start = $tempTime{$p}{s};
		my $end = $tempTime{$p}{e};
		my ($start,$end) = conv24to12($start,$end);
		my $val = qq{$start-$end};
		$periodTime{$p} = $val;
	    }
	    
	    # print qq{<div>MapValue:$mapvalue Periods:}, %periodTimes, "<br>\n";

	    
=head
	    # Testing %timetable
	    print qq{<h3>Timetable Hash</h3>\n};
	    foreach my $period (keys %timetable ) {
		foreach my $day ( keys %{ $timetable{$period} } ) {
		    print qq{Day:$day Period:$period Courses:}, @{ $timetable{$period}{$day} },};
                    print qq{<br>\n};
		}
	    }
=cut
	
	    if ( not %timetable ) { next; } # term

	    # Start Table.
	    print qq{<table cellspacing="0" border="1" cellpadding="3" style="margin-bottom:1em;">\n};
	
	    # Print Top Row here.
	    print qq{<tr><th>$lex{Term} $term / $lex{Day}</th>\n};

	    my $dayvalue;
	    for my $day ( 1 .. $maxdays ) { 
		if ( $g_DaysPerCycle == 5 or $g_DaysPerCycle eq 'W' or $g_DaysPerCycle eq 'w' ) {
		    # W|w = weekly
		    $dayvalue = $dow[$day + 1];
		} else {
		    $dayvalue = $day;
		}
		print qq{<th>$dayvalue</th>};
	    }
	    print qq{</tr>\n};

	    my @periods = sort { $a <=> $b } keys %timetable;
	    my $maxperiods = $periods[-1];

	    foreach my $period ( 1 .. $maxperiods ) {

		print qq{<tr><td>$lex{Period} $period<br>$periodTime{$period}</td>};
	    
		foreach my $day ( 1 .. $maxdays ) {

		    print qq{<td>};
		    while ( my $subjsec = pop @{ $timetable{$period}{$day} } ) {

			# Load subject information.
			$sth2->execute( $subjsec );
			if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
			my $ref = $sth2->fetchrow_hashref;
			%r = %$ref;
			
			if ( not $r{smdesc} ) { # which may be chosen field
			    $r{smdesc} = substr( $r{description},0, arr{descsize} );
			}

			
			# Load course enrollment
			$sth3->execute( $subjsec );
			if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
			$studcount = $sth3->fetchrow;

			# $arr{desctype} is either 'description' or 'smdesc' field
			my $coursedesc = $r{"$arr{desctype}"};
			if ( length $coursedesc > $arr{descsize} ) { # truncate.
			    $coursedesc = substr( $coursedesc, 0, $arr{descsize} );
			}

			# Append info to cell value
			my $cellvalue = qq{<b>$coursedesc</b><br>};
			if ( $arr{includeSubjsec} ) { $cellvalue .= qq{ $subjsec }; }
			if ( $arr{includeStudcount} and $studcount ) {
			    $cellvalue .= qq{ ($studcount)};
			}
			if ( $arr{includeLocation} and $r{location} ) {
			    $cellvalue .= qq{<br>$r{location}};
			}

			print qq{$cellvalue<br>};
		    }
		    print qq{</td>};

		} # end of day loop.
		print qq{</tr>\n};
		
	    } # end of periods loop

	    print qq{</table>\n};

	} # end of Term Loop

	if ( $arr{includePageBreak} ) {
	    print qq{<p style="page-break-after:always;"></p>\n};
	}
	## new page for next teacher.
	
    } # next userid

    return @skipped;

} # end of prTimetable




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


    my $checkteacher  = 1;
    if ( $arr{nocheck} ) {
	$checkteacher = 0;
    }

    
    print qq{<div><form action="$self" method="post">\n};
    print qq{<input type="hidden" name="nocheck" value="1">\n};
    print qq{<input type="submit" value="Unselect All Teachers"></form>\n\n};

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

    print qq{<table cellpadding="3" cellspacing="0" border="1" style="float:left;">\n};
    print qq{<tr><th>Staff Member</th><th>Position</th></tr>\n};
    
    # Get staff and real teachers are checked.
    my $sth1 = $dbh->prepare("select field_value from staff_multi where field_name = 'position' and userid = ?");
    

    my $sth = $dbh->prepare("select * from staff order by lastname, firstname");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $ref = $sth->fetchrow_hashref ) {
	my %r = %$ref;

	my $userid = $r{userid};
	$sth1->execute($userid);
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my ($checked, @position);
	while ( my $position = $sth1->fetchrow ) {
	    push @position, $position;
	    if ( $position eq 'Classroom Teacher' and $checkteacher ) {
		$checked = qq{checked="checked"};
	    }
	}

	my $pos = join(',',@position);
	
	print qq{<tr><td><input type="checkbox" name="$userid" value="1" $checked>\n};
	print qq{<b>$r{lastname}</b>, $r{firstname}</td><td>$pos</td></tr>\n};

    }

    print qq{</table>\n};

    print qq{<table cellpadding="3" cellspacing="0" border="1" style="float:left;margin-left:0.3em;">\n};
    print qq{<tr><th colspan="2">Program Options</th></tr>\n};
    
    # Now do the term
    print qq{<tr><td class="bla" colspan="2" style="font-size:120%;">$lex{'Terms'}};
    print qq{ <input type="text" name="term" size="12">\n};
    print qq{$lex{'Separate with Spaces'}</td></tr>\n};

    # Things to Include: location, count, subjsec
    my $checked = qq{checked="checked"};
    print qq{<tr><td class="bla" colspan="2"><input type="checkbox" name="includeSubjsec" value="1" $checked>};
    print qq{ Include Course Code-Section</td></tr>\n};

    print qq{<tr><td class="bla" colspan="2"><input type="checkbox" name="includeStudcount" value="1">};
    print qq{ Include Student Count</td></tr>\n};

    print qq{<tr><td class="bla" colspan="2"><input type="checkbox" name="includeLocation" value="1">};
    print qq{ Include Room # / Location</td></tr>\n};

    print qq{<tr><td class="bla" colspan="2"><input type="checkbox" name="includePageBreak" value="1" $checked>};
    print qq{ Add Page Break after each Staff Member</td></tr>\n};
    
    print qq{<tr><td><select name="desctype"><option value="description">Full</option>};
    print qq{<option value="smdesc">Short</option>};
    print qq{</select></td><td class="bla">Course Description Size</td></tr>\n};

    print qq{<tr><td><input type="text" name="descsize" style="width:2em;" value="25"></td>\n};
    print qq{<td class="bla">Max Description Characters (for Full Description)</td></tr>\n};
    
    
    print qq{<tr><td class="la" colspan="2">};
    print qq{<input type="submit" value="$lex{Continue}"></td></tr>\n};

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

    exit;
}


#-------------
sub conv24to12 {
#-------------

    my @times;
    while ( my $time = shift ) {

#	if ( not $time ) { return }
	$time =~ s/\s+//g; # strip any spaces.
	my ($hr, $min) = split(':', $time);
	my $ampm = 'AM';
	if ( $hr == 12 ) { $ampm = 'PM'; }
	if ( $hr == 0 ) { $hr = 12; };

	if ( $hr > 12 ) { 
	    $hr -= 12;
	    $ampm = 'PM';
	}

	my $t = qq{$hr:$min$ampm};
	push @times, $t;
    }

    return @times;

}


