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

#  This file is part of Open Admin for Schools.

# An admin site script to view teachers' daybook timetables


my %lex = ('Main' => 'Main',
	   'Error' => 'Error',
	   'Timetable Entry' => 'Timetable Entry',
	   'Timetable' => 'Timetable',
	   'Grade' => 'Grade',
	   'Term' => 'Term',
	   'Terms' => 'Terms',
	   'Day' => 'Day',
	   'Save' => 'Save',
	   'Period' => 'Period',
	   'Add Backings' => 'Add Backings',
	   'Records Stored' => 'Records Stored',
	   'Contact' => 'Contact',
	   'Separate with Spaces' => 'Separate with Spaces',
	   'Additional Subjects' => 'Additional Subjects',
	   'Continue' => 'Continue',
	   'Teacher' => 'Teacher',
	   'Or' => 'Or',
	   'Either' => 'Either',
	   'No Terms Found' => 'No Terms Found',
	   'Number of Periods' => 'Number of Periods',
	   'Same Day/Period; More Than 1 Subject' => 'Same Day/Period; More Than 1 Subject',
	   'No Terms' => 'No Terms',
	   'Course' => 'Course',
	   'Exists' => 'Exists',
	   'Skipping' => 'Skipping',
	   'Per' => 'Per',
	   'Current' => 'Current',

	   'User Id' => 'User Id',
	   'Password' => 'Password',
	   'Not Found' => 'Not Found',
	   'Cookie Duration' => 'Cookie Duration',
	   'Please Log In' => 'Please Log In',
	   'Set' => 'Set',
	   'Select' => 'Select',
	   'Add' => 'Add',
	   'Delete' => 'Delete',
	   
	   );


use DBI;
use CGI;


my $self = "dbkViewTimetable.pl";

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


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

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



my $sth = $dbh->prepare("select datavalue from conf_system where dataname = ?");
foreach my $var ( qw( doctype chartype charset css homepage g_MTrackTerm
  g_AttendanceEntryMethod g_DaysPerCycle)) {
    $sth->execute( $var );
    my $datavalue = $sth->fetchrow;
    eval $datavalue;
    if ( $@ ) {
	print "$lex{Error}: $@<br>\n";
	die "$lex{Error}: $@\n";
    }
}

print $q->header( -charset, $charset );



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



