#!/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',
	   'Set' => 'Set',
	   '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 $self = 'setNonSchoolDays.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;
#    $downloaddir = $tchdownloaddir;  # not needed in this script.
#    $webdownloaddir = $tchwebdownloaddir;
}


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

my %periodmap = (1 => 'AM', 2 => 'PM');


my $title = "$lex{Set} PK/K 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{<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};
    selectDates();
    
} elsif ( $arr{page} == 2 ) {
    delete $arr{page};
    updateDates();
}


#--------------
sub updateDates {
#--------------

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

    my $homeroom = $arr{homeroom};
    delete $arr{homeroom};

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

    print qq{<h3>$lex{'Home Room'} $homeroom</h3>\n};
    
    # load any records for this month for this homeroom, to check for values turned off (and to be deleted)
    my %dates;
    my $sth = $dbh->prepare("select * from  dates_homeroom 
      where month(date) = ? and  year(date) = ? and homeroom = ?");
    $sth->execute( $mo, $yr, $homeroom);
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $ref = $sth->fetchrow_hashref ) {  # these will only be for that grade.
	my %r = %$ref;
	$dates{$r{date}}{$r{period}} = $r{id};
    }

#    foreach my $date ( sort keys %dates) {
#	foreach my $period ( sort keys %{$dates{$date}} ) {
#	    print qq{Date:$date Period:$period ID:$dates{$date}{$period}<br>\n};
#	}
#    }


    # check for any deselected date, period values that should be deleted.
    my $sth = $dbh->prepare("delete from dates_homeroom where id = ?");
    my %params;
    foreach my $key ( keys %arr ) {
	my ($date, $period) = split(':', $key);
	$params{$date}{$period} = 1;
    }
    
    # go through current records for this month, this homeroom, and
    # remove any extras not passed as parameters.
    foreach my $date ( sort keys %dates ) { 
	foreach my $period ( sort keys %{ $dates{$date} } ) {
	    if ( not $params{$date}{$period} ) {
		my $id = $dates{$date}{$period};
#		print "ID:$id Date:$date Period:$period<br>\n";
		$sth->execute( $id );
		if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
		print qq{<div>$lex{Record} <b>$lex{Deleted}</b> $date - $periodmap{$period}</div>\n};
	    }
	}
    }
    

    # Insert any New records
    my $sth = $dbh->prepare("insert into dates_homeroom ( date, period, homeroom ) values (?,?, '$homeroom')");
    
    foreach my $key ( sort keys %arr ) {
	my ($date, $period) = split(':', $key);

	if ( not $dates{$date}{$period} ) { # if doesn't exist, add the record.
#	    print "Date:$date Period:$period<br>DATA:$dates{$date}{$period}<br>\n";
	    $sth->execute( $date, $period);
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    print qq{<div>$lex{Record} <b>$lex{Added}</b> $date - $periodmap{$period}</div>\n};
	    
	}
    }

    print qq{<h3>$lex{'Non-School Days'} $lex{Updated}</h3>\n};
    
    print qq{</body></html>\n};

    exit;

}



#--------------
sub selectDates {
#--------------

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

    if ( not $arr{homeroom} or 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};

    my $homeroom = $arr{homeroom};
    delete $arr{homeroom};

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

    # 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;
    }
    
     
    
    # Start Form
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="2">\n};
    print qq{<input type="hidden" name="homeroom" value="$homeroom">\n};
    print qq{<input type="hidden" name="month" value="$month">\n};
    
    print qq{<h3>$lex{'Home Room'} $homeroom</h3>\n};

    
    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;">$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 $checked = qq{checked="checked"};
    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";
	    
	    if ( $col == 0 or $col == 6 or $dayclosed{$caldate} ) {
		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 ) {
		    my $chk;
		    if ( $dates{$caldate}{'1'} ) { $chk = $checked; }
		    print qq{<input type="checkbox" name="$caldate:1" value="1" $chk>AM<br>};
		    if ( $dates{$caldate}{'2'} ) { $chk = $checked; } else { $chk = ''; }
		    print qq{<input type="checkbox" name="$caldate:2" value="1" $chk>PM};
		    
		}
		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{<p><input type="submit" value="$lex{Update} $lex{'Non-School Days'}"></p>\n};
    print qq{</form>\n};
    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;
    # 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.
    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++;
	}
	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};


    # 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' ) and homeroom is not NULL");
    $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;
    }

#    foreach my $hr (keys %homerooms ) {
#	print qq{<div>HR: $hr</div>\n};
#    }

    
    # 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};
    
    print qq{<tr><td></td><td><input type="submit" value="$lex{Continue}"></td></tr>\n};
    print qq{</table></form>\n};

    print qq{<br clear="left">\n};
    
    # Load all Homerooms closed
    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;
    }

   
    
    my $count;    
    # Now Display the current days set
    foreach my $homeroom ( sort 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'} };
	print qq{$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};

	$count++;
	if ( $count % 3 == 0 ) { print qq{<br clear="left">\n}; }
	
    }
       

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

    exit;

}
