#!/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',

	   'Next Week' => 'Next Week',
	   'Previous Week' => 'Previous Week',
	   'Select' => 'Select',
	   'Date' => 'Date',
	   'Go' => 'Go',


	   
	   );


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


my $self = "dbkViewPlanning.pl";

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

eval require "../../lib/libschedule.pl";
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 dow month s_month)) {
    $sth->execute( $var );
    my $datavalue = $sth->fetchrow;
    eval $datavalue;
    if ( $@ ) {
	print "$lex{Error}: $@<br>\n";
	die "$lex{Error}: $@\n";
    }
}

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

my (@tim, $year,$month,$day);
@tim = localtime(time);
$year = $tim[5] + 1900;
$month = $tim[4] + 1;
$day = $tim[3];
my $currjd = julian_day($year,$month,$day);
if ( not $arr{date} ) { # put in current date;
    $arr{date} = qq{$year-$month-$day};
}


# print page header.
my $title = "$lex{View} Teachers' Lesson Plans";
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:0.5em;">\n};

print qq{[ <a href="$homepage">$lex{Main}</a> ]\n};
print qq{<h1>$title</h1>\n};

# format arr{date}
my ($tyr,$tmo,$td) = split('-',$arr{date});
my $tempjd = julian_day($tyr,$tmo,$td);
my $tdow = day_of_week($tempjd) + 1; # not zero based

print qq{<h4>$dow[$tdow], $month[$tmo] $td $tyr</h4>\n}; # ($arr{date})


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

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



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


    # Setup for Calendar popup.
    print qq{<link rel="stylesheet" type="text/css" media="all" href="/js/calendar-blue.css" };
    print qq{title="blue">\n};
    print qq{<script type="text/javascript" src="/js/calendar.js"></script>\n};
    print qq{<script type="text/javascript" src="/js/lang/calendar-en.js"></script>\n};
    print qq{<script type="text/javascript" src="/js/calendar-setup.js"></script>\n};

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

    
    # Display Date Selections at top of the page.
    my ($currdate,$currsdate, $mondayjd, $currjd, $dow );
    if ( $arr{date} ) {

	# Generate a list from those dates.
	($year,$month,$day) = split('-',$arr{date});
    
	$currjd = julian_day($year,$month,$day);
	$dow = day_of_week($currjd);
	$mondayjd = $currjd - ($dow-1);
	
	if ( $dow == 0 or $dow == 6 ) { # weekend, change to next monday;
	    $nextmondayjd = $currjd - ($dow-1) + 7;
	    $currjd = $nextmondayjd;
	    ($year,$month,$day) = inverse_julian_day( $currjd );
	    $dow = day_of_week($currjd);
	}
    
	if (length($month) == 1){ $month = "0".$month;}
	if (length($day) == 1){ $day = "0".$day;}
	$currsdate = "$year$month$day"; 
	$currdate = "$year-$month-$day";

    } else {

	@tim = localtime(time);
	$year = $tim[5] + 1900;
	$month = $tim[4] + 1;
	$day = $tim[3];

	$currjd = julian_day($year,$month,$day);
	$dow = day_of_week($currjd); # for consumption below also; subj att entry
	$mondayjd = $currjd - ($tim[6]-1); #This will now give Monday of that week.
	if (length($month) == 1){ $month = "0".$month;}
	if (length($day) == 1){ $day = "0".$day;}
	$currdate = "$year-$month-$day";
	$currsdate = "$year$month$day";

    } 

    
    # Weekly Date Calcs - Previous Week / Next Week.
    my $prevjd = $mondayjd - 7;
    my ($prevyear, $prevmonth, $prevday) = inverse_julian_day($prevjd);
    my $prevdate = "$prevyear-$prevmonth-$prevday";

    
    print qq{<tr><td colspan="2">};
    print qq{<form action="$self" method="post" style="display:inline;">\n};
    print qq{<input type="hidden" name="date" value="$prevdate">\n};
    print qq{<input type="submit" value="<= $lex{'Previous Week'}"></form>\n};

    my $nextjd = $mondayjd + 7; 
    my ($nextyear, $nextmonth, $nextday) = inverse_julian_day($nextjd);
    my $nextdate = "$nextyear-$nextmonth-$nextday";

    print qq{<form action="$self" method="post" style="display:inline;">\n};
    print qq{<input type="hidden" name="date" value="$nextdate">\n};
    print qq{<input type="submit" value="$lex{'Next Week'} =>"></form>\n\n};


    # Pop Up Calendar Date Selector
    print qq{<form action="$self" method="post" };
    print qq{style="display:inline;background-color:yellow;padding:0.3em 0.5em;};
    print qq{border:1px solid gray;">\n};

    print qq{<button type="reset" id="date_trigger">$lex{Select} $lex{Date}</button>\n};
    print qq{<input type="text" name="date" id="date" style="width:12ch;">\n};
    print qq{<input type="submit" value="$lex{Go}">\n};
    print qq{</form><br>\n\n};


    my $sth = $dbh->prepare("select id, dayfraction from dates where date = ?");

    for my $i ( 1..5 ) { # five days of this week.

	my ($wkyear, $wkmonth, $wkday) = inverse_julian_day($mondayjd);
	my $dow = day_of_week($mondayjd) + 1;
	my $tmpdate = qq{$wkyear-$wkmonth-$wkday};

	# Check for date being fully closed or not (ie ALL DAy).
	# Skip if closed all day.
	$sth->execute( $tmpdate );
	my ( $id, $dayfrac ) = $sth->fetchrow;
	# Logic: Skip for attendance if closed all day.
	if ( $dayfrac > 0.99 ) { # ie. only 1.000, closed all day, skip
	    $mondayjd++;
	    next;
	}

	print qq{<form action="$self" method="post" style="display:inline;">\n};
	print qq{<input type="hidden" name="date" value="$tmpdate">\n};
	print qq{<input type="submit" value="$dow[$dow] $s_month[$wkmonth] $wkday"></form>\n};
	$mondayjd++;
    }
    print qq{</td></tr>\n};

    

    # 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{<input type="hidden" name="date" value="$arr{date}">\n};


    # Select Term
    # 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;
    }

    print qq{<tr><th>Select Current Term</th></tr>\n};
    print qq{<tr><td>};
    foreach my $trm ( sort {$a <=> $b} keys %terms ){
	print qq{<input type="radio" name="term" value="$trm">$lex{Term} $trm \n};
    }
    print qq{</td></tr>\n};
    # End of Term Setting
    
    
    print qq{<tr><th style="text-align:left;padding:0.4em;">Teacher / Homeroom</th></tr>\n};
    print qq{<tr><td class="la" colspan="2"><input type="submit" value="$lex{Continue}"></td></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="$userid" value="1" };
#	if ( $homeroom{$userid} ) {
#	    print qq{checked};
#	}
	print qq{>\n}; # close the element
	print qq{$teacher{$userid} ($userid) };
	if ( $homeroom{$userid} ) {
	    print qq{/ <b>$homeroom{$userid}</b>};
	}
	print qq{</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};



    print qq{<script type="text/javascript">
 Calendar.setup({
   inputField  : "date",
   ifFormat    : "%Y-%m-%d",
   button      : "date_trigger",
   singleClick : false,
   step : 1
 });
 </script>\n};

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

    exit;
}