# Starting Page
if ( not $arr{page} ){
    showStartPage();

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


#-----------------
sub showTimetables {
#-----------------

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

    my @terms;
    foreach my $key ( keys %arr ) {
	if ( $key =~ m/term/ ) {
	    $key =~ s/term//; # strip leading term text.
	    push @terms, $key;
	}
    }

    if ( not @terms ) {
	print qq{<h3>No Terms Selected</h3>\n};
	print qq{</body></html>\n};
	exit;
    }
    
    my (%teacher,%sort);
    
    my $sth = $dbh->prepare("select lastname, firstname from staff where userid = ?");

    
    foreach my $key ( keys %arr ) {
	my ($sigil,$userid) = split(':',$key);
	if ( $sigil eq 'T' ) { # we have a teacher userid

	    # get teacher name
	    $sth->execute( $userid );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my ( $lastname, $firstname ) = $sth->fetchrow;

	    $teacher{$userid} = qq{<b>$lastname</b>, $firstname};
	    $sort{"$lastname$firstname$userid"} = $userid;
	}
    }

    # Loop over all teachers, all terms.
    foreach my $key ( sort keys %sort ) {
	my $userid = $sort{$key};

	# Display All Current Timetables
	print qq{<h3>$teacher{$userid}</h3>\n};
	
	foreach my $trm ( sort @terms ){
	    printTimetable($userid,$trm );
	}
	print qq{<div style="clear:both;"></div><hr>\n};

    }

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

    exit;

    
} # end of showTimetables



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

    # Load terms from school year configuration
    my %terms;
    foreach my $key ( sort keys %g_MTrackTerm ) {
	foreach my $t ( sort keys %{ $g_MTrackTerm{$key}} ) {
	    $terms{$t} = 1;
	}
    }

    if ( not %terms ) {
	print qq{<h1>$lex{'No Terms Found'}</h1>\n};
	print qq{</body></html>\n};
	exit;
    }


    # Get the Classroom Teachers


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

    # Get homeroom
    my $sth2 = $dbh->prepare("select field_value from staff_multi where field_name = 'homeroom'
			     and userid = ?");

    
    my $sth = $dbh->prepare("select userid from staff_multi 
			    where field_name = 'position' and field_value = 'Classroom Teacher'");

    my (%teacher,%sort,%homeroom);    
    
    $sth->execute;
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $userid = $sth->fetchrow ) {
	# Get Name of Teacher
	$sth1->execute( $userid );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my ($lastname, $firstname ) = $sth1->fetchrow;

	# Get Homeroom(s) of Teacher
	my @rooms;
	$sth2->execute( $userid );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	while (my $hr = $sth2->fetchrow) {
	    push @rooms, $hr;
	}
	my $rooms = join(',',@rooms);
	
	$homeroom{$userid} = $rooms;
	$teacher{$userid} = qq{<b>$lastname</b>, $firstname};
	$sort{"$lastname$firstname$userid"} = $userid;
    }


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

    print qq{<table cellpadding="1" cellspacing="0" border="0" };
    print qq{style="border:1px solid gray;padding:0.4em;">\n};

    # Select Terms
    print qq{<tr><td colspan="2" class="bla">$lex{Select} $lex{Terms} \n};
    foreach my $trm ( sort {$a <=> $b} keys %terms ){
	print qq{<input type="checkbox" name="term$trm" value="1">$lex{Term} $trm / \n};
    }
    print qq{</td></tr>\n};

    print qq{<tr><th>Teacher</th><th>Homeroom</th></tr>\n};
    
    # Display Teachers.
    print qq{<tr><td>\n};
    foreach my $key ( sort keys %sort ) {
	my $userid = $sort{$key};
	print qq{<tr><td><input type="checkbox" name="T:$userid" value="1" };
	if ( $homeroom{$userid} ) {
	    print qq{checked};
	}
	print qq{>\n}; # close the element
	print qq{$teacher{$userid} ($userid)</td><td>$homeroom{$userid}</td></tr>\n};
    }
    
    # Continue
    print qq{<tr><td class="la" colspan="2"><input type="submit" value="$lex{Continue}"></td></tr>\n};
    print qq{</table></form>\n};

    
    # Display All Current Timetables
#    print qq{<div style="font-weight:bold;font-size:120%;margin:1em;">};
#    print qq{$lex{Current} $lex{Timetable}</div><hr>\n};

#    foreach my $trm ( sort {$a <=> $b} keys %terms ){
#	printTimetable($userid,$trm );
#    }
#    print qq{<div style="clear:both;"></div><hr>\n};
    
    print qq{</body></html>\n};

    exit;
}


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

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

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

    
    # Get Subjects and Activities from dbktimetable.
    my $sth = $dbh->prepare("select day, period, courseact from dbktimetable  
      where term = ? and userid = ?
      order by period, day");
    $sth->execute( $term, $teacher );
    my %courseact;  # courseact{period}{day}{courseact} = 1;
    while ( my ($day, $period, $courseact) = $sth->fetchrow ) {
#	print "Day:$day Period:$period CRS:$courseact<br>\n";
	$courseact{$period}{$day}{$courseact} = 1;
    }

    
    if ( not %courseact ) { return; } # no timetable
    
    my $sth = $dbh->prepare("select description from subject where subjsec = ?");
    my $sth1 = $dbh->prepare("select title from dbkactivity where id = ?");

    # Find max days and periods for table.
    my ($maxperiod, $maxday);
    foreach my $period ( sort keys %courseact ) {
	foreach my $day ( sort keys %{ $courseact{$period} } ) {
	    if ( $period > $maxperiod ) { $maxperiod = $period; }
	    if ( $day > $maxday ) { $maxday = $day; }
	}
    }

    
    # 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></th>};
    
    foreach my $day (1..$maxday){ print qq{<th>$lex{Day} $day</th>}; }
    print qq{</tr>\n};
    
    # Main body of table.
    for $period (1..$maxperiod){
	print qq{<tr><td>$lex{Per} $period</td>};
	
	foreach my $day (1..$maxday ) {
	    
	    if ( %{ $courseact{$period}{$day}}  ) {

		print qq{<td>};
		# Loop through each course/activity and print title/desc
		foreach my $crsact ( keys %{ $courseact{$period}{$day} } ) {
		    
#		    print "CRSACT:$crsact Day:$day Period:$period<br>\n";
		    
		    my $desc; # description (course) or title (activity)
		    my ($type, $id) = split('-', $crsact );
		    
		    if ( $type eq 'ACTIV' ) { # an activity
			$sth1->execute( $id );
			if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
			$desc = $sth1->fetchrow;
			$desc = "<b>ACT</b> $desc";
			
		    } else { # a course (with course code)
			$sth->execute( $crsact );
			if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
			$desc = $sth->fetchrow;
			$desc .= ($crsact);
		    }
			
		    print qq{$desc<br>\n};
		}
		print qq{</td>};
		
	    } else {
		print qq{<td style="color:green;">$lex{'No Value'}</td>};
	    }
	}
	print qq{</tr>\n};
    }
    print qq{</table>\n};

    return;

}
