#!/usr/bin/perl
#  Copyright 2001-2021 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 = ('Main' => 'Main',
	   'Error' => 'Error',
	   'Literacy Intervention' => 'Literacy Intervention',
	   'Edit' => 'Edit',
	   'Update' => 'Update',
	   'No Blanks Allowed' => 'No Blanks Allowed',
	   'No User Id' => 'No User Id',
	   'No Password' => 'No Password',
	   'Please Log In' => 'Please Log In',
	   'Record(s) Updated' => 'Record(s) Updated',
	   'Not Allowed' => 'Not Allowed',
	   'Teacher' => 'Teacher',
	   'Start Date' => 'Start Date',
	   'End Date' => 'End Date',
	   'Group' => 'Group',
	   'Description' => 'Description',
	   'Program Hours' => 'Program Hours',
	   'Close' => 'Close',
	   'Period Length' => 'Period Length',

	   );

use DBI;
use CGI;
use CGI::Session;


my $self = 'lintProgEdit.pl';

# Configuration Settings -----------------------
my $allow_lint = 1; # allow user with lint access code to edit
#-----------------------------------------------

my $q = new CGI;
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);

# Session Setup Here
my $session = new CGI::Session("driver:mysql;serializer:FreezeThaw",
 undef,{Handle => $dbh}) or die CGI::Session->errstr;

# Get/Set  Session Values (a defined userid means it was passed)
if ( $arr{userid} ){ # we want to login, passed userid/password pair.

    # Check password/userid against database (-1 no user, -2 wrong password);
    my $error = checkPassword($arr{userid}, $arr{password}, $dbh);
    if ($error == -1){ print $q->header( -charset, $charset ); login($lex{'No User Id'}); }
    if ($error == -2){ print $q->header( -charset, $charset ); login($lex{'No Password'}); }

    $cookietime = checkCookieTime( $arr{duration} );

    # Set values for userid and logged_in in session
    $session->param( 'logged_in','1');
    $session->expire( 'logged_in', $cookietime );
    $session->param( 'userid',$arr{userid} );
    $session->param( 'duration',$cookietime );

    $userid = $arr{userid};


} else { # check logged_in value in session

    if ( not $session->param('logged_in') ){
	$userid = $session->param('userid');
        print $q->header( -charset, $charset );
	print qq{[ <a href="$tchpage">$lex{Main}</a> ]\n};
        print qq{<h3>$lex{'Please Log In'}</h3></body></html>\n};
        exit;
    }
    # Ok, we have a login. Values below we have in environment.

    $userid = $session->param('userid');
    $duration = $session->param('duration');

    if ( not ($duration =~ /\+/)) { # if not in +20m format, do so.
	$duration = checkCookieTime( $duration );
    }

    $session->expire('logged_in', $duration );


} # End of check for logged_in value

print $session->header( -charset, $charset );
# Session Setup End


# Check for LINT 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 $accesslint;
while ( my $val = $sth->fetchrow ) {
    if ( uc $val eq 'LINT' ) { $accesslint = 1; }
    # print qq{VAL:$val ACCESS:$accesslint<br>\n};
}


# Page Header
my $title = "$lex{Edit} $lex{'Literacy Intervention'}";
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$tchcss" 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 style="padding:1em 2em;">\n};
print qq{[ <a href="$tchpage">$lex{Main}</a> ]\n};
print qq{<h1>$title</h1>\n};

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


