#!/usr/bin/perl
#  Copyright 2001-2024 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',
	   'Set' => 'Set',
	   'Select' => 'Select',
	   'Update' => 'Update',
	   'Updated' => 'Updated',
	   'Deleted' => 'Deleted',
	   'Record' => 'Record',
	   'Added' => 'Added',
	   'Home Room' => 'Home Room',
	   'Missing' => 'Missing',
	   'Value' => 'Value',
	   'Homerooms' => 'Homerooms',
	   'Date' => 'Date',
	   'Homeroom' => 'Homeroom',
	   
	   );

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

my $self = 'setHomeroomsClosed.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";
if ( $@ ) {
    print $lex{Error}. ": $@<br>\n";
    die $lex{Error}. ": $@\n";
}


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


# 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} 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{<link rel="stylesheet" type="text/css" media="all" };
print qq{href="/js/calendar-blue.css" title="blue">\n};
print qq{<script type="text/javascript" src="/js/calendar.js"></script>\n};
print qq{<script type="text/javascript" src="/js/lang/calendar-en.js"></script>\n};
print qq{<script type="text/javascript" src="/js/calendar-setup.js"></script>\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};
    selectDates();
    
} elsif ( $arr{page} == 2 ) {
    delete $arr{page};
    updateDates();
    
} elsif ( $arr{page} == 3 ) {
    delete $arr{page};
    confirmDelete();

} elsif ( $arr{page} == 4 ) {
    delete $arr{page};
    deleteSingleDayRecs();
}

#----------------
sub confirmDelete {
#----------------

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

    my $jd = julian_day( split('-',$arr{date}));
    my $dow = day_of_week($jd);
    
    
    my $sth = $dbh->prepare("select * from  dates_homeroom where date = ? order by homeroom,period");
    $sth->execute( $arr{date} );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    my $first = 1;
    while ( my $ref = $sth->fetchrow_hashref ) {
	my %r = %$ref;

	if ( $first ) { # start table of records
	    print qq{<table cellspacing="0" border="1" cellpadding="4" };
	    print qq{style="border:1px solid gray;margin:1em">\n};
	    print qq{<caption style="font-size:144%;font-weight:bold;">};
	    print qq{Date to Delete  $dowstd[$dow], $arr{date}</caption>\n};
	    print qq{<tr><th>Homeroom</th><th>Period</th></tr>\n};
	    $first = 0;
	}

	print qq{<tr><td>$r{homeroom}</td><td class="cn">$r{period}</td></tr>\n};

    }

    if ( $first ) {
	print qq{<h3>No Records found for this date</h3>\n};
	print qq{</body></html>\n};
	exit;
    } else {
	print qq{</table>\n};
    }

    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="4">\n};
    print qq{<input type="hidden" name="date" value="$arr{date}">\n};
    print qq{<div><input type="submit" value="Delete these records"></div>\n};
    print qq{</form>\n};

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

}

