#!/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 = ('Staff' => 'Staff',
	   'Main' => 'Main',
	   'Eoy' => 'Eoy',
	   'Staff Member' => 'Staff Member',
	   'Error' => 'Error',
	   'Absence' => 'Absence',
	   'Reason' => 'Reason',
	   'Day' => 'Day',
	   'Part' => 'Part',
	   'Date' => 'Date',
	   'AM' => 'AM',
	   'PM' => 'PM',
	   'All Day' => 'All Day',
	   'Record Exists' => 'Record Exists',
	   'Skipping' => 'Skipping',
	   'Record Updated' => 'Record Updated',
	   'Absent' => 'Absent',
	   'Continue' => 'Continue',
	   'Out of Range' => 'Out of Range',
	   'Invalid Date' => 'Invalid Date',
	   'Missing' => 'Missing',
	   'Other' => 'Other',
	   'Late' => 'Late',
	   'Audit' => 'Audit',
	   'Record Stored' => 'Record Stored',
	   'Edit' => 'Edit',
	   
	   );

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


my @dayparts; # put in translated values, if necessary.
foreach my $dp ( 'AM', 'PM', 'All Day' ) {
    push @dayparts, $lex{$dp};
}

my $self = 'staffabsEdit.pl';


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


# Load audit write function
eval require "../../lib/libaudit.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 @tim = localtime(time);
my $year = $tim[5] + 1900;
my $month = $tim[4] + 1;
my $day = $tim[3];
if (length($month) == 1){ $month = "0".$month;}
if (length($day) == 1){ $day = "0".$day;}
my $currdate = "$year-$month-$day";


# Print Page Header
my $title = "$lex{Edit} $lex{Staff} $lex{Absence}";

print qq{$doctype\n<html><head><title>$title</title>
<link rel="stylesheet" href="$css" type="text/css">
$chartype\n};

