#!/usr/bin/perl
#  Copyright 2001-2020 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.

my %lex = ('Main' => 'Main',
	   'Grade' => 'Grade',
	   'Not Found' => 'Not Found',
	   'Error' => 'Error',
	   'Continue' => 'Continue',
	   'Month' => 'Month',
	   'Non-School Days' => 'Non-School Days',
	   'View' => 'View',
	   'Select' => 'Select',
	   'Part of Day' => 'Part of Day',
	   'Update' => 'Update',
	   'Updated' => 'Updated',
	   'Deleted' => 'Deleted',
	   'Record' => 'Record',
	   'Added' => 'Added',
	   'Home Room' => 'Home Room',
	   'Missing' => 'Missing',
	   'Value' => 'Value',
	   
	   );

use DBI;
use CGI;
use CGI::Session;
use Time::JulianDay;
use Number::Format qw(:all);
use Cwd;

my @colors = ('#99D','#9D9','#D99', '#AAE','#ADA','#DAA','#AA8','#A8A',
	      '#9AA','#AAF','#AFA','#FAA','#866','#896','#878', '#DAD',
	      '#DDF', '#DFA', '#FFA','#FFC','#FFE','#FDD','#FAD','#FDA',
	      '#F99', '#9F9', '#99F','#FBB'
    );


my $self = 'viewHomeroomsClosed.pl';

# Get current dir so know what path for config files.
my ($configpath, $teachermode );
if ( getcwd() =~ /tcgi/ ){ # we are in tcgi
    $teachermode = 1;
    $configpath = '..'; # go back one to get to etc.
} else {
    $configpath = '../..'; # go back two to get to etc.
}


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


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

# Load Configuration Variables;
my $sth = $dbh->prepare("select id, datavalue from conf_system where filename = 'admin'");
$sth->execute;
if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
while (	my ($id, $datavalue) = $sth->fetchrow ) {
    eval $datavalue;
    if ( $@ ) {
	print "$lex{Error}: $@<br>\n";
	die "$lex{Error}: $@\n";
    }
}

# Teachermode
if ( $teachermode ) { # running on teacher site
    $css = $tchcss;
    $homepage = $tchpage;
}


my $q = new CGI;
print $q->header(-charset, $charset ); 
my %arr = $q->Vars;

if ( $arr{nocolor} ) {
    @colors = ();
}


my $title = "$lex{View} Homerooms Closed";
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};
print qq{<meta HTTP-EQUIV="Pragma" CONTENT="no-cache">\n};
print qq{$chartype\n</head><body style="padding:1em 2em;">\n};

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

#foreach my $key ( sort keys %arr ) { print "K:$key V:$arr{$key}<br>\n"; }
# Values passed: page, date, and then any school databases;


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