#----------------------
sub deleteSingleDayRecs {
#----------------------

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

    my $sth = $dbh->prepare("delete from dates_homeroom where date = ?");
    $sth->execute( $arr{date} );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

    print qq{<h3>Records for $arr{date} Deleted</h3>\n};
    print qq{</body></html>\n};
    
    exit;

}


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

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


    my ($yr,$mo) = split('-', $arr{month} );
    delete $arr{month};

    my @homerooms = split(',',$arr{homerooms});  # comma separated list.
    delete $arr{homerooms};

    
    my %data; # more efficient that looping over %arr
    foreach my $key ( keys %arr ) {
	my ($hr,$date,$period) = split(':', $key);
	$data{$hr}{$date}{$period} = 1;
    }


    foreach my $hr ( @homerooms ) {
    
	# 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, $hr);
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	while ( my $ref = $sth->fetchrow_hashref ) {
	    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.
	# go through current records for this month, this homeroom, and
	# remove any extras not passed as parameters.
	
	my $sth = $dbh->prepare("delete from dates_homeroom where id = ?");
	foreach my $date ( sort keys %dates ) { 
	    foreach my $period ( sort keys %{ $dates{$date} } ) {
		if ( not $data{$hr}{$date}{$period} ) { # not passed.
		    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 style="margin:0.5em 0;">$lex{Record} <b>$lex{Deleted}</b> };
		    print qq{Room/Cohort:<b>$hr</b> $date - Period $period</div>\n};
		}
	    }
	}
    

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

		if ( not $dates{$date}{$period} ) { # if doesn't exist, add the record.
		    # print "Insert 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 style="margin:0.5em 0;">$lex{Record} <b>$lex{Added}</b> };
		    print qq{Room/Cohort:<b>$hr</b> $date - Period $period</div>\n};
		}
	    }
	} # Date Loop
	
    } # Homeroom Loop

    print qq{<h3>$lex{Homerooms} $lex{Updated}</h3>\n};

    print qq{<div>[ <a href="$self">Add/Edit More</a> | };
    print qq{<a href="viewHomeroomsClosed.pl">View Homerooms Closed</a> ]\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, periods

    if ( not $arr{month} or not $arr{periods} ) {
	print qq{<h3>$lex{Missing} $lex{Value}. Go Back to Previous Page</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 $periods = $arr{periods};
    delete $arr{periods};

    # any fields remaining are homerooms.
    my @homerooms = sort {$a <=> $b} keys %arr;

    if ( not @homerooms ) {
	print qq{<h3>$lex{Missing} $lex{Homeroom}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }
    
    # watch for colons in homeroom names
    foreach $hr ( @homerooms ) {
	if ( $hr =~ m/:/ ) {
	    print qq{<h3>Error in homeroom $hr. No colons allowed.</h3>\n};
	    print qq{</body></html>\n};
	    exit
	}
#	print qq{Homeroom: $hr<br>\n};
    }
   
    
    # 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;
    }
    
    my $homerooms = join(',',@homerooms);
    
    # 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="homerooms" value="$homerooms">\n};
    print qq{<input type="hidden" name="month" value="$month">\n};



    # ALL HOMEROOMS
    foreach my $homeroom ( @homerooms ) {

    
	# 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};
	}
  
    
#	print qq{<hr><h3>$lex{'Home Room'} $homeroom</h3>\n};
    
	print qq{<table cellspacing="0" border="1" cellpadding="4" };
	print qq{style="border:1px solid gray;margin:1em;float:left;">\n};
	print qq{<caption style="font-size:144%;font-weight:bold;">};
	print qq{Homeroom $homeroom - $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 ) {
			foreach my $period (1..$periods) {
			    my $chk;
			    if ( $dates{$caldate}{$period} ) { $chk = $checked; }
			    print qq{<input type="checkbox" name="$homeroom:$caldate:$period" };
			    print qq{value="1" $chk>$period<br>};
			}
		    }
		    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>};

    } # end of homerooms loop
	
    print qq{<br clear="left"><input type="submit" value="$lex{Update} Homerooms Closed"></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"; }

    # Form for Deleting records for a single day.
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="3">\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>Delete Closures for a Single Date };
    print qq{<input type="text" name="date" id="date" size="10">\n};
    print qq{<button type="reset" id="start_trigger">...</button>\n};
    print qq{<input type="submit" value="Continue"></td></tr>\n};
    print qq{</table></form><br clear="left">\n};
    
    print qq{<script type="text/javascript">
  Calendar.setup({
    inputField     :    "date", // id of the input field
    ifFormat       :    "%Y-%m-%d", // format of the input field
    button         :    "start_trigger", // trigger for the calendar (button ID)
    singleClick    :    false,        // double-click mode
    step           :    1             // show all years in drop-down boxes
    });
   </script>\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><th class="bla">$lex{Select} $lex{Month}</th>};
    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};


    my %homerooms; # cohorts
    my %allowedgrades = ('K' => 1, 'PK' => 1, 'P3' => 1); # only these 3 can set homeroom closed.
    my $sth = $dbh->prepare("select distinct homeroom from student
			    where homeroom is not NULL and homeroom != '' ");
    
    my $sth1 = $dbh->prepare("select distinct grade from student where homeroom = ?");
    
    $sth->execute;
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
HR:    while ( my $hr = $sth->fetchrow ) {  # these will only be for that grade.

	# Get Grade
	$sth1->execute($hr);
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	while (	my $gr = $sth1->fetchrow ) {
	    if ( not defined $allowedgrades{$gr} ) { next HR; }
	    # skip even if one in splitroom is not allowed
	}
	
	$homerooms{$hr} = 1;
    }

    if ( not %homerooms ) {
	print qq{<h3>No Homerooms/Cohorts Found. Required to do Cohorts</h3>\n};
	print qq{</body></html>\n};
	exit;
    }
    
    
    # Homeroom/Cohort
    print qq{<tr><th class="bla">$lex{Select} $lex{'Home Room'}/Cohort</th>};
    print qq{<td>}; #Don't pick too many at once!<br>\n};
    my $hrcount = 0;
    foreach my $hr ( sort keys %homerooms ) { #{ $a <=> $b }
	print qq{<input type="checkbox" name="$hr" value="1">$hr\n};
	$hrcount ++;
	if ($hrcount % 4 == 0 ) { print qq{<br>\n}; }
    }
    print qq{</td></tr>\n};
    

    # Periods
    print qq{<tr><th>$lex{Select} Number of Periods</th>};
    print qq{<td><select name="periods"><option></option>\n};
    foreach my $period ( 1..8 ) {
	print qq{<option>$period</option>};
    }
    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/Dates closed to display;
    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%;">};
	print qq{$lex{'Home Room'} $homeroom</caption>\n};
	print qq{<tr><th>$lex{Date}</th><th>Periods</th></tr>\n};

	foreach my $date ( sort keys %{ $dates{$homeroom}} ) {
	    my ($daystring,@periods, $closedstring );
	    foreach my $period ( sort keys %{ $dates{$homeroom}{$date} } ) {
		my $type = $dates{$homeroom}{$date}{$period};
		push @periods, $period;
	    }

	    $daystring = join(',',@periods);

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

	    print qq{<tr><td>$dowstd[$dow], $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;

}