if ( not $arr{page} ) { # date function
    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{</head>\n<body style="padding:1.5em;">[ <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};
    writeRecords();
}



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

    my $id = $arr{id}; # id of the record to edit in staff_absent table


    # select values from staff table.
    $sth1 = $dbh->prepare("select * from staff where userid = ?");


    my $sth = $dbh->prepare("select * from staff_absent where id = ?");
    $sth->execute( $id );
    if (DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    my $ref = $sth->fetchrow_hashref;
    my %r = %$ref;


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

    print qq{<table cellpadding="3" border="1" cellspacing="0">\n};

    print qq{<tr><td class="bra">$lex{Absent} $lex{Date}</td>};
    print qq{<td><input type="text" name="adate" id="date" size="10" value="$r{adate}">\n};
    print qq{<button type="reset" id="start_trigger">...</button></td></tr>\n};

    print qq{<tr><td class="bra">$lex{'Staff Member'}</td><td>$r{firstname} $r{lastname} };
    print qq{($r{userid})</td></tr>\n};

    # Day Part
    print qq{<tr><td class="bra">$lex{Day}<br>$lex{Part}</td>};
    print qq{<td><select name="daypart"><option>$r{daypart}</option>\n};
    foreach my $part ( @dayparts ) { # defined at top; also translated.
	print qq{<option>$part</option>};
    }
    print qq{</select></td></tr>\n};

    # Reason
    print qq{<tr><td class="bra">$lex{Reason}</td>};
    print qq{<td class="la"><select name="reason"><option>$r{reason}</option>\n};
	foreach my $rsn ( @g_StaffAbsReason ) {
	    print qq{<option>$rsn</option>};
	}
    print qq{</select></td></tr>};

    # Other Reason
    print qq{<tr><td class="bra">$lex{Reason}<br>$lex{Other}</td>};
    print qq{<td class="la"><input type="text" name="other" size="12" value="$r{other}"></td></tr>};

    # Late
    print qq{<tr><td class="bra">$lex{Late}<br>(minutes)</td>};
    print qq{<td class="la"><input type="text" name="late" size="4" value="$r{late}"></td></tr>};
    
    print qq{<tr><td></td><td class="la"><input type="submit" value="$lex{Continue}"></td></tr>\n};
    
    print qq{</table></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};

    exit;

} # end of showStartPage



#---------------
sub writeRecords {
#---------------

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

    my $date = $arr{adate};

    my $userid = $arr{userid};
    delete $arr{userid}; # don't need to update in record

    # Check Date for not in future and within current school year, and validity.
    if ( not checkdate( $date ) ) { 
	print qq{<h3>$lex{'Invalid Date'}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    my $currjd = julian_day( split('-', $currdate));	
    my $startjd = julian_day( split('-', $schoolstart)); # global var
    my $datejd = julian_day( split('-', $date));
    if ( $datejd > $currjd + 7 or $datejd < $startjd ) {
	print qq{<h3>$lex{Error}: $lex{Date} $lex{'Out of Range'}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }


    my $sth1 = $dbh->prepare("select lastname, firstname from staff where userid = ?");
    $sth1->execute( $userid );
    if (DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    my ( $lastname, $firstname ) = $sth1->fetchrow;


     # Check each userid group for completeness
     if ( not $arr{daypart} ) { 
	 print qq{<h3>$lex{Error} - $lex{Missing} $lex{Day} $lex{Part}: $firstname $lastname</h3>\n};
	 next;
     }

     if ( $arr{reason} =~ 'Other' and not $arr{other} ) { 
	 print qq{<h3>$lex{Error} - $lex{Missing} $lex{Other} $lex{Reason}: $firstname $lastname</h3>\n};
	 next;
     }


# Bypass this checking since we already have this on add.
=head
    my $sth1 = $dbh->prepare("select count(*) from staff_absent where adate = ? and daypart = ? and userid = ?");

     # Check for an existing record for this userid for this date and for this day part.
     $sth1->execute($date, $lex{AM}, $userid );
     if (DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
     my $amcount = $sth1->fetchrow;

     $sth1->execute($date, $lex{PM}, $userid );
     if (DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
     my $pmcount = $sth1->fetchrow;

     $sth1->execute($date, $lex{'All Day'}, $userid );
     if (DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
     my $alldaycount = $sth1->fetchrow;

     # print qq{AM:$amcount PM:$pmcount ALL DAY:$alldaycount<br>\n};

     # not efficient but easier to understand.
     if ( $daypart eq $lex{AM} and ($amcount or $alldaycount) ) {
	 print qq{<h3>$lex{Error}: $lex{'Record Exists'}; $date - $userid - $daypart; $lex{Skipping}</h3>\n};
	 next;
     }
     
     if ( $daypart eq $lex{PM} and ($pmcount or $alldaycount) ) {
	 print qq{<h3>$lex{Error}: $lex{'Record Exists'}; $date - $userid - $daypart; $lex{Skipping}</h3>\n};
	 next;
     }

     if ( $daypart eq $lex{'All Day'} and ($amcount or $alldaycount or $pmcount) ) {
	 print qq{<h3>$lex{Error}: $lex{'Record Exists'}; $date - $userid - $daypart; $lex{Skipping}</h3>\n};
	 next;
     }
=cut

    # Load Current Record for audit
    my $sth1 = $dbh->prepare("select * from staff_absent where id = ?");
    $sth1->execute( $id );
    if (DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    my  $startref = $sth1->fetchrow_hashref;


    my %audit;
    $audit{userid} = $ENV{REMOTE_USER};
    $audit{ipaddr} = $ENV{REMOTE_ADDR};
    $audit{scriptname} = $self;
    $audit{tablename} = 'student_absent';
    $audit{tableid} = $sref->{studid};
    $audit{startval} = $startref;
    $audit{endval} = \%arr; 

    addAudit( \%audit, $dbh );

    print qq{<h3>$lex{Audit} $lex{'Record Stored'}</h3>\n};


    foreach my $field ( keys %arr ) {
	# print qq{Field:$field V:$arr{$field}<br>\n";
	my $sth = $dbh->prepare("update staff_absent set $field = ? where id = ?");
	$sth->execute( $arr{$field}, $id );
	if (DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

    }

    print qq{<h3>$lex{'Record Updated'}: $firstname $lastname - $date - $arr{daypart}</h3>\n};

    print qq{<p>[ <a href="$homepage">$lex{Main}</a> | \n};
    print qq{ <a href="$self">$title</a> ]</p>\n};

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

    exit;

} # End of writeRecords



#------------
sub checkdate {  # check date for validity
#------------

    my @mdays = (0,31,28,31,30,31,30,31,31,30,31,30,31);
    my $maxyear = 2100;

    my $val = shift;

    if ( not $val =~ m/-/ ) {  # fail if no hyphens
	return undef;
    }

    # Strip Spaces
    $val =~ s/^\s+//g;
    $val =~ s/\s+$//g;

    my ( $year, $month, $day) = split(/-/, $val);


    # Check for non-digits
    if ($year =~ m/\D/) { return undef; }
    if ($month =~ m/\D/) { return undef; }
    if ($day =~ m/\D/) { return undef; }

    # reset Feb max days, if leap years
    if ($month == 2) {
	if ($year % 4 != 0) { $mdays[2] = 28; }
	elsif ($year % 400 == 0) { $mdays[2] = 29; }
	elsif ($year % 100 == 0) { $mdays[2] = 28; }
	else { $mdays[2] = 29; }
    }

    # check ranges
    if ( $day < 0 or $day > $mdays[$month] ) { # days out of range
	return undef;
    } elsif ( $month < 0 or $month > 12 ) { # month error
	return undef;
    } elsif ( $year < 0 or $year > $maxyear ) {
	return undef;
    }

    return $val;

}


