#!/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.

my %lex = ('Add' => 'Add',
	   'Eoy' => 'Eoy',
	   'Main' => 'Main',
	   'Type' => 'Type',
	   'Statutory Holiday' => 'Statutory Holiday',
	   'Inservice' => 'Inservice',
	   'Holiday' => 'Holiday',
	   'Other' => 'Other',
	   'Description' => 'Description',
	   'Day In Cycle' => 'Day In Cycle',
	   'No' => 'No',
	   'Yes' => 'Yes',
	   'Save' => 'Save',
	   'Date' => 'Date',
	   'Add Another' => 'Add Another',
	   'Error' => 'Error',
	   'Closed' => 'Closed',
	   'School Closed' => 'School Closed',
	   'Continue' => 'Continue',
	   'Periods' => 'Periods',
	   'School' => 'School',
	   
	   );

my $self = 'dateAdd.pl';

use DBI;
use CGI;

# Read Config variables
eval require "../../etc/admin.conf";
if ( $@ ) {
    print $lex{Error}. " $@<br>\n";
    die $lex{Error}. " $@\n";
}

# Library to provide grade groups based on g_ppd values. (ie. K-4)
eval require "../../lib/libDate.pl";
if ( $@ ) {
    print $lex{Error}. " $@<br>\n";
    die $lex{Error}. " $@\n";
}


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


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


my $title = "$lex{Add} $lex{Date} - $lex{'School Closed'}";
print qq{$doctype\n<html><head><title>$title</title>
<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{$chartype\n</head><body>\n};
print qq{[ <a href="$homepage">$lex{Main}</a> |\n};
print qq{<a href="$eoypage">$lex{Eoy}</a> ]\n};

print qq{<h1>$title</h1>\n};

if ( not $arr{page} ) {
    showStartPage();

} elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    editDates();
    
} elsif ( $arr{page} == 2 ) {
    delete $arr{page};
    writeDates();
}


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

    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};

    # Get the date
    print qq{<tr><td class="bra">$lex{Date}</td>\n};
    print qq{<td class="la"><input type="text" name="date" id="date" size="10">\n};
    print qq{<button type="reset" id="start_trigger">...</button></td></tr>\n};

    # Type
    print qq{<tr><td class="bra">$lex{Type}</td>\n};
    print qq{<td class="la"><select name="type"><option></option>\n};
    print qq{<option value="onlinelearning">Online Learning</option>};
    print qq{<option value="stathol">$lex{'Statutory Holiday'}</option>};
    print qq{<option value="inservice">$lex{Inservice}</option>\n};
    print qq{<option value="holiday">$lex{School} $lex{Holiday}</option>};
    print qq{<option value="other">$lex{Other}</option>\n};
    print qq{</select></td></tr>\n};

    # Description
    print qq{<tr><td class="bra">$lex{Description}</td>\n};
    print qq{<td class="la"><input type="text" name="desc1" size="30"></td></tr>\n};

    # Day In Cycle
    print qq{<tr><td class="bra">$lex{'Day In Cycle'}?</td>\n};
    print qq{<td class="la"><select name="dayincycle"><option>$lex{No}</option>};
    print qq{<option>$lex{Yes}</option></select></td></tr>\n};

    # Day Fraction Closed
    print qq{<tr><td class="bra">$lex{Closed} All Day</td>\n};
    print qq{<td class="la"><input type="checkbox" Name="dayfraction" size="6" value="1.000">\n};
    print qq{ for <b>All</b> Students</td></tr>\n};

#    print qq{<tr><td class="cn" colspan="2">Set Fraction Closed to Zero (0) if using Periods Closed };
#    print qq{on next page<br> };
#    print qq{OR using Homerooms (homeroom) for varying cohorts/homerooms</td></tr>\n};

    
    # Copy more than one date.
    print qq{<tr><td class="bra">Add Extra School Days in Sequence</td>\n};
    print qq{<td><select name="extradays">};
    foreach my $day (1..14) { print qq{<option>$day</option>\n}; }
    print qq{</select></td></tr>\n};


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

    print qq{</form>\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};

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

}


