#!/usr/bin/perl
#  Copyright 2001-2023 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 the Timetables for Grades and Terms; select from timetable.


my $self = 'tt_report3.pl';

my %lex = ('View' => 'View',
	   'Main' => 'Main',
	   'Timetable' => 'Timetable',
	   'No Records Found' => 'No Records Found',
	   'Grade' => 'Grade',
	   'Term' => 'Term',
	   'Delete Entries' => 'Delete Entries',
	   'No Value' => 'No Value',
	   'Period' => 'Period',
	   'Day' => 'Day',
	   'Term' => 'Term',
	   'Error' => 'Error',
	   'Course' => 'Course',
	   'Missing' => 'Missing',
	   'Enrollments' => 'Enrollments',
	   'Report' => 'Report',

	   'Grades' => 'Grades',
	   'Terms' => 'Terms',
	   'Not Found' => 'Not Found',
	   'Description' => 'Description',
	   'Sort by' => 'Sort by',
	   'Select' => 'Select',
	   'Continue' => 'Continue',
	   
	   );

$novalue = qq{<td></td>};
#$novalue = qq{<td style="color:red;">$lex{'No Value'}</td>}; # value for an empty cell in the report

use DBI;
use CGI;
use Cwd;

# 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 $q = new CGI;
print $q->header( -charset, $charset );
my %arr = $q->Vars;

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

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



# print page header.
my $title = "$lex{Timetable} $lex{Report} 3";

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{<h1>$title</h1>\n};




if (not $arr{page} ) {
    showStartPage();
    
} elsif ($arr{page} == 1 ) {
    showReport();
}