#------------------
sub showLessonPlans {
#------------------

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

    my $date = $arr{date};
    delete $arr{date};
    my $term = $arr{term};
    delete $arr{term};
    if ( not $term ) {
	print qq{<h3>Missing Term</h3>\n};
	print qq{</body></html>\n};
	exit;
    }
    # remaining values in %arr are teachers' userids.
    
    my (%teacher,%sort);
    
    my $sth = $dbh->prepare("select lastname, firstname from staff where userid = ?");

    
    foreach my $userid ( keys %arr ) {

	# 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
    foreach my $key ( sort keys %sort ) {
	my $userid = $sort{$key};

	# Display All Current Lesson Plans
	print qq{<h3>$teacher{$userid}</h3>\n};
	
	printLesson($userid,$date,$term );

	print qq{<div style="clear:both;"></div><hr>\n};

    }

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

    exit;

    
} # end of showLessonPlans


#-----------------
sub printLesson { # print Lesson for one teacher for 1 date.
#-----------------

    my ($userid, $date,$term ) = @_;

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

    # Find DayInCycle
    my $dayInCycle = findDayInCycle($date, $dbh);
    
    
    # Get Courses and Activities from dbktimetable for this dayInCycle
    my $sth = $dbh->prepare("select day, period, courseact from dbktimetable  
			    where term = ? and userid = ? and day = ? order by period");
    $sth->execute( $term, $userid, $dayInCycle );
    
    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 ) {
	print qq{<div>No Timetable - Cycle Day: $dayInCycle</div>\n};
	return;
    } # no timetable
    
    my $sth = $dbh->prepare("select description from subject where subjsec = ?");
    my $sth1 = $dbh->prepare("select title from dbkactivity where id = ?");

    # get subjsec, topic, notes
    my $sth2 = $dbh->prepare("select topic,notes from dbkdata 
			     where userid = ? and date = ? and period = ?");
    
    
    # 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="text-align:left;font-size:120%;font-weight:bold;">};
    print qq{$date</caption>};
#    print qq{$lex{Term} $term </caption>\n};

    print qq{<tr><th></th>}; # for period column

    my $day = $dayInCycle;
    print qq{<th>$lex{Day} $day</th>};
    print qq{<th>Lesson Plan</th></tr>\n};
    
    # Main body of table.
    for $period (1..$maxperiod){
	print qq{<tr><td>$lex{Per} $period</td>};
	    
	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 ); # course code
		    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
		    $desc = $sth->fetchrow;
		    $desc .= qq{<br>($crsact)};
		}
			
		print qq{$desc<br>\n};
	    }
	    print qq{</td>};

	    # Get any planning done (topic, notes)
	    $sth2->execute( $userid, $date, $period );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    my ($topic,$notes) = $sth2->fetchrow;
	    print qq{<td><b>$topic</b> $notes</td></tr>\n};
	    
	} else {
	    print qq{<td colspan="2" style="color:green;">$lex{'No Value'}</td>};
	}

	print qq{</tr>\n};
    }

    print qq{</table>\n};

    return;

}
