#!/usr/bin/perl
#  Copyright 2001-2022 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; version 2 of 
#  the License, only.


my %lex = ('Term' => 'Term',
	   'Student' => 'Student',
	   'Timetable' => 'Timetable',
	   'Continue' => 'Continue',
	   'Please Log In' => 'Please Log In',
	   'Period' => 'Period',
	   'Day' => 'Day',
	   'No Value' => '',
	   'Select' => 'Select',
	   'Terms' => 'Terms',
	   'Error' => 'Error',

	   );


my $self = 'ptimetableview.pl';


use DBI;
use CGI;
use CGI::Session;


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

# Michael's Override
# $arr{page} = 1;
# $arr{1} = 1;


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


# Add period times, remove soon!
eval require "../etc/schedule.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;

# Get Session
my $session = new CGI::Session("driver:mysql;serializer:FreezeThaw",
 undef,{Handle => $dbh}) or die CGI::Session->errstr;

if ( not $session->param('logged_in') ){
    # my $userid = $session->param('userid');
    print $session->header( -charset, $charset );
    print qq{$doctype\n<html><head><title>$title</title>\n};
    print qq{<meta name="viewport" content="width=device-width, initial-scale=1.0">\n};
    print qq{<link rel="stylesheet" href="$parcss" type="text/css">\n};
    print qq{$chartype\n</head><body>\n};
    print qq{[ <a href="$parpage">Parent Home Page</a> ]\n};
    
    print qq{<h3>$lex{'Please Log In'}</h3>};

    print qq{<form action="plogin.pl" method="post">\n};
    print qq{<input type="submit" value="Log In">\n};
    print qq{</form>\n};
    
    print qq{</body></html>\n};
    exit;
}

# Ok, we have a login. Values below we have in environment.
$userid = $session->param('userid');
# Reset duration.
$duration = $session->param('duration');
$session->expire('logged_in', $duration );

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


# Print HTML Page Header....
my $title = "$lex{Student} $lex{Timetable}";
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<meta name="viewport" content="width=device-width, initial-scale=1.0">\n};
print qq{<link rel="stylesheet" href="$parcss" type="text/css">\n};
print qq{$chartype\n</head><body>\n};

print qq{[ <a href="$parpage">Parent Home Page</a> ]\n};
print qq{<h1>$title</h1>\n};

# Get Student Name, Grade
my $sth = $dbh->prepare("select lastname, firstname, grade from studentall where studnum = ?");
$sth->execute($userid);
if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
my ($lastname, $firstname, $grade) = $sth->fetchrow;

print qq{<h3>$firstname $lastname ($userid) $lex{Timetable}</h3>\n};


# Get Term Display Mapping
my %termmap;
my $track = $g_MTrackTermType{$grade};
my $ref = $g_TermDisplay{$track};
foreach my $trm ( keys %{$ref} ) {
    $termmap{$trm} = $ref->{$trm};
}



# Get Student Enrollments
my @subjects;
my $sth = $dbh->prepare("select distinct subjcode from eval where studnum = ? 
  and subjcode is not NULL and subjcode != ''");
$sth->execute( $userid );
if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr;}
while ( my $subjcode = $sth->fetchrow ) {
    push @subjects, $subjcode;
}


# Get Course Info ( start,end term, description, teacher(userid) )
my %subjects;
$sth = $dbh->prepare("select description, smdesc, startrptperiod, endrptperiod, teacher
 from subject where subjsec = ?");
foreach my $subjsec ( @subjects ) {
    $sth->execute( $subjsec );
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr;}
    while ( my $ref = $sth->fetchrow_hashref ) {
	$subjects{$subjsec} = $ref; # put values into hash;
    }
}


=head   
# Test View Data Structure
foreach my $subjsec ( sort keys %subjects ) {
    foreach my $key ( keys %{ $subjects{$subjsec} } ) {
	print qq{$subjsec - $key - $subjects{$subjsec}{$key}<br>\n};
    }
}
=cut


# Get Terms to do.
my %terms;
foreach my $subjsec ( sort keys %subjects ) {
    my $startterm = $subjects{$subjsec}->{startrptperiod};
    my $endterm = $subjects{$subjsec}->{endrptperiod};
    for my $trm ( $startterm .. $endterm ) {
	$terms{$trm} = 1;
    }
}


if (not $arr{page} ) {
    showStartPage(\%terms);
} 
delete $arr{page};

# Set Teacher names
my  %teacher;
my $sth = $dbh->prepare("select lastname, firstname, sal from staff where userid = ?");

foreach my $subjsec ( keys %subjects ) {
    my $userid = $subjects{$subjsec}->{teacher};
    $sth->execute($userid);
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    my ($lastname, $firstname, $sal) = $sth->fetchrow;
    $teacher{$subjsec} = "$sal $firstname $lastname";
    # print qq{$subjsec - $teacher{$subjsec}<br>\n};
}


foreach my $term ( sort { $a <=> $b } keys %arr ) {
    # Print Each Term in turn.
    printTimetable($userid, $term, \@subjects );
}

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




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

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

    my @subject;
    my ($tblcols, $tblrows); # not globals anymore
    my $sth = $dbh->prepare("select day, period from schedat 
     where term = ? and subjsec = ? order by period, day");

    foreach my $subjsec ( @{$subjref} ) {

	$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 = ?");

    # print heading
    print qq{<div style="font-weight:bold;font-size:120%;text-align:left;padding:0.4em;">};
    print qq{$lex{Term} $term</div>\n};
    print qq{<table cellpadding="3" cellspacing="0" border="1">\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};

    
    # Main body of table.
    for $i (1..$tblrows){
	print qq{<tr><td class="cn">$i<br>$ptime[$i]</td>};
	for (1..$tblcols){
	    if ($subject[$i][$_]){ # if we have a subjsec value;
		my $firstflag = 1;
		my @subjval = split(/\s/,$subject[$i][$_]);
		print q{<td style="vertical-align:top;">};
		foreach my $sv (@subjval){
		    if (not $firstflag){ print q{<br>};} else { $firstflag = 0;}

		    # Get subject info
		    $sth->execute($sv);
		    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
		    my ($desc, $location) = $sth->fetchrow;
		    print qq{<b>$desc</b> ($sv)\n};
		    if ( $location ) { print qq{<br>$location}; }
		    print qq{<br>$teacher{$sv}};
		}
		print q{</td>};
	    } else {
		print qq{<td style="color:green;">$lex{'No Value'}</td>};
	    }
	}
	print qq{</tr>\n};
    }
    print qq{</table>\n};

    return;

} # end of printTimetable (1 term)



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


    my $ref = shift;
    my %terms = %$ref;

    if ( not %terms ) {
	print qq{<h3>No Courses/Terms Found</h3>\n};
	print qq{</body></html>\n};
	exit;
    }
    
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};

    print qq{<table cellpadding="3" cellspacing="0" border="0" style="padding:1em;">\n};
    print qq{<tr><td>$lex{Select} $lex{Terms}</td></tr>\n};

    foreach my $term ( sort {$a <=> $b} keys %terms ) {
	my $termname = $termmap{$term};
	if ( not $termname ) { $termname = "$lex{Term} $term"; }
	print qq{<tr><td><input type="checkbox" name="$term" value="1"> $termname</td></tr>\n};
    }

    print qq{<tr><td><input type="submit" value="$lex{Continue}"></td></tr>\n};

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

    exit;

} # end of showStartPage
