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

#  This file is part of Open Admin for Schools.

# Note to self: needs to be redone. Remove any term requirements and
# print all terms containing timetable data for a teacher.


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



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 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 style="margin:1em;">\n};

print qq{<div>[ <a href="$homepage">$lex{Main}</a> };
unless (getcwd() =~ /tcgi/){ # unless we are in tcgi
    print qq{| <a href="$schpage">$lex{Timetable}</a> };
}
print qq{]</div>\n};



# Get Teacher's Grade by homeroom or courses.
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;  # get the first grade value
}


# Get the term or current term
my $term = $arr{term};
if ( not $term ) { # figure out the term for this userid.
    
    # Get Track from grade
    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;
	}
    }
} # end of finding term.


# 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 courses in the timetable and find matching teacher userid
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;
}


# Form Start
print qq{<div style="margin:1em;">\n};
print qq{<form action="$self" method="post" };
print qq{style="display:inline;border:1px solid gray;padding:0.4em;">\n};

# Terms
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 value=""></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
	if ( $uid eq $userid ) { next; }
	print qq{<option value="$uid">$staffname{$uid}</option>};
    }
}
print qq{<option value=""></option></select>\n};
print qq{<input type="submit" value="$lex{View}"></form>\n};
print qq{</div>\n};
# end of form.


# Find Numbers of Rows (periods) and Columns(Days) in Cycle (total)
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;
}

# Get courses for this teacher from the subject table (either teacher or teacher2)
my %courses;
my $sth = $dbh->prepare("select subjsec, description from subject 
			where (teacher = ? or teacher2 = ?) and
			startrptperiod <= '$term' and
			endrptperiod >= '$term'");
$sth->execute($userid, $userid);
if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr;}
while ( my ($subjsec,$desc) = $sth->fetchrow ) {
    $courses{$subjsec} = $desc;
}

my @subjects = keys %courses;


printTimetable($userid, $term, \@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);
    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" };
	    print qq{style="float:left;margin:0.4em;">\n};
	    print qq{<caption style="font-size:120%;font-weight:bold;">$firstname $lastname - };
	    print qq{$lex{Term} $term <span style="font-size:80%">(Enrolled)</span></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' ) {
		    # W or w is 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">P $i $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 $sv ($enrolcount) $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;

}
