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

# display teacher timetables. If passed teacher userid,
# display only that teacher's timetable.

my %lex = ('Day' => 'Day',
	   'Term' => 'Term',
	   'No Value' => '',
	   'View' => 'View',
	   'Teacher Timetable' => 'Teacher Timetable',
	   'Timetable' => 'Timetable',
	   'Per' => 'Per',
	   'Main' => 'Main',
	   'Teacher' => 'Teacher',
	   'View' => 'View',
	   'No Records Found' => 'No Records Found',
	   'Error' => 'Error',
	   'Period' => 'Period',

	   );

my $self = 'tchschedview.pl';

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

my $stripampm = 1; # turn off with a zero value.


# Set prepath for config file: (/tcgi or cgi/schedule)
my $prepath = '../..';
if ( getcwd() =~ /tcgi/){ # we are in tcgi
    $prepath = '..';

}

eval require "$prepath/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;

my ($sec, $min, $hour, $mday, $mon, $year, $wday, 
    $yday, $iddst) = localtime(time);
$year = $year + 1900;
$mon++;
if ( length($mon) == 1 ) { $mon = '0'. $mon; }
if ( length($mday) == 1 ) { $mday = '0'. $mday; }
my $currdate = "$year-$mon-$mday";
my $currjd = julian_day($year,$mon,$mday);
# $currlongdate = "$dowstd[$wday], $month[$mon] $mday, $year";



#$sth = $dbh->prepare("select distinct schedat.subjsec, subject.description, 
#  subject.teacher, schedat.term from schedat
#  left outer join subject on schedat.subjsec = subject.subjsec
#  $select order by subject.teacher, schedat.term");

my $userid;
if ( not defined $arr{userid} ) {
    $userid = $ENV{'REMOTE_USER'};
} else {
    $userid = $arr{userid};
}


# Get Teacher's Grade
my $sth = $dbh->prepare("select field_value from staff_multi where userid = ? and field_name = 'grade'");
$sth->execute( $userid );
if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
my $grade = $sth->fetchrow;
if ( not $grade ) { # get from a subject.
    my $sth = $dbh->prepare("select distinct grade from subject where teacher = ?");
    $sth->execute( $userid );
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    $grade = $sth->fetchrow;
}


my $term = $arr{term};
if ( not $term ) { # figure out the term for this userid.

    # Get Track.
    my $track = $g_MTrackTermType{ $grade };
    
    # Get Term
    for my $trm ( sort keys %{ $g_MTrackTerm{$track} } ) {
	my $start = $g_MTrackTerm{$track}{$trm}{start};
	my $startjd = julian_day( split('-',$start));
	my $end = $g_MTrackTerm{$track}{$trm}{end};
	my $endjd = julian_day( split('-',$end));
	if ( $currjd >= $startjd and $currjd <= $endjd ) {
	    $term = $trm;
	    last;
	}
    }

   
}


my $select;
if ( $term and $userid ) {
    $select = "where schedat.term = '$term' and subject.teacher = '$userid' ";
} elsif ( $term ) {
    $select = "where schedat.term = '$term' ";
} elsif ( $userid ) {
    $select = "where subject.teacher = '$userid' ";
}


# Get current dir so know what CSS to display;
if (getcwd() =~ /tcgi/){ # we are in tcgi
    $css = $tchcss;
    $homepage = $tchpage;
}


# print page header.
my $title = qq{$lex{View} $lex{'Teacher Timetable'}};
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> };
unless (getcwd() =~ /tcgi/){ # unless we are in tcgi
    print qq{| <a href="$schpage">$lex{Timetable}</a> };
}
print qq{]\n};

# print qq{Userid:$userid Term:$term Grade:$grade<br>\n};


# Get Teacher values for the Form
my $sth = $dbh->prepare("select lastname, firstname, userid from staff order by lastname, firstname");
$sth->execute;
if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
my (@staff, %staffname);
while ( my ( $lastname, $firstname, $userid)  = $sth->fetchrow ) {
    push @staff, $userid;
    $staffname{$userid} = qq{$lastname, $firstname};
}

# Get Terms from Eval table.
$sth = $dbh->prepare("select distinct term from eval order by term");
$sth->execute;
if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
my @terms;
while ( my $t  = $sth->fetchrow ) {
    push @terms, $t;
}

# get the subjects in the timetable and find matching teacher.
my (%courses, %teachers);
$sth = $dbh->prepare("select distinct s.subjsec, su.teacher from schedat s, subject su where s.subjsec = su.subjsec");
$sth->execute;
if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
while ( my ($subjsec, $userid)  = $sth->fetchrow ) {
    push @{ $teachers{$userid}}, $subjsec;
    $courses{$subjsec} = $userid;
}

# Terms
print qq{<form action="$self" method="post" style="display:inline;">\n};
print qq{$lex{Term} <select name="term"><option>$term</option>\n};
foreach my $trm ( @terms ) {
    if ( $trm == $term ) { next; }
    print qq{<option>$trm</option>}; 
}
print qq{<option></option></select>\n};

# Teachers
print qq{$lex{Teacher} <select name="userid"><option value="$userid">$staffname{ $userid}</option>\n};
foreach my $uid ( @staff ) {
    if ( $teachers{$uid} ) {  # only display if they have a timetable somewhere
	print qq{<option value="$uid">$staffname{$uid}</option>};
    }
}
print qq{<option></option></select>};
print qq{<input type="submit" value="$lex{View}"></form>\n};
print qq{<div style="clear:both;"></div>\n};