#-------------
sub editDates {
#-------------

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

    my $checkdayfraction;
    if ( $arr{dayfraction} ) {
	$checkdayfraction = qq{checked="checked"};
    }

    
    # Check Date format.
    my $err = checkDate( $arr{date} );
    if ( $err == 1 ) {
	print qq{<h3>$lex{Error}: Date Outside School Year: $arr{tdate}</h3>\n};
	print qq{</body></html>\n};
	exit;
	
    } elsif ( $err ) {
	print qq{<h3>Date Error. Must be in yyyy-mm-dd format</h3>\n};
	print qq{</body></html>\n};
	exit;
    }


    # Get Date and convert to jd, increment, 
    my $jd = julian_day( split( '-', $arr{date} ) );
    my $dow = day_of_week($jd);

    if ( $dow == 0 or $dow == 6 ) {
	print qq{<h3>Cannot add weekend dates closed. They are already considered to be closed</h3>\n};
	print qq{</body></html>\n};
	exit;
    }	

    my $gpref = getGradesPeriod(); # uses g_ppd values.
    my %periodgroup = %$gpref; # grade group with minimum and max for each attendance periods.
    # Key is periods, value is the groups of grades.
    
    my $counter = $arr{extradays};
    delete $arr{extradays};

    # Start Form
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="2">\n};

    print qq{<input type="submit" value="$lex{Save}">\n};
    print qq{<table cellpadding="3" cellspacing="0" border="0">\n};
    print qq{<tr><td colspan="2"><hr></td></tr>\n};
    
    foreach my $count (1..$counter) {

	my $date = join('-', inverse_julian_day($jd) );
	my $dow = day_of_week($jd);
	
	# Date
	print qq{<tr><td class="bra">$lex{Date}</td>\n};
	print qq{<td class="bla"><input type="text" name="$count:date" value="$date" };
	print qq{style="width:10ch;">\n};
	print qq{$dowstd[$dow]</td></tr>\n};

	# Type
	print qq{<tr><td class="bra">$lex{Type}</td>\n};
	print qq{<td class="la"><select name="$count:type"><option>$arr{type}</option>\n};
	print qq{<option>$lex{'Statutory Holiday'}</option><option>$lex{Inservice}</option>\n};
	print qq{<option>$lex{School} $lex{Holiday}</option><option>$lex{Other}</option>\n};
	print qq{</select></td></tr>\n};

	# Description
	print qq{<tr><td class="bra">$lex{Description}</td>\n};
	print qq{<td class="la"><input type="text" name="$count:desc1" size="30" };
	print qq{value="$arr{desc1}"></td></tr>\n};

	# Day In Cycle
	print qq{<tr><td class="bra">$lex{'Day In Cycle'}?</td>\n};
	print qq{<td class="la"><select name="$count:dayincycle"><option>$arr{dayincycle}</option>};
	if ( $arr{dayincycle} eq $lex{No} ) { 
	    print qq{<option>$lex{Yes}</option>};
	} else {
	    print qq{<option>$lex{No}</option>};
	}
	print qq{</select></td></tr>\n};
	
	# Closed All Day (or not) - Day Fraction
	print qq{<tr><td class="bra">$lex{Closed} All Day</td>\n};
	print qq{<td class="la"><input type="checkbox" Name="$count:dayfraction" size="6" };
	print qq{value="1.000" $checkdayfraction> for <b>All</b> Students</td></tr>\n};

	# Periods Closed
	print qq{<tr><td class="bra">$lex{Periods} $lex{Closed}</td>};
	print qq{<td>(if NOT checked above)</td></tr>\n};
	foreach my $periods ( sort keys %periodgroup ) {
	    my $group = $periodgroup{$periods};
	    print qq{<tr><td>Grades $group</td><td>};
	    foreach my $p ( 1.. $periods ) {
		print qq{<input type="checkbox" name="$count:$group:$p" value="1">P$p };
	    }
	    print qq{</td></tr>\n};
	}

	# spacer.
	print qq{<tr><td colspan="2"><hr></td></tr>\n};

	# Update Julian Day
	do {
	    $jd++;
	    $dow = day_of_week($jd);
	} until ($dow != 0 and $dow != 6 )
	
	
    }

    print qq{</table>};
    print qq{<input type="submit" value="$lex{Save}">\n};
    print qq{</form>\n};
    print qq{</body></html>\n};

    exit;
    
}


