#!/usr/bin/perl
#  Copyright 2001-2019 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',
	   'Contact' => 'Contact',
	   'Error' => 'Error',
	   'Fraction' => 'Fraction',
	   'Closed' => 'Closed',
	   'Record Stored' => 'Record Stored',
	   'School Closed' => 'School Closed',
	   'Record' => 'Record',
	   'Exists' => 'Exists',
	   'Continue' => 'Continue',
	   'Periods' => 'Periods',

	   );

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

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);
$dbh->{mysql_enable_utf8} = 1;

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

    # Fraction Closed
    print qq{<tr><td class="bra">$lex{Fraction} $lex{Closed}</td>\n};
    print qq{<td class="la"><input type="text" Name="dayfraction" size="6" value="1.000">\n};
    print qq{</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 (instead of every other year as default)
    });
   </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;    

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


    # Get Attendance Periods.
    my %ppdData;
    foreach my $grade (keys %g_ppd ) {
	my $periods = $g_ppd{$grade};
	$ppdData{$periods}{$grade} = 1;
    }

=head    
    # my $trackcount = keys %ppdData;
    # print "Track Count: $trackcount<br>\n";
    foreach my $p ( keys %ppdData ) {
	print "Period:$p - ";
	foreach my $gr ( keys %{ $ppdData{$p} } ) {
	    print "$gr ";
	}
	print "<br>\n";
    }
=cut    

    my %periodgroup; # grade group with minimum and max for each attendance periods.
    foreach my $p ( keys %ppdData ) {
	@gr = sort {$a <=> $b} keys %{ $ppdData{$p} };
	if ($ppdData{$p}{PK}) { $gr[0] = 'PK'; }; # since a K value will show instead.
	$val = "$gr[0]-$gr[-1]";
#	print "P:$p VAL:$val<br>\n";
	$periodgroup{$p} = $val;
    }

#    foreach my $p ( sort keys %periodgroup ) {
#	print "Periods:$p Group:$periodgroup{$p}<br>\n";
#    }
    
    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" 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" 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>$lex{No}</option>};
	print qq{<option>$lex{Yes}</option></select></td></tr>\n};

	# Fraction Closed
	print qq{<tr><td class="bra">$lex{Fraction} $lex{Closed}</td>\n};
	print qq{<td class="la"><input type="text" Name="$count:dayfraction" size="6" value="$arr{dayfraction}">\n};
	print qq{</td></tr>\n};

	# Periods Closed
	print qq{<tr><td class="bra">$lex{Periods} $lex{Closed}</td><td>(if less than full day closed)</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}; }
#    exit;

    # Add Any Periods to dates_periods
    foreach my $key ( keys %arr ) {
	my ($count, $field, $period ) = split(':', $key );
#	print "Count:$count Field:$field Period:$period<br>\n";
	
	if ( $period ) { # we have a period closed

#	    print "Period:$period<br>\n";
	    
	    # check for a partial day fraction closed;
	    if ( $arr{"$count:dayfraction"} > 0.99 ) { # skip
		next;
	    }

	    
	    # add a record and delete from hash.
	    # $field contains the grade group.
	    my $date = $arr{"$count:date"};

	    # Check for existing record
	    my $sth = $dbh->prepare("select count(*) from dates_periods 
              where date = ? and grades = ? and period = ?");
	    $sth->execute( $date, $field, $period );
	    if ($DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my $count = $sth->fetchrow;
	    if ( $count ) { # Error, notify
		print qq{<h3 style="color:red;">};
		print qq{$lex{Error}: Period Closed $lex{Record} $lex{Exists}:};
		print qq{Date $date Grades $field Period $period</h3>\n};
		
	    } else { # Add the record
		my $sth = $dbh->prepare("insert into dates_periods (date,grades,period) values(?,?,?)");
		$sth->execute( $date, $field, $period );
		if ($DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    }

	    delete $arr{$key};
	}
	    
    }

     
    foreach my $key ( keys %arr ) {
	my ($count, $field ) = split(':', $key );

	# skip any fields but a date field.
	if ( $field ne 'date' ) { next; }

	my $date = $arr{$key};
	
	# Check for existing record with same date.
	my $sth = $dbh->prepare("select count(*) from dates where date = ?");
	$sth->execute( $date );
	if ($DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my $dupcount = $sth->fetchrow;
	if ( $dupcount ) {
	    print qq{<h3 style="color:red;">$lex{Error}: $lex{Record} $lex{Exists}: $arr{date}</h3>\n};
	    next;
	}
	
	my %data; # create other keys and check for any blanks.
	$data{dayfraction} = $arr{"$count:dayfraction"};
	$data{dayincycle} = $arr{"$count:dayincycle"};
	$data{desc1} = $arr{"$count:desc1"};
	$data{type} = $arr{"$count:type"};

	my $missingflag;
	foreach my $dkey (keys %data ) {
	    if ( not $data{$dkey} ) {
		print qq{<div>Missing Value for $key in Date <b>$date</b></div>\n};
		$missingflag = 1;
	    }
	}
	if ( $missingflag ) {
	    # delete the date flag hash entry, don't worry about the others.
	    delete $arr{$key}; # the date field in a count set.
	    next;
	}
	
	# Convert dayincycle to Yes = 1, No = 0 format.
	if ( $data{dayincycle} eq $lex{Yes} ) {
	    $data{dayincycle} = '1';
	} else {
	    $data{dayincycle} = '0';
	}

	# insert the record
	my $sth = $dbh->prepare("insert into dates (date, type, desc1, dayincycle, dayfraction )
           values ( ?, ?, ?, ?, ? )");
	if ($DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	$sth->execute( $date, $data{type}, $data{desc1}, $data{dayincycle}, $data{dayfraction});
	if ( not $DBI::errstr ) {
	    print qq{<h3>$lex{'Record Stored'}<br>};
	    print qq{Date:$date Type:$data{type}  Desc:$data{desc1} DayInCycle:$data{dayincycle} }; 
	    print qq{ Fraction Closed:$data{dayfraction}</h3>\n};

	} else {
	    print qq{<h3>$lex{Error}: $DBI::errstr</h3>\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;

}



#------------
sub checkDate {
#------------

    use Time::JulianDay;
    
    my $date = shift;

    my ($y,$m,$d) = split('-',$date);
    
    if ( not $d ) { return 255; }  # wrong format.
    if ( $m > 12 or $m < 1 ) { return 255; }
    if ( $d > 31 or $d < 1 ) { return 255; }

    my $datejd = julian_day( $y, $m, $d );

    my $startjd = julian_day( split('-', $schoolstart ));
    my $endjd = julian_day( split('-', $schoolend ));
    
#    print "DATE:$date - $datejd Start:$schoolstart - $startjd  End:$schoolend - $endjd<br>\n";

    if ( $datejd > $endjd  or $datejd < $startjd ) {
	return 1; # different code for date outside of current year;
    }
    
    return 0;

}
