#!/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 = ('Set' => 'Set',
	   'Literacy Intervention' => 'Literacy Intervention',
	   'Group' => 'Group',
	   'Name' => 'Name',
	   'Dates' => 'Dates',
	   'New' => 'New',
	   'Teacher' => 'Teacher',
	   'Start Date' => 'Start Date',
	   'End Date' => 'End Date',
	   'Program Hours' => 'Program Hours',
	   'Main' => 'Main',
	   'Error' => 'Error',
	   'Students' => 'Students',
	   'Record(s) Stored' => 'Record(s) Stored',
	   'Save' => 'Save',
	   'No User Id' => 'No User Id',
	   'No Password' => 'No Password',
	   'Please Log In' => 'Please Log In',
	   'Description' => 'Description',
	   'Add' => 'Add',
	   'Edit' => 'Edit',
	   'Delete' => 'Delete',
	   'Period Length' => 'Period Length',
	   'No Blanks Allowed' => 'No Blanks Allowed',
	   'Not Found' => 'Not Found',

	   );

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


my $self = 'lintProgSet.pl';
my $editscript = 'lintProgEdit.pl';
my $deletescript = 'lintProgDelete.pl';


my $q = new CGI;
my %arr = $q->Vars;


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


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

eval require "../../lib/libsession.pl";
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;


my ( $userid, $duration);
# 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{<html><body>\n};
	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


# Page Header
my $title = "$lex{Set} $lex{'Literacy Intervention'} $lex{Group}";
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};


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

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

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

}  elsif ( $arr{page} == 3 ) {
    delete $arr{page};
    writeRecords();
}


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

    # Load existing programs (ie. lint groups)
    my $sth = $dbh->prepare("select p.*, s.lastname,s.firstname from lint_program p
      left join staff s on s.userid = p.userid  order by startdate desc, s.lastname, s.firstname");
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    

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

    # Add New Group
    print qq{<tr><td colspan="5" class="la">\n};
    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{Add} $lex{New} $lex{Group}"></form>\n};
    print qq{</td></tr>\n};

    print qq{<tr><th>$lex{Name}</th><th>$lex{Dates}</th><th>$lex{Group}</th>};
    print qq{<th></th><th>$lex{Students}</th></tr>\n};

    # Get Names, Programs
    my $sth2 = $dbh->prepare("select s.lastname, s.firstname from lint_student l, studentall s  
      where s.studnum = l.studnum and progid = ? order by s.lastname, s.firstname");


    while ( my $ref = $sth->fetchrow_hashref ) {
	my %r = %$ref;
#	foreach my $key ( sort keys %r ) { print qq{K:$key V:$r{$key}<br>\n}; }

	# Get Staff Member Name; part of main query.
	my $teachername;
	if ( $r{lastname} ) {
	    $teachername = qq{<b>$r{lastname}</b>, $r{firstname}};
	} else {
	    $teachername = qq{<span style="color:red;">$lex{'Not Found'}:</span> $r{userid}}
	}

	print qq{<tr style="vertical-align:top;"><td>$teachername</td>};
	print qq{<td>$ref->{startdate} | $ref->{enddate}</td>\n};
	print qq{<td>$ref->{groupdesc}</td>\n<td>};

	# Edit Button
	print qq{<form action="$editscript" method="post" target="_blank" };
	print qq{style="display:inline;">\n};
	print qq{<input type="hidden" name="id" value="$ref->{id}">\n};
	print qq{<input type="submit" value="$lex{Edit}">\n};
	print qq{</form>\n};

	# Delete Button
	print qq{<form action="$deletescript" method="post" target="_blank" };
	print qq{style="display:inline;">\n};
	print qq{<input type="hidden" name="id" value="$ref->{id}">\n};
	print qq{<input type="submit" value="$lex{Delete}">\n};
	print qq{</form>\n};

	print qq{</td>\n<td>};
	
	# Get Students
	$sth2->execute( $ref->{id} );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	while ( my ($lastname, $firstname) = $sth2->fetchrow ) {
	    print qq{<b>$lastname</b>, $firstname<br>};
	}

	print qq{</td></tr>\n};

    }


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

    exit;

} # end of showStartPage



#-------------
sub addProgram {
#-------------

    print qq{<form action="$self" method="post"> \n};
    print qq{<input type="hidden" name="page" value="3">\n};
    print qq{<table cellpadding="3" cellspacing="0" border="0">\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"><option></option>\n};
    while ( my ($lastname, $firstname, $userid) = $sth->fetchrow ) {
	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" size="10" >\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" size="10">\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"></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"></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"> minutes</td></tr>\n};


    print qq{<tr><td></td><td><input type="submit" value="$lex{Save}"></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;

} # end of addProgram


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

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

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

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

    my $sth = $dbh->prepare("insert into lint_program ( 
      userid, groupdesc, startdate, enddate, programhours, periodlength )
      values ( ?,?,?,?,?,?)"); 

    # Write the test record 
    $sth->execute( $arr{teacherid}, $arr{groupdesc}, $arr{startdate}, $arr{enddate},
		   $arr{programhours},$arr{periodlength});
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }

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

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

    exit;

}