# Find Numbers of Rows (periods) and Columns(Days) in Cycle
my $sth = $dbh->prepare("select max(period) from schedat");
$sth->execute;
if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
my $tblrows = $sth->fetchrow;

$sth = $dbh->prepare("select max(day) from schedat");
$sth->execute;
if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
$tblcols = $sth->fetchrow;

if ( $tblrows < 1 ) {
    print qq{<h3>$lex{'No Records Found'}</h3>\n};
    print qq{</body></html>\n};
    exit;
}


$sth = $dbh->prepare("select distinct schedat.subjsec, subject.description, 
  subject.teacher, schedat.term from schedat
  left outer join subject on schedat.subjsec = subject.subjsec
  $select order by subject.teacher, schedat.term");
# $select is set above.

$sth->execute;
if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr;}

my $oldterm = -1; 
my $oldtch = -1;
my $firstflag = 1;

while ( my ($subjsec,$desc,$teacher,$term) = $sth->fetchrow ) {
    
    #print qq{Subj: $subjsec Tch: $teacher $term<br>\n};
    $oldterm = $currterm;
    $currterm = $term;
    $oldtch = $currtch;
    $currtch = $teacher;

    if ( ($currterm ne $oldterm or $currtch ne $oldtch ) and not $firstflag ) { 
	# change in teacher or term
	# ship to printTimetable with $teacher, $term, and @subjects
	printTimetable($oldtch, $oldterm, \@subjects);
	if ( $currtch ne $oldtch ) { print qq{<div style="clear:both;"></div><hr>\n}; }
	@subjects = (); # empty array.
	push @subjects,$subjsec; # start new array with existing value.
	
    } else {
	push @subjects, $subjsec;
	$firstflag = 0;
    }

}

# print out the last table.
printTimetable($currtch, $currterm, \@subjects);

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


#-----------------
sub printTimetable { # print timetable for one teacher for 1 term.
#-----------------

    my ($teacher, $term, $subjref) = @_; 

    if ( not $teacher or not $term ) {
#	print qq{<h3>$lex{'No Records Found'} - Teacher $teacher - Term $term</h3>\n};
	return;
    }

    # Get Teacher Name
    my $sth = $dbh->prepare("select lastname, firstname from staff where userid = ?");
    $sth->execute( $teacher );
    my ($lastname, $firstname) = $sth->fetchrow;

    # Courses
    my @subject;
    my ($tblcols, $tblrows); # not globals anymore
    foreach my $subjsec ( @{ $subjref } ) {

	my $sth = $dbh->prepare("select day, period from schedat 
         where term = ? and subjsec = ? order by period, day");
	$sth->execute($term, $subjsec);
	while (my ($day, $period) = $sth->fetchrow ) {
	    # setup values for $tblrows and $tblcols
	    if ( $day > $tblcols ) { $tblcols = $day; }
	    if ( $period > $tblrows ) { $tblrows = $period; }

	    if ($subject[$period][$day] and $subject[$period][$day] ne $subjsec){ 
		# if a value exists and is not identical to subjsec then add to it.
		$subject[$period][$day] .= " $subjsec";
	    } else { # just slap it in...
		$subject[$period][$day] = $subjsec;
	    }
	}
    }
    # Done filling 2D array.

    my $sth = $dbh->prepare("select description, location  from subject where subjsec = ?");
    my $sth1 = $dbh->prepare("select count(distinct studnum) from eval where subjcode = ?");
    
    # Main body of table.
    my $first = 1;

    # Period Times
    my %periodTime;    
    my %tempTime = %{ $g_PeriodTime{$g_PeriodMap{$grade}} };
    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};
	if ( $stripampm ) { $val =~ s/AM|PM|am|pm//g; }
	$periodTime{$p} = $val;
    }

    
#    print qq{Grade:$grade Periods:}, %periods, "<br>\n";
    # periods{s or e}

    
    for $i (1..$tblrows){

	if ( $first ) {
	    # print heading
	    print qq{<table cellpadding="3" cellspacing="0" border="1" style="float:left;margin:0.4em;">\n};
	    print qq{<caption style="font-size:120%;font-weight:bold;">$firstname $lastname - };
	    print qq{$lex{Term} $term</caption>\n};
	    

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

	
	print qq{<tr><td class="cn">$lex{Period} $i<br>$periodTime{$i}</td>};
	for (1..$tblcols){
	    if ($subject[$i][$_]){ # if we have a subjsec value;
		my $firstflag = 1;
		@subjval = split(/\s+/,$subject[$i][$_]);
		print qq{<td>};
		foreach my $sv (@subjval){
		    if (not $firstflag){ print qq{<br>};} else { $firstflag = 0;}

		    # Get Course Description and Location
		    $sth->execute($sv);
		    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
		    my ($desc,$location) = $sth->fetchrow;

		    # Get Enrollment count
		    $sth1->execute($sv);
		    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
		    my $enrolcount = $sth1->fetchrow;

		    
		    print qq{$desc<br>$sv ($enrolcount)<br>$location};
		}
		print qq{</td>};
	    } else {
		print qq{<td style="color:green;">$lex{'No Value'}</td>};
	    }
	}
	print qq{</tr>\n};
    }
    print qq{</table>\n};

    if ( $first ) { 
	print qq{<h3>$lex{'No Records Found'} - $firstname $lastname - $lex{Term} $term</h3>\n};
    }

    return;

}



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

}
