#!/usr/bin/perl
#  Copyright 2001-2022 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 = ('Dates' => 'Dates',
	   'Eoy' => 'Eoy',
	   'Main' => 'Main',
	   'Date' => 'Date',
	   'Edit' => 'Edit',
	   'Delete' => 'Delete',
	   'Error' => 'Error',
	   'Not Found' => 'Not Found',
	   'Closed' => 'Closed',
	   'Type' => 'Type',
	   'Continue' => 'Continue',
	   'Save' => 'Save',
	   'Day In Cycle' => 'Day In Cycle',
	   'Statutory Holiday' => 'Statutory Holiday',
	   'Inservice' => 'Inservice',
	   'Holiday' => 'Holiday',
	   'Other' => 'Other',
	   'Description' => 'Description',
	   'No' => 'No',
	   'Yes' => 'Yes',
	   'Periods' => 'Periods',
	   'School' => 'School',
	   
	   );

use DBI;
use CGI;
use Time::JulianDay;

my $self = qq{dateDelEd.pl};


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

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



print qq{$doctype\n<html><head><title>$lex{Edit}/$lex{Delete} $lex{Dates}</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\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>$lex{Edit}/$lex{Delete} $lex{Dates}</h1>\n};


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

} elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    delEditDates();

} elsif ( $arr{page} == 2 ) {
    delete $arr{page};
    updateEdits();
}



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

    
    my $first = 1;
    
    my $sth = $dbh->prepare("select * from dates order by date");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

    # Start the Form.
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<input type="submit" value="$lex{Continue}">\n\n};

    my $count = 1;
    
    while ( my $ref = $sth->fetchrow_hashref ) {
	my %r = %$ref;
    	# $id, $date, $type, $desc1, dayincycle 

	# Find DOW;
	my $jd = julian_day( split('-', $r{date} ));
	my $dow = day_of_week( $jd );
	
	# Put in a text month value.
	my @dt = split('-', $r{date});
	$dt[1] = $s_month[$dt[1]];
	my $newdate = join('-', @dt);
	
	if ( $first ) { 
	    print qq{<table cellpadding="3" border="1" cellspacing="0">\n};
	    print qq{<tr><th>$lex{Date}</th><th>Week Day</th><th>$lex{Description}</th>};
	    print qq{<th>$lex{Type}</th>};
	    print qq{<th>Day in<br>Cycle</th><th>$lex{Closed}</th><th>Edit</th><th>Delete</th></tr>\n};
	    $first = 0;
	}

	my $dayfracString = 'All Day';
	if ( $r{dayfraction} eq '0.000' ) {
	    $dayfracString = '<b>Partial</b>';
	}

	my $dayincycle = $lex{No};
	if ( $r{dayincycle} == 1 ) {
	    $dayincycle = qq{<b>$lex{Yes}</b>};
	}
	
	print qq{<tr><td class="bla">$newdate</td><td>$dowstd[$dow]</td>};
	print qq{<td>$r{desc1}</td><td>$r{type}</td>};
	print qq{<td>$dayincycle</td><td>$dayfracString</td>\n};
	print qq{<td><input type="checkbox" name="edit:$r{id}" value="1">Edit</td>\n};

	print qq{<td><input type="checkbox" name="delete:$r{id}" value="1">Delete</td></tr>\n};

	$count++;
	if ( $count % 20 == 0 ) {
	    print qq{<tr><td colspan="7"><input type="submit" value="$lex{Continue}"></td></tr>\n};
	}
    }

    
    if ( $first ) {
	print qq{<h3>$lex{Dates} $lex{'Not Found'}</h3>\n};
    } else {
	print qq{</table>\n};
    }

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

}