#--------------
sub showDates {
#--------------

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

    if ( not $arr{month} ) {
	print qq{<h3>$lex{Missing} $lex{Value}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    
    my $month = $arr{month};
    my ($yr,$mo) = split('-', $arr{month});
    if ( length( $mo ) == 1 ) { $mo = '0'. $mo; }
    delete $arr{month};

    # Get Homerooms and assign color;
    my (%hroomcolor, %teacher);
    my $sth1 = $dbh->prepare("select lastname, firstname from staff s, staff_multi sm where 
       sm.userid = s.userid and sm.field_name = 'homeroom' and sm.field_value = ?");
    
    my $sth = $dbh->prepare("select distinct homeroom from dates_homeroom order by homeroom");
    $sth->execute;
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $homeroom = $sth->fetchrow ) {
	
	# get the teacher for this homeroom
	$sth1->execute( $homeroom );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my ($lastname, $firstname) = $sth1->fetchrow;
	$teacher{$homeroom} = "$firstname $lastname";

	# get a color for this room
	my $color = pop @colors;
	$hroomcolor{$homeroom} = $color;
    }
    
   
    # load any records for this month;
    my %dates;
    my $sth = $dbh->prepare("select * from  dates_homeroom 
      where month(date) = ? and  year(date) = ?");
    $sth->execute( $mo, $yr );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $ref = $sth->fetchrow_hashref ) {
	%r = %$ref;
	$dates{ $r{date} }{ $r{period} }{ $r{homeroom} } = $r{id};
    }

    if ( not %dates ) {
	print qq{<h3>No Records this month</h3>\n};
	print qq{</body></html>\n};
	exit;
    }
   
    
    # Find dow for first of the month
    my $startdate = "$yr-$mo-01";
    my $startjd = julian_day( split('-', $startdate) );
    my $startdow = day_of_week($startjd);

    # Find last day of the month (eomday)
    my $nextmonth = $mo + 1;
    my $tempyear = $yr;
    if ( $nextmonth == 1 ) { $tempyear++; }
    my $eomjd = julian_day($tempyear,$nextmonth,'1');
    my @temp = inverse_julian_day( $eomjd - 1 );
    my $eomday = $temp[2];

    # Set number of rows in the calendar
    my $rowcount = 5; # 5 rows in the calendar.
    my $totalcells = $eomday + $startdow; # total cells required in calendar.
    if ( $totalcells > 36 ) { $rowcount = 6; }  # to accomodate all the dates in the month.
    
#    print "End of Month:$eomday<br>\n";

    # Add Style settings for calendar
    print qq{<style>\n.caldate { font-size:140%;font-weight:bold; }</style>\n};

    
    # Get the days closed (>0.999) in the month.
    my %dayclosed;
    my $sth = $dbh->prepare("select date from dates 
      where month(date) = ? and  year(date) = ? and dayfraction > 0.999");
    $sth->execute( $mo, $yr );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $date = $sth->fetchrow ) {
	$dayclosed{$date} = 1;
    }


    # Print the homerooms with colors;
    print qq{<table style="border:1px solid gray;padding:0.4em;" border = "1" };
    print qq{cellspacing="0" cellpadding="3"><tr>\n};
    
    my $count;
    foreach my $homeroom ( sort keys %hroomcolor ) {
	print qq{<td style="background-color:$hroomcolor{$homeroom}; color:black;">};
	print qq{$homeroom - $teacher{$homeroom}</td>\n};
	$count++;
	if ( $count % 4  == 0 ) { print qq{</tr><tr>\n}; }
    }
    print qq{</tr></table><p></p>\n};

  
    # Calendar Table
    print qq{<table cellspacing="0" border="1" cellpadding="4" style="border:1px solid gray;">\n};
    print qq{<caption style="font-size:144%;font-weight:bold;">Homerooms Closed };
    print qq{- $month[$mo], $yr</caption>\n};

    
    # Days of the Week Header
    print qq{<tr>};
    foreach my $da (0..6) { # day 1 (Sunday) and 7 (Saturday) not used, of course.
	print qq{<th>$dow[$da + 1]</th>};
    }
    print qq{</tr>\n};

    my ($calday, $caldate); # set and updated through the month.
    foreach my $row (1..$rowcount) {
	print qq{<tr>};
	foreach my $col (0..6) {

	    # Set the starting calendar day
	    if ($row == 1 and $col == $startdow ) {
#		print qq{Row:$row  COL:$col StartDOW:$startdow<br>\n};
		$calday = 1; 
	    }
	    my $tempday = $calday;
	    if ( length $tempday == 1 ) { $tempday = '0'. $tempday; }
	    if ( $calday ) { $caldate = qq{$yr-$mo-$tempday}; }
	    
#	    print "CALDATE:$caldate<br>\n";
	    # NOTE: $calday is day of month 1..31; $caldate is a full date;

	    
	    if ( $col == 0 or $col == 6 or $dayclosed{$caldate} ) { # a weekend or closed
		print qq{<td style="background-color:#DDD;">};
		print qq{<span>$calday</span></td>\n};
		
	    } else { # a week day
		
		print qq{<td><span class="caldate">$calday</span><br>};
		if ( $calday ) {

		    foreach my $period ( sort keys %{ $dates{$caldate} } ) {
			my %dayper = %{ $dates{$caldate}{$period} };
			print qq{<b>P$period</b> };
			foreach  my $hr ( sort keys %dayper ) {
			    print qq{<span style="background-color:$hroomcolor{$hr};};
			    print qq{padding:0.1em 0.3em;">$hr</span>\n};
			}
			print qq{<br>\n};
		    }
		}

		print qq{</td>\n};
		
#		print qq{<br>R:$row C:$col</td>};
	    }
	    if ($calday) { $calday++; }
	    if ( $calday > $eomday ) { $calday = ''; $caldate = ''; }
	}
	print qq{</tr>\n};
    }
    
    print qq{</table>};
    print qq{</body></html>\n};

    exit;

}



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

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

    my @tim = localtime(time);
    my $cyear = @tim[5] + 1900;
    my $cmonth = @tim[4] + 1;
    if ( length $cmonth == 1 ) { $cmonth = '0'. $cmonth; }
    # my $cday = @tim[3];
    # my $currdate = "$cyear-$cmonth-$cday";
    # my $currjd = julian_day( split('-', $currdate) );
    my $curryrmo = "$cyear-$cmonth";

    
    # Setup Year-Months.
    my @months;
    my %months;

    my ($sy, $sm, $sd) = split('-', $schoolstart); # schoolstart is global var from config.
    if ( length $sm == 1 ) { $sm = '0'. $sm; }
    my $yrmo = "$sy-$sm";
    push @months, $yrmo;
    $months{$yrmo} = "$s_month[$sm]-$sy";

    for my $i (1..10) {
	my $mo = $sm + $i;
	my $yr = $sy;
	if ( $mo > 12 ) {
	    $mo = $mo - 12;
	    $yr++;
	}
	if ( length $mo == 1 ) { $mo = '0'. $mo; }
	my $yrmo = "$yr-$mo";
	push @months, $yrmo;
	$months{$yrmo} = "$s_month[$mo]-$yr";
    }

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

    print qq{<table cellspacing="4" border="0" cellpadding="3" style="margin:1em;};
    print qq{border:1px solid gray;float:left;">\n};

    print qq{<tr><td class="bla">$lex{Select} $lex{Month}</td>};
    print qq{<td><select name="month"><option value="$curryrmo">$months{$curryrmo}</option>\n};
    
    foreach my $mo ( @months ) {
	if ( $mo eq $curryrmo ) { next; }
	print qq{<option value="$mo">$months{$mo}</option>\n};
    }
    print qq{</select></td></tr>\n};

=head    
    # Load homerooms for PK and K, P3 grades.
    my %homerooms;
    my $sth = $dbh->prepare("select distinct homeroom from student 
      where grade = 'K' or grade = 'PK' or grade = 'P3'");
    $sth->execute;
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $hr = $sth->fetchrow ) {  # these will only be for that grade.
	$homerooms{$hr} = 1;
    }

    
    # Homeroom
    print qq{<tr><td class="bla">$lex{Select} $lex{'Home Room'}</td>};
    print qq{<td><select name="homeroom"><option></option>\n};
    foreach my $hr ( sort keys %homerooms ) {
	print qq{<option>$hr</option>\n};
    }
    print qq{</select></td></tr>\n};
    

    # Part of Day
#    print qq{<tr><th>$lex{Select} $lex{'Part of Day'}</th>};
#    print qq{<td><select name="dayfraction"><option value="both">Morning & Afternoon</option>\n};
#    print qq{<option value="1">Morning only closed</option><option value = "2">Afternoon only closed</option>};
#    print qq{</select></td></tr>\n};

=cut

    print qq{<tr><td class="bra">Show No Colors</td>};
    print qq{<td><input type="checkbox" name="nocolor" value="1"></td></tr>\n};

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

=head    
    # Load all NSD's
    my %dates;
    my $sth = $dbh->prepare("select * from  dates_homeroom");
    $sth->execute;
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $ref = $sth->fetchrow_hashref ) {  # these will only be for that homeroom
	my %r = %$ref;
	$dates{ $r{homeroom} }{ $r{date} }{ $r{period} } = 1;
    }

    
    # Now Display the current days set
    foreach my $homeroom ( keys %dates ) {
	
	# Start a Table for this homeroom
	print qq{<table cellspacing="4" border="0" cellpadding="3" };
	print qq{style="margin:1em;border:1px solid gray;float:left;">\n};
	print qq{<caption style="font-weight:bold;font-size:144%;">$lex{'Home Room'} $homeroom</caption>\n};
	print qq{<tr><th>$lex{Date}</th><th>AM/PM</th></tr>\n};

	foreach my $date ( sort keys %{ $dates{$homeroom}} ) {
	    my $daystring;
	    if ( $dates{$homeroom}{$date}{'1'} and $dates{$homeroom}{$date}{'2'} ) {
		$daystring = 'All Day';

	    } elsif ( $dates{$homeroom}{$date}{'1'} ) {
		$daystring = 'AM';

	    } elsif ( $dates{$homeroom}{$date}{'2'} ) {
		$daystring = 'PM';
	    }

	    my $jd = julian_day( split('-', $date));
	    my $dow = day_of_week( $jd );

	    print qq{<tr><td>$dow[$dow + 1], $date</td><td>$daystring</td></tr>\n};
	    
	}

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

    exit;

}
