#!/usr/bin/perl
#  Copyright 2001-2026 Leslie Richardson

#  This file is part of Open Admin for Schools.

# Edit an existing ssp_exception record

my %lex = ('Main' => 'Main',
	   'Error' => 'Error',
	   'Edit' => 'Edit',
	   'Name' => 'Name',
	   'Update' => 'Update',
	   'Record(s) Updated' => 'Record(s) Updated',
	   'Edit not allowed' => 'Edit not allowed',
	   'Date' => 'Date',
	   'Close' => 'Close',
	   'Test' => 'Test',

    );

use DBI;
use CGI;
use Cwd;

my $self = 'readExceptEdit.pl';


# Configuration Settings -----------------------
my $allow_author = 1; # allow author to edit
my $allow_dra = 1; # allow user with reading access code to edit
#-----------------------------------------------

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

my @time = localtime(time);
my $year = $time[5] + 1900;
my $month = $time[4] + 1;
my $currdate = "$year-$month-$time[3]";


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


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


# Teacher Site
if ( getcwd() =~ /tcgi/ ){ # we are in tcgi
    $css = $tchcss;
    $homepage = $tchpage;
    $downloaddir = $tchdownloaddir;
    $webdownloaddir = $tchwebdownloaddir;
} 


# Check for access code
my $sth = $dbh->prepare("select field_value from staff_multi 
  where field_name = 'access' and userid = ?");
$sth->execute( $userid );
if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }

my $accessdra;
while ( my $val = $sth->fetchrow ) {
    if ( uc $val eq 'DRA' ) { $accessdra = 1; }
    # print qq{VAL:$val ACCESS:$accessdra<br>\n};
}


# Page Header
my $title = "$lex{Edit} Reading Exceptions";
print qq{$doctype\n<html><head><title>$title</title>};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};

if ( not $arr{page} ) { # date widget
    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 style="padding:1em 2em;">\n};
print qq{[ <a href="$homepage">$lex{Main}</a> ]\n};
print qq{<h1>$title</h1>\n};


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

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


#----------------
sub editException {
#----------------

    #foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }
    # id is passed.
    my $id = $arr{id};
    
    # Print Form Heading
    print qq{<form action="$self" method="post"> \n};
    print qq{<input type="hidden" name="page" value="1">\n};

    print qq{<div><input type="submit" value="$lex{Update}"></div>\n};

    my $datecounter = 1;
    
    # Get Exception Record
    my $sth = $dbh->prepare("select * from ssp_exceptions where id = ?");
    $sth->execute( $id );
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
    my $ref = $sth->fetchrow_hashref;
    my %r = %$ref;
    
    my $studnum = $r{studnum};

=head
    # Access Controls
    my $failflag;
    if ( not $allow_author and not $allow_dra ) { $failflag = 1; } # nobody edits
    elsif ( $allow_author and $r{tauthor} ne $userid ) { $failflag = 1; } # not author
	
    if ( $allow_dra and $accessdra ) { $failflag = 0; }
    # allow override of author failure for catalyst.

    if ( $failflag ) {
	print qq{<h3>$lex{'Edit not allowed'}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }
=cut
	
    # Get Student Record
    my $sth1 = $dbh->prepare("select * from studentall3 where studnum = ?");
    $sth1->execute( $studnum );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    my $sref = $sth1->fetchrow_hashref; 
    my %s = %$sref;
    
    # Print Table Header and Heading values
    print qq{<table cellpadding="3" cellspacing="0" border="0">\n};
    print qq{<tr><td colspan="2" class="la">\n};

    # Name
    print qq{<tr><td class="bra">$lex{Name}</td>};
    print qq{<td class="la">$s{firstname} $s{lastname}</td></tr>\n};

    print qq{<tr><td class="bra">Grade</td><td class="la">$r{tgrade}</td></tr>\n};
    print qq{<tr><td class="bra">Author</td><td class="la">$r{tauthor}</td></tr>\n}; 

    #  Date
    print qq{<tr><td class="bra">$lex{Test} $lex{Date}</td><td>$r{tdate}</td></tr>\n};

    # Reason Code
    print qq{<tr><td class="bra">Reason</td>};
    print qq{<td class="la"><input type="text" name="$id:reasoncode" value="$r{reasoncode}" };
    print qq{style="width:12ch;"></td></tr>\n};

    # Reason Other Code
    print qq{<tr><td class="bra">Other</td>};
    print qq{<td class="la"><input type="text" name="$id:reasonother" value="$r{reasonother}" };
    print qq{style="width:12ch;"></td></tr>\n};
	
    print qq{</table>\n};


 #   } # record loop end

    
    print qq{<div><input type="submit" value="$lex{Update}"></div>\n};
    print qq{</form>\n};

#    print qq{<script type="text/javascript">\n};

#    foreach my $idx (1 .. ($datecounter - 1)) {

#	print qq{Calendar.setup({
#        inputField     :    "date$idx", // id of the input field
#        ifFormat       :    "%Y-%m-%d", // format of the input field
#        button         :    "start_trigger$idx", // trigger for the calendar (button ID)
#        singleClick    :    false,        // double-click mode
#        step           :    1             // show all years in drop-down boxes 
#    });};

#    }
#    print qq{</script>\n};

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

    exit;

}


#-----------------
sub writeException {
#-----------------

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

	my ($id, $field ) = split(':', $key );

=head	
	if ( $field eq 'tdate' ) { # check validity
	    my $err = checkDate( $arr{$key} );
	    if ( $err == 1 ) {
		print qq{<h4>$lex{Error}: Date Outside School Year: $arr{$key}. Skipping</h4>\n};
		next;
	
	    } elsif ( $err ) {
		print qq{<h4>Date Error: $err. Skipping</h4>\n};
		next;
	    }
	}
=cut

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

    }

    print qq{<h1>$lex{'Record(s) Updated'}</h1>\n};

    print qq{<p><form><input type="hidden" name="none">\n};
    print qq{<input type="button" value="$lex{Close} this Tab" };
    print qq{onClick="parent.close()"></form></p>};

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

}