if ( not $arr{page} ) {
    editProgram( $arr{id} );

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


#--------------
sub editProgram {
#--------------

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

    my $id = shift;

    $accesslint = 1;
    #~~ Override for testing....

    # Access Controls
    my $failflag;
    if ( not $allow_lint ) { $failflag = 1; } # nobody edits
    if ( not $accesslint ) { $failflag = 1; } # user doesn't have access code.


    if ( $failflag ) {
	print qq{<h3>$lex{Edit} $lex{'Not Allowed'}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    # Get the Program Record
    my $sth = $dbh->prepare("select * from lint_program where id = ?");
    $sth->execute( $id );
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
    my $ref = $sth->fetchrow_hashref;
    # my %rec = %$ref;

    # Get Current Teacher Name
    my $sth1 = $dbh->prepare("select lastname, firstname from staff where userid = ?");
    $sth1->execute( $ref->{userid} );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    my ( $tlastname, $tfirstname ) = $sth1->fetchrow;


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

    # Print Table Header and Heading values
    print qq{<table cellpadding="3" cellspacing="0" border="0">\n};
    print qq{<tr><td></td><td><input type="submit" value="$lex{Update}"></td></tr>\n};

    my $sth = $dbh->prepare("select lastname, firstname, userid from staff 
      order by lastname, firstname");
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    
    print qq{<tr><td class="bra">$lex{'Teacher'}</td>\n};
    print qq{<td class="la"><select name="teacherid">\n};
    print qq{<option value="$ref->{userid}">$tlastname, $tfirstname</option>\n};
    while ( my ($lastname, $firstname, $userid) = $sth->fetchrow ) {
	if ( $userid eq $ref->{userid} ) { next; } # skip current.
	print qq{<option value="$userid">$lastname, $firstname</option>\n};
    }
    print qq{</select></td></tr>\n};


    print qq{<tr><td class="bra">$lex{'Start Date'}</td>\n};
    print qq{<td class="la"><input type="text" name="startdate" id="startdate" };
    print qq{size="10" value="$ref->{startdate}">\n};
    print qq{<button type="reset" id="start_trigger">...</button>\n};
    print qq{</td></tr>\n};


    print qq{<tr><td class="bra">$lex{'End Date'}</td>\n};
    print qq{<td class="la"><input type="text" name="enddate" id="enddate" };
    print qq{size="10" value="$ref->{enddate}">\n};
    print qq{<button type="reset" id="end_trigger">...</button>\n};
    print qq{</td></tr>\n};

    # Group Description
    print qq{<tr><td class="bra">$lex{Group} $lex{Description}</td>};
    print qq{<td><input type="text" name="groupdesc" size="40" maxlength="40" };
    print qq{value="$ref->{groupdesc}"></td></tr>\n};

    # Program Hours
    print qq{<tr><td class="bra">$lex{'Program Hours'}</td>};
    print qq{<td><input type="text" name="programhours" size="6" };
    print qq{value="$ref->{programhours}"></td></tr>\n};

    # Period Length
    print qq{<tr><td class="bra">$lex{'Period Length'}</td>};
    print qq{<td><input type="text" name="periodlength" size="4" maxlength="4" };
    print qq{value="$ref->{periodlength}"> minutes</td></tr>\n};


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

    print qq{</table></form>\n};

    print qq{<script type="text/javascript">
     Calendar.setup({
        inputField     :    "startdate", // 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 
    });

     Calendar.setup({
        inputField     :    "enddate", // id of the input field
        ifFormat       :    "%Y-%m-%d", // format of the input field
        button         :    "end_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;

}


#----------------
sub updateProgram {
#----------------

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

    # Check for any Blanks
    foreach my $key ( sort keys %arr ) { 
	if ( not $arr{$key} ) {
	    print qq{<h3>$lex{Error}: $lex{'No Blanks Allowed'}</h3>\n};
	    print qq{</body></html>\n};
	    exit;
	}
    }


    my $sth = $dbh->prepare("update lint_program set 
			    userid = ?, groupdesc = ?, startdate = ?, enddate = ?, 
			    programhours = ?, periodlength = ? where id = ?");  

    $sth->execute( $arr{teacherid}, $arr{groupdesc}, $arr{startdate},
		   $arr{enddate},$arr{programhours}, $arr{periodlength}, $arr{id} );

    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }

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

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

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

    exit;

}
