#!/usr/bin/perl
#  Copyright 2001-2024 Leslie Richardson / Michael Peters

#  This file is part of Open Admin for Schools.

# Display the Timetables for Grades and Terms; select from timetable. Display locations


my $self = 'tt_report4.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',
	   'Location' => 'Location',
	   
	   );

$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} 4 - Course Locations";

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 ) {
    delete $arr{page};
    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 ) {  # All 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 ) {
	    $terms{$trm} = 1;
	}
    }


    my @grades = split(/\s+/, $arr{grades} );
    if ( not @grades ) {  # all grades.
	my $sth = $dbh->prepare("select distinct grade from student where grade is not NULL and grade != ''");
	$sth->execute;
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	while ( my $grd = $sth->fetchrow ) {
	    push @grades, $grd;
	}

	#	print qq{<h3>$lex{Grades} $lex{'Not Found'}</h3>\n};
	#	print qq{</body></html>\n};
	#	exit;
    }

    @grades = sort {$a <=> $b} @grades;

#    print "Grades:@grades Terms:", %terms, "<br>\n";


    # Get all of the locations / rooms
    my (@loctot, %loctot); # total locations in the school
    my $sth = $dbh->prepare("select distinct location from subject where location is not NULL and location != ''");
    $sth->execute;
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $loc = $sth->fetchrow ) {
	$loctot{$loc} = 1;
    }
    @loctot = sort keys %loctot;

        
    # 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 grades for 1 term (grade split option? - separate tables for each).
#-----------------

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

    # Make them look better, create array.
    my @grades = split(/\s+/, $grades); # split on spaces.
    $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;"> $subjsec };
                        print qq{ (<b>$course{$subjsec}{location}</b>) $course{$subjsec}{teacher}</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" style="border:1px solid gray;padding:0.5em;">\n};


    # Terms
    print qq{<tr><td class="bra" style="vertical-align:top;">$lex{Select} $lex{Terms}<br>};
    print qq{<span style="font-weight:normal;">(Blank=All)</span></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" style="vertical-align:top;">$lex{Grades}</td>\n};
    print qq{<td><input type="text" name="grades" size="12"><br>};
    print qq{Separate with Spaces (Blank=All)</td></tr>\n};

    print qq{<tr><td colspan="2"></td></tr>\n};
    
    # Sort Order
    print qq{<tr><td class="bra">$lex{'Sort by'}</td>\n};
    print qq{<td><select name="sort">\n};
    print qq{<option value="loc">$lex{Location}</option>};
    print qq{<option value="grade">$lex{Grade}</option>};
    print qq{<option value="desc">Course $lex{Description}</option>};
    print qq{</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;

}

