#!/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.


my %lex = ('Main' => 'Main',
	   'Timetable' => 'Timetable',
	   'Error' => 'Error',
	   'Day' => 'Day',
	   'Period' => 'Period',
	   'Location' => 'Location',
	   'Subject' => 'Subject',
	   'Current Date' => 'Current Date',
	   'Not Found' => 'Not Found',
	   'Term' => 'Term',
	   'Teacher Timetable' => 'Teacher Timetable',
	   'Day In Cycle' => 'Day In Cycle',
	   'Level' => 'Level',
	   'Time' => 'Time',
	   
	   );

use DBI;
use CGI;
use Time::JulianDay;
use Cwd;

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

} else {
    $configpath = '../..'; # go back two to get to etc.
}


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

# load findDayInCycle
eval require "$configpath/lib/libschedule.pl";
if ( $@ ) {
    print qq{$lex{Error}: $@<br>\n};
    die qq{$lex{Error}: $@\n};
}


# Set Date
my @tim = localtime(time);
my $year = $tim[5] + 1900;
my $month = $tim[4] + 1;
my $day = $tim[3];
my $dow = $tim[6] + 1;
if (length($month) == 1){ $month = "0".$month;}
if (length($day) == 1){ $day = "0".$day;}
my $currdate = "$year-$month-$day";
my $displaydate = "$dow[$dow], $month[$month] $day, $year";

my $currjd = julian_day( split (/-/, $currdate) );

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

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



# Set Current Terms for various tracks.
my $track; 
my %currterms;
foreach my $trk ( keys %{ g_MTrackTerm } ) {
    foreach my $trm ( sort keys %{ $g_MTrackTerm{$trk} } ) {

	my $startdate = $g_MTrackTerm{$trk}{$trm}{'start'};
	my $enddate = $g_MTrackTerm{$trk}{$trm}{'end'};

	my $startjd = julian_day( split (/-/, $startdate ));
	my $endjd = julian_day( split (/-/, $enddate ));

	if ( $endjd >= $currjd and $startjd <= $currjd ){
	    $currterms{$trk} = $trm; last;
	}
    }
}


# Get Day in Cycle
my $dayInCycle = findDayInCycle( $currdate, $dbh );

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


# Print HTML Page Header
print qq{$doctype\n<html><head><title>$lex{'Teacher Timetable'}</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};
if ( not $teachermode ) {
    print qq{| <a href="$schpage">$lex{Timetable}</a>};
}
print qq{ ]\n};

# Date and Day In Cycle
print qq{<h3>$displaydate - $lex{'Day In Cycle'}: $dayInCycle</h3>\n};

# Print out tracks and current terms
print qq{<table cellpadding="3" cellspacing="0" border="1" style="margin-bottom:1em;">\n};
print qq{<tr><th>$lex{Level}</th><th>$lex{Term}</th></tr>\n};
foreach my $track ( sort keys %currterms ) {
    print qq{<tr><td>$g_TrackDisplay{$track}</td><td>$currterms{$track}</td></tr>\n};
}
print qq{</table>\n};



# Find subjects first and their terms.
$sth = $dbh->prepare("select subjsec, grade, startrptperiod, endrptperiod,
  description, teacher, location from subject order by teacher, description");
$sth->execute;
if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }

my $sth1 = $dbh->prepare("select count(*) from eval where subjcode = ?");
my $sth2 = $dbh->prepare("select lastname, firstname from staff where userid = ?");

my %teachers; # main data structure.
my %loc; #location.
my %tch; # teacher name (userid).
# $teachers{userid}{period}{subjsec}

while ( my ( $subjsec, $grade, $startterm, $endterm, $description,
	     $teacher, $location ) = $sth->fetchrow ) {

    # Check if any enrollments
    $sth1->execute( $subjsec );
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    my $count = $sth1->fetchrow;
    if ( not $count ) { next; } # skip if no enrollments

    # Get the term.
    if ( not $track ) {	$track = $g_MTrackTermType{ $grade }; } # track from subject grade.
    my $trm = $currterms{$track};

    # Check if active.
    if ( $trm < $startterm or $trm > $endterm ) { # inactive term.
	next;
    }

    my $userid = $teacher; # get userid of teacher.
    $loc{$subjsec} = $location; # location hash.

    # Get Teacher Name
    $sth2->execute( $userid );
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    my ($lastname, $firstname) = $sth2->fetchrow;

    $teachersort{"$lastname$firstname$userid"} = $userid;
    $tch{$userid} = qq{<b>$lastname</b>, $firstname};


    # Get the schedule period(s)
    my $sth2 = $dbh->prepare("select period from schedat 
      where subjsec = ? and term = ? and day = ?");

    # Get the Periods
    $sth2->execute( $subjsec, $trm, $dayInCycle );
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    while ( my $period = $sth2->fetchrow ) {
	my $timemap = $g_PeriodMap{$grade};
	my $start = $g_PeriodTime{$timemap}{$period}{'s'};
	my $end = $g_PeriodTime{$timemap}{$period}{'e'};
	$start =~ s/\s+$//; # strip trailing space
	$end =~ s/\s+$//;

	my $time = qq{$start-$end};
	
	$teachers{$userid}{$period}{$subjsec} = $time;
	
    }
}

my $tchcount = scalar keys %teachers;
$tchcount = $tchcount / 3; # split in half; could be fractional
$sth = $dbh->prepare("select description from subject where subjsec = ?");

my $tcount; # counter for split page
print qq{<div style="float:left;">\n};

# Now print the data structure
foreach my $key ( sort keys %teachersort ) {

    my $userid = $teachersort{$key};
    print qq{<div style="font-size:120%;font-weight:bold;">$tch{$userid}</div>\n};
    
    my $first = 1;
    foreach my $period ( sort {$a <=> $b} keys %{$teachers{$userid}} ) {

	if ( $first ) {
	    print qq{<table cellpadding="3" cellspacing="0" border="1" style="margin:0.4em;">\n};
	    print qq{<tr><th>$lex{Subject}</th><th>$lex{Period}</th><th>$lex{Time}</th>};
	    print qq{<th>$lex{Location}</th></tr>\n};
	    $first = 0;
	}

	foreach my $subjsec ( sort keys %{ $teachers{$userid}{$period} } ) {

	    $sth->execute($subjsec);
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    my $description = $sth->fetchrow;

	    my $time = $teachers{$userid}{$period}{$subjsec};
	    
	    print qq{<tr><td class="la"><b>$description</b> ($subjsec)</td>};
	    print qq{<td class="cn">$period</td><td>$time</td>};
	    print qq{<td class="la">$loc{$subjsec}</td></tr>\n};
	}
    } # end of period loop

    if ( not $first ) {
	print qq{</table>\n};
	$tcount++;
	if ( $tcount > $tchcount ) {
	    $tcount = 0;
	    print qq{</div><div style="float:left">\n};
	}
	
    } else {
	print qq{<div>No Periods Set</div>\n};
    }

} # end of teacher loop

print qq{</div><div></div>\n};
print qq{<break clear="left">\n};
print qq{</body></html>\n};