#----------------
sub delEditDates {
#----------------

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

    # Delete any records to start
    my $sth = $dbh->prepare("delete from dates where id = ?");
    my $sth1 = $dbh->prepare("delete from dates_periods where date = ?");
    my $sth2 = $dbh->prepare("select date from dates where id = ?");
    
    # Delete any selected records
    foreach my $key ( keys %arr ) {
	my ($action, $id) = split(':', $key);
	if ( $action eq 'edit' ) { next; }

	# check for id
	if ( not $id ) {
	    print qq{<h3>Error: Record ID not found for deletion</h3>\n};
	    print qq{</body></html>\n};
	    exit;
	}
	
	# Get Date
	$sth2->execute( $id );
	if ($DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my $date = $sth2->fetchrow;
	if ( not $date ) { 
	    print qq{<h3>Error: Date not found for deletion</h3>\n};
	    print qq{</body></html>\n};
	    exit;
	}

	# Delete any periods for this date
	$sth1->execute( $date );
	if ($DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

	# Delete the main record
	$sth->execute( $id );
	if ($DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

	# Delete this entry from hash.
	delete $arr{$key}; 

	print qq{<h3>Date Closed record for $date deleted</h3>\n};

    }


    if ( not %arr ) { # end of any changes if only deletes.
	print qq{</body></html>\n};
	exit;
    }

    # Setup for Editing; Periods
    my $gpref = getGradesPeriod(); # uses g_ppd values.
    my %periodgroup = %$gpref; # grade group with minimum and max for each attendance periods.
    
    # Start Form for Edit
    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};

    my $sth = $dbh->prepare("select * from dates where id = ?" );
    my $sth1 = $dbh->prepare("select grades, period from dates_periods where date = ?");
	
    
    foreach my $key ( sort keys %arr ) {
			     
	my ($action, $id) = split(':', $key);

	if ( $action ne 'edit' ) {
	    print qq{<h3>Error: Edit action not found. Action is: $action</h3>\n};
	    print qq{</body></html>\n};
	    exit;
	}
			     
	# Load the main record and any period records
	$sth->execute( $id );
	if ($DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my $ref = $sth->fetchrow_hashref;
	my %r = %$ref;
	my $date = $r{date};
	my $jd = julian_day( split('-', $date));
			     
	# Load any Periods;
	my %periods;
	$sth1->execute( $date );
	if ($DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	while  ( my ( $grades, $period ) = $sth1->fetchrow ) {
	    $periods{$grades}{$period} = 1;
	}
	
	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="$id:date" };
	print qq{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="$id:type"><option>$r{type}</option>\n};
	print qq{<option value="onlinelearning">Online Learning</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="$id:desc1" size="30" };
	print qq{value="$r{desc1}"></td></tr>\n};

	# Day In Cycle
	# convert from 0/1 to No/Yes
	if ( $r{dayincycle} ) { $r{dayincycle} = $lex{Yes}; } else { $r{dayincycle} = $lex{No}; }
	print qq{<tr><td class="bra">$lex{'Day In Cycle'}?</td>\n};
	print qq{<td class="la"><select name="$id:dayincycle"><option>$r{dayincycle}</option>\n};
	print qq{<option>$lex{No}</option><option>$lex{Yes}</option></select></td></tr>\n};

	# Fraction Closed
	my $checkdayfraction;
	if ( $r{dayfraction} eq '1.000' ) { $checkdayfraction = qq{checked="checked"}; }
	print qq{<tr><td class="bra">$lex{Closed} All Day</td>\n};
	print qq{<td class="la"><input type="checkbox" Name="$id:dayfraction" };
	print qq{size="6" value="1.000" $checkdayfraction>\n};
	print qq{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 ) {
		my $checked;
		if ( $periods{$group}{$p} ) { # we have a record for this...
		    $checked = qq{checked="checked"};
		}
		print qq{<input type="checkbox" name="$id:$group:$p" value="1" $checked>P$p };
	    }
	    print qq{</td></tr>\n};
	}

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

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

    exit;
}
    


#--------------
sub updateEdits {
#--------------

    # foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }
    
    # Update Date Records
    my $sth1 = $dbh->prepare("update dates set dayfraction = '0' where id = ?");
    my @dates;
    foreach my $key ( sort keys %arr ) {
	my ($id, $field, $period ) = split(':', $key );
	if ( $period ) { # skip this record if we have 3 values
	    next;
	}

	# Capture Date
	if ( $field eq 'date' ) {
	    push @dates, "$arr{$key}:$id";

	    # Check for day fraction (since now a checkbox field) missing and delete value
	    my $dayfractionkey = qq{$id:dayfraction};
	    if ( not $arr{$dayfractionkey} ) { # it's been unchecked.
		$sth1->execute( $id );
		if ( $DBI::errstr ) {
		    print qq{<h3>Error Deleting Day Fraction! $DBI::errstr</h3>\n};
		}
	    }
	}
	
	# Convert dayincycle to Yes = 1, No = 0 format.
	if ( $field eq 'dayincycle' ) {
	    if ( $arr{$key} eq $lex{Yes} ) {
		$arr{$key} = '1';
	    } else {
		$arr{$key} = '0';
	    }
	}

	# update the record
	my $sth = $dbh->prepare("update dates set $field = ? where id = ?");
	$sth->execute( $arr{$key}, $id);
	if ( not $DBI::errstr ) {
	    print qq{<div>Updated $field to $arr{$key} RecId:$id</div>};
	} else {
	    print qq{<h3>$lex{Error}: $DBI::errstr</h3>\n};
	}

	delete $arr{$key};

    }

#    print "<div>Dates:</div>";
#    foreach my $date (@dates) { print qq{Date:$date<br>\n}; }


    # Now loop again and update dates_periods records
    my $sth = $dbh->prepare("select id, grades, period from dates_periods where date = ?");
    my $sth1 = $dbh->prepare("delete from dates_periods where date = ? and grades = ? and period = ?");
    my $sth2 = $dbh->prepare("insert into dates_periods (date,grades,period) values(?,?,?)");
    
    foreach my $key ( @dates ) {
	my ($date, $dateid) = split(':',$key);

	my %pdata;
	$sth->execute( $date );
	if ($DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	while ( my ($id, $grades,$period ) = $sth->fetchrow ) {
	    $pdata{"$period:$grades"} = $id;
	}
	
	foreach my $key ( keys %arr ) {
	    my ($id, $grades, $period ) = split(':', $key );
	    if ( $id != $dateid ) { next; } # skip those for a different date
#	    print "ID:$id Grades:$grades Period:$period<br>\n";

	    if ( $pdata{"$period:$grades"} ) { # we have a match.
#		print qq{<div>Match! - $grades - $period</div>\n};
		delete $arr{$key};
		delete $pdata{"$period:$grades"};
	    }

	}

	# Delete Period Recs

	foreach my $key ( sort keys %pdata ) {
	    my ($period,$grades) = split(':', $key);
	    $sth1->execute($date,$grades,$period);
	    if ($DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    print qq{<div><b>Deleted Periods Closed</b> - Date:$date - Grades:$grades - Period:$period</div>\n};
	}

	
	# Add Period Recs.
	foreach my $key ( sort keys %arr ) { 
	    my ($id, $grades, $period ) = split(':', $key );
	    if ( $id != $dateid ) { next; } # skip those for a different date
	    $sth2->execute($date,$grades,$period);
	    if ($DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    print qq{<div><b>Added Periods Closed</b> - Date:$date - Grades:$grades - Period:$period</div>\n};
	}
	
    } # end of dates loop	
	
    
    print qq{<p>[ <a href="$eoypage">$lex{Eoy}</a> |\n};
    print qq{ <a href="$self">$lex{Edit} $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;

}