#-------------
sub writeDates {
#-------------

    # foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }
    # Passed: date, dayincycle,desc1,type, then grade groupings:Period

    
    my (%info,%grade);
    foreach my $key ( keys %arr ) {
	my ($count, $field, $period ) = split(':', $key );
	if ( $period ) { # this is a grade closed record;
	    $grade{$count}{$field}{$period} = 1;
	} else { # just a date closed record
	    $info{$count}{$field} = $arr{$key}; # value significant
	}
    }
    
=head
    # Show values in %info - goes into normal dates field.
    foreach my $count ( sort keys %info ) {
	foreach my $field ( sort keys %{ $info{$count} } ) {
	    print qq{INFO Count:$count Field:$field Value:$info{$count}{$field}<br>\n};
	}
    }

    # Show values in %grade
    foreach my $count ( sort keys %grade ) {
	foreach my $grade ( sort keys %{ $grade{$count} } ) {
	    foreach my $period ( sort keys %{ $grade{$count}{$grade}} ) {
		print qq{<div>GRADE Count:$count Grades:$grade Period:$period</div>\n};
	    }
	}
    }
=cut

    
Daycount:  foreach my $idx ( sort keys %info ) { # loop over all indexes. Called count above
	
	# Do error checking here for each record passed.
	# If we have closed all day but have grades values, mistake, skip
	if ( $info{$idx}{dayfraction} == 1 and %{ $grade{$idx}} ) {
#	    print "Partial Grades Inside:$idx - ", %grade, "<br>\n";
	    print qq{<h3>Error: Day closed all day but Partial Grades closed!</h3>\n};
	    print qq{<div>Skipping...</div>\n};
	    next; # idx
	}
	
	if ( not $info{$idx}{dayfraction} and not %{ $grade{$idx}} ) {
	    print qq{<h3>Error: NOT Day closed all day but No Grades closed!</h3>\n};
	    print qq{<div>Skipping...</div>\n};
	    next; # idx
	}

# Logicallly incorrect. If only one group of grades are closed all
# doesn't mean all grade groups are. So this test is wrong. Skip
=head	
	# Test if closed all day via periods closed, but not using dayfraction.
	if ( not $info{$idx}{dayfraction} and  %{ $grade{$idx}} ) {
	    # Get first grade / only grade
	    my ($start,$end) = split('-', $grades);
	    my $ppd = $g_ppd{$start};
	    my $periodcount;
	    foreach my $grades ( keys %{ $grade{$idx}} ) { # Key is 2-4 type;
	    
		# Get first grade / only grade
		my ($start,$end) = split('-', $grades);
		my $ppd = $g_ppd{$start};
		my $periodcount;
		
		foreach my $period ( sort keys %{ $grade{$idx}{$grades}} ) {
		    $periodcount++;
		}
	    	print "GR:$grades PPD:$ppd Count:$periodcount<br>\n";
		if ( $ppd == $periodcount ) {
		    print qq{<h3>Day $idx: Please close day by selecting closed all day</h3>\n};
		    next Daycount; # idx
		}
	    } # grades loop
	}
=cut
	
	
	if ( not $info{$idx}{dayfraction} ) { # no dayfraction passed if zero/null
	    $info{$idx}{dayfraction} = '0';
	}
	
	my %rec = %{ $info{$idx} };
	my $date = $rec{date};

	# check for existing dates record, skip if found.
	my $sth = $dbh->prepare("select count(*) from dates where date = ?");
	$sth->execute( $date );
	if ($DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my $datecheck = $sth->fetchrow;
	if ( $datecheck ) {
	    print qq{<h3>Error: Day Closed Record exists for this date - $date !</h3>\n};
	    print qq{<div>Skipping...</div>\n};
	    next; # idx
	}
	
	# Check for existing Grades error
	my $sth = $dbh->prepare("select count(*) from dates_periods where date = ?");
	$sth->execute( $date );
	if ($DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my $gradecheck = $sth->fetchrow;
	if ( $gradecheck ) {
	    print qq{<h3>Error: Grades Closed Record exists for this date - $date !</h3>\n};
	    print qq{<div>Skipping...</div>\n};
	    next; # idx
	}
		
	
	# Convert dayincycle to Yes = 1, No = 0 format.
	if ( $rec{dayincycle} eq $lex{Yes} ) {
	    $rec{dayincycle} = '1';
	} else {
	    $rec{dayincycle} = '0';
	}

	my (@fields,@values,@qst);
	foreach my $key ( keys %rec ) {
	    push @fields, $key;
	    push @values, $rec{$key};
	    push @qst, '?';
	}
	my $qst = join(',',@qst);
	my $fields = join(',',@fields);

	# insert the 'dates' table record
	my $sth = $dbh->prepare("insert into dates ( $fields ) values ( $qst )");
	if ($DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	$sth->execute( @values );
	if ($DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	print qq{<div>Date Record Added</div>\n};

	
	# if we have any grades closed, add record to dates_periods
	my $sth = $dbh->prepare("insert into dates_periods ( date, grades, period  ) values (?,?,?)");
	foreach my $grades ( keys %{ $grade{$idx} } ) {
	    foreach my $period ( keys %{ $grade{$idx}{$grades}} ) {
		$sth->execute( $date, $grades, $period );
		if ($DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
		print qq{<div>Period Closed Added $date / Grades $grades / Period $period</div>\n};
	    }
	}

	# print qq{<div><b>$date</b> record written</div>\n};
    }	
	

    print qq{<p>[ <a href="$eoypage">$lex{Eoy}</a> |\n};
    print qq{ <a href="$self">$lex{'Add Another'} $lex{Date}</a> ]\n};
    print qq{</p></body></html>\n};

    exit;

}
