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

#  This file is part of Open Admin for Schools.

# Edit an existing land edu record

my %lex = ('Main' => 'Main',
	   'Error' => 'Error',
	   'Edit' => 'Edit',
	   'Name' => 'Name',
	   'Update' => 'Update',
	   'Record Updated' => 'Record Updated',
	   'Edit not allowed' => 'Edit not allowed',
	   'Date' => 'Date',
	   'Close' => 'Close',
	   'Location' => 'Location',
	   'Time' => 'Time',
	   'Action' => 'Action',
	   'Taken' => 'Taken',

	   );

use DBI;
use CGI;
use Cwd;


my $self = 'landEdit.pl';


# Configuration Settings -----------------------
#my $allow_author = 1; # allow author to edit
#my $allow_admin = 1; # allow anyone on the admin site 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]";

my $userid = $ENV{'REMOTE_USER'};

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


# Get current dir so know what CSS to display and shift settings.
if ( getcwd() !~ /tcgi/ ) { # we are in cgi
    $tchcss = $css;
    $tchpage = $homepage;
    $tchdownloaddir = $downloaddir;
    $tchwebdownloaddir = $webdownloaddir;
}


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


# Page Header
my $title = "$lex{Edit} Land Based Education Records";
print qq{$doctype\n<html><head><title>$title</title>};
print qq{<link rel="stylesheet" href="$tchcss" 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="$tchpage">$lex{Main}</a> ]\n};
print qq{<h1>$title</h1>\n};


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

} elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    writeLandEdu();
    
} elsif ( $arr{page} == 2 ) {
    delete $arr{page};
    deleteLandEdu();
}


#---------------
sub deleteLandEdu {
#---------------

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

    my $id = $arr{id};
    delete $arr{id};

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

    if ( $ref->{author} ne $userid ) {
	print qq{<h3>Deletion not allowed if not author</h3>\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;
    }

    
    # Delete LBE Record
    my $sth = $dbh->prepare("delete from landedu where id = ?");
    $sth->execute( $id );
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }

    print qq{<h3>LBE Record is deleted</h3>\n};

    # back to landView
    # print qq{[ <a href="./landView.pl">View/Edit/Delete More Records</a> ]\n};

    print qq{<div><b>Note:</b> Reload main view page to see updates</div>\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 editLandEdu {
#---------------

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

    my $id = $arr{id};
    delete $arr{id};

    # Delete Option
    print qq{<form action="$self" method="post" style="padding:1em;">\n};
    print qq{<input type="hidden" name="page" value="2">\n};
    print qq{<input type="hidden" name="id" value="$id">\n};
    print qq{<input type="submit" value="Delete this Record">\n};
    print qq{</form>\n};

    # Or
    print qq{<div style="margin:0.5em;"><b>Or</b> Edit the Record</div>\n};
    

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


    # Get LBE Record
    my $sth = $dbh->prepare("select * from landedu where id = ?");
    $sth->execute( $id );
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
    my $ref = $sth->fetchrow_hashref;
    my %r = %$ref;
	
	
    # Get Staff Record
    my $sth1 = $dbh->prepare("select * from staff where userid = ?");
    $sth1->execute( $r{userid} );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    my $ref = $sth1->fetchrow_hashref; #
    my %s = %$ref;

    
    
    # Table Header and Heading values
    print qq{<table cellpadding="3" cellspacing="0" border="0" style="border:1px solid gray;padding:0.5em;">\n};

    # Date
    print qq{<tr><td class="bra">Date</td>\n};
    print qq{<td class="la"><input type="text" name="date" id="date" style="width:10ch;" value="$r{date}">};
    print qq{<button type="reset" id="start_trigger">...</button>\n};
    print qq{</td></tr>\n};
   
    # Grades
    print qq{<tr><td class="bra">Grades</td>\n};
    print qq{<td class="la"><input type="text" name="grades" style="width:8ch;" value="$r{grades}">};
    print qq{ involved</td></tr>\n};

    # Hours
    print qq{<tr><td class="bra"># Hours</td>\n};
    print qq{<td class="la"><input type="text" name="hours" style="width:8ch;" value="$r{hours}">};
    print qq{ for this date</td></tr>\n};

    # Description
    print qq{<tr><td class="bra">Description</td>\n};
    print qq{<td class="la">};
    print qq{<textarea name="description" cols="80" rows="4">$r{description}</textarea>\n};
    print qq{</td></tr>\n};

    # Update
    print qq{<tr><td></td><td class="la"><input type="submit" value="Update"></td></tr>\n};
    
    # End of Table
    print qq{</table></form>\n};
    
    print qq{<script type="text/javascript">\n};

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

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

    exit;

}


#-------------
sub writeLandEdu {
#-------------

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

    my $id = $arr{id};
    delete $arr{id};

    my $first = 1;
    
    foreach my $field ( sort keys %arr ) {

	if ( $first ) {
	    print qq{<table cellpadding="3" cellspacing="0" border="0" };
	    print qq{style="border:1px solid gray;padding:0.5em;">\n};
	    print qq{<tr><th>Field</th><th>New Value</th></tr>\n};
	    $first = 0;
	}
	    

	if ( $field eq 'date' ) { # check validity
	    my $err = checkDate( $arr{$field} );
	    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;
	    }
	}

	
	my $sth = $dbh->prepare("update landedu set $field = ? where id = ?");  
	$sth->execute( $arr{$field}, $id );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	print qq{<tr><td class="bra">$field</td><td>$arr{$field}</td></tr>\n};

    }

    print qq{</table>\n};

    print qq{<h3>Record Updated</h3>\n};
    
    print qq{<div><b>Note:</b> Reload main view page to see updates</div>\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;

}