#-------------
sub showReport {
#-------------

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

    
    print qq{<div style="clear:both;margin-bottom:1em;"></div>\n};

    # Get the terms.
    my %terms;
    foreach my $key ( keys %arr ) {
	my ($type,$val) = split(':', $key);
	if ( $type eq 'term' ) {
	    $terms{$val} = 1;
	}
    }

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


    my @grades = split(/\s+/, $arr{grades} );
    if ( not @grades ) {
	print qq{<h3>$lex{Grades} $lex{'Not Found'}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }
    
    # Get all courses in grades;
    my %courses;
    my $sth = $dbh->prepare("select * from subject where grade = ?");
    my $sth1 = $dbh->prepare("select count(*) from eval where subjcode = ?");
    
    foreach my $grade ( @grades ) {
	$sth->execute($grade);
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	while ( my $ref = $sth->fetchrow_hashref ) {
	    $courses{$ref->{subjsec}} = $ref;

	    # Get course enrollment record count
	    $sth1->execute($ref->{subjcode});
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    my $count = $sth1->fetchrow;
	    $ref->{count} = $count;
	}
    }

    my $first = 1;
    foreach my $term ( sort keys %terms ) {
	if ( not $first ) {
	    print qq{<div style="page-break-after:always;"></div>\n};
	} else { $first = 0; }

	printTimetable( $term, \%courses, $arr{sort}, $arr{grades});

    }

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

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

    exit;
    
} # end of showReport



#-----------------
sub printTimetable { # print timetable for 1 grade for 1 term.
#-----------------

    my ($term, $courseref, $sort, $grades) = @_;
    my %course = %$courseref;
#    print "Term:$term Sort:$sort<br>\n";
#    print "Course:", %course, "<br>\n";

    # Make them look better.
    my @grades = split(/\s+/, $grades);
    $grades = join(',', @grades);


    
    my (%tb, $rows, $cols );  # %tb{period}{$day}{$subjsec} = 1;
 
    my $sth = $dbh->prepare("select day,period from schedat where term = ? and subjsec = ? 
			    order by period, day");

    foreach my $subjsec ( keys %course ) {

#	print "Subjsec:$subjsec<br>\n";
	
	# Get Timetable values
	$sth->execute( $term, $subjsec );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr;}
	while ( my ($day,$period) = $sth->fetchrow ) {
	    if ( not $day or not $period ) { next; }

#	    print "S:$subjsec D:$day P:$period<br>\n";
	    if ( $period > $rows ) { $rows = $period; }
	    if ( $day > $cols ) { $cols = $day; }
	    $tb{$period}{$day}{$subjsec} = 1;
	}
    }

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

	# heading
	print qq{<tr><th></th>};
	for my $day ( 1 .. $cols ){ print qq{<th>$lex{Day} $day</th>}; }
	print qq{</tr>\n};
    
	# Main body of table.
	for my $i ( 1 .. $rows ) {
	    print qq{<tr><td class="cn" style="vertical-align:top;">$lex{Period} $i</td>};
	    for my $j ( 1 .. $cols ) {
		if ( $tb{$i}{$j} ){ # if we have at least one course.

		    my $first = 1;
		    my %cellcourses = %{ $tb{$i}{$j} };  # for this day / period only.
#		    print "CELL courses", %cellcourses, "<br>\n";
		    my %sort;

		    if ( $sort eq 'desc' ) {
			foreach my $subjsec ( keys %cellcourses ) {
			    my $desc = $course{$subjsec}{description};
			    $sort{"$desc$subjsec"} = $subjsec;
			}
		    } else { # sort by grade, then description.
			foreach my $subjsec ( keys %cellcourses ) {
			    my $desc = $course{$subjsec}{description};
			    my $grade = $course{$subjsec}{grade};
			    if ( length $grade == 1 ) { $grade = '0'. $grade; } 
			    $sort{"$grade$desc$subjsec"} = $subjsec;
			}
		    }
			
		    print qq{\n<td style="vertical-align:top;">};

		    my $color = 'white';
		    my ($currgrade, $prevgrade);
		    
		    if ( $sort eq 'grade' ) {
			$color = '#EEE';
		    }

		    
		    foreach my $key ( sort keys %sort ) {
			my $subjsec = $sort{$key};
			my $grade = $course{$subjsec}{grade};
			if ( not $currgrade ) { $currgrade = $grade; }

			$prevgrade = $currgrade;
			$currgrade = $grade;
			if ( $currgrade ne $prevgrade and $sort eq 'grade') {
			    if ( $color eq '#EEE' ) { $color = '#CCC'; } else { $color = '#EEE'; }
			}
			
			
			print qq{<div style="background-color:$color;">$course{$subjsec}{description}};
			print qq{ ($subjsec)</div>};
		    }
		    print qq{</td>};

		} else {
		    print $novalue;  # Empty; cell values set at top of script.
		}
	    }
	    print qq{</tr>\n};
	}
	print qq{</table>\n};

    } else { # no data
	print qq{<div style="clear:both;font-weight:bold;">};
	print qq{$lex{Term} $term - $lex{'No Records Found'}</div>\n};
    }

    return;

} # End of printTimetable





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


    # Find the terms in the timetable
    my @terms;
    my $sth = $dbh->prepare("select distinct term from schedat 
      where term is not NULL and term != '' order by term");
    $sth->execute;
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $trm = $sth->fetchrow ) {
	push @terms, $trm;
    }

    
    # Start Form
    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">\n};


    # Terms
    print qq{<tr><td class="bra" style="vertical-align:top;">$lex{Select} $lex{Terms}</td>\n};
    print qq{<td>};
    foreach $term ( @terms ) {
	print qq{<input type="checkbox" name="term:$term" value="1">Term $term<br>\n};
    }
    print qq{</td></tr>\n};


    # Grades
    print qq{<tr><td class="bra">$lex{Grades}</td>\n};
    print qq{<td><input type="text" name="grades" size="12"> Separate with Spaces</td></tr>\n};

    
    # Sort Order
    print qq{<tr><td class="bra">$lex{'Sort by'}</td>\n};
    print qq{<td><select name="sort"><option value="desc">$lex{Description}</option>};
    print qq{<option value="grade">$lex{Grade}</option></select></td></tr>\n};

    

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

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

    exit;

}

