#!/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.

# Overridden values for testing: homepage, css


my %lex = ('Error' => 'Error',
	   'Main' => 'Main',
	   'Principal' => 'Principal',
	   'Walkthrough' => 'Walkthrough',
	   'Continue' => 'Continue',
	   'Date' => 'Date',
	   'Time' => 'Time',
	   'Select' => 'Select',
	   'Staff Member' => 'Staff Member',
	   'Template' => 'Template',
	   'Comment' => 'Comment',
	   'Save' => 'Save',
	   'Subject' => 'Subject',
	   'Missing Values' => 'Missing Values',
	   'Areas of Strength' => 'Areas of Strength',
	   'Areas for Improvement' => 'Areas for Improvement',


	   );

my $self = 'pwalkeval.pl';
my $etcpath = "../../etc/admin.conf"; 


use DBI;
use CGI;
use Time::JulianDay;
use Number::Format qw(:all);

eval require $etcpath;
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);
$dbh->{mysql_enable_utf8} = 1;

# Set Date
my @tim = localtime(time);
my $year = $tim[5] + 1900;
my $month = $tim[4] + 1;
my $day = $tim[3];
my $currdate = "$year-$month-$day";
my $currtime = "$tim[2]:$tim[1]:$tim[0]";


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

=head
if ( not $arr{page} ) {
    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};
}
=cut

print qq{$chartype\n</head><body style="padding:1em;">\n};

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


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

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

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


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

    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<input type="hidden" name="currdate" value="$currdate">\n};
    print qq{<input type="hidden" name="currtime" value="$currtime">\n};


    # Display Date/Time but pass as hidden values.
    print qq{<div style="font-weight:bold;font-size:120%;">$lex{Date} $lex{Time}</div>\n};
    print qq{<div>$currdate $currtime</div><p></p>\n};


    # Display Staff
    my $sth = $dbh->prepare("select userid, lastname, firstname from staff  
       order by lastname, firstname");
    $sth->execute;
    if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

    print qq{<div style="font-weight:bold;font-size:120%;margin-top:1em;">};
    print qq{$lex{Select} $lex{'Staff Member'}</div>\n};

    print qq{<table cellpadding="3" border="0" cellspacing="0" >\n};
    print qq{<tr><td class="la"><select name="userid"><option></option>\n};
    while ( my ($userid, $lastname, $firstname) = $sth->fetchrow ) {
	print qq{<option value="$userid">$lastname, $firstname ($userid)</option>\n};
    }
    print qq{</select></td></tr></table>\n};

    
    # Display Templates
    print qq{<div style="font-weight:bold;font-size:120%;margin-top:0.5em;">};
    print qq{$lex{Select} $lex{Template}</div>\n};

    print qq{<table cellpadding="3" border="1" cellspacing="0">\n};
    print qq{<tr><td class="la" colspan="3"><input type="submit" value="$lex{Continue}">\n};
    print qq{</td></tr>\n};

    
    my $sth = $dbh->prepare("select id, title, category  from pwalk_mst order by title, category");
    $sth->execute;
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }


    while ( my ( $id, $title, $category ) = $sth->fetchrow ) {
	print qq{<tr><td class="la"><input type="radio" name="template" value="$id"></td>\n};
	print qq{<td>$title</td><td>$category</td></tr>\n};
    }
    
    print qq{<tr><td class="la" colspan="3"><input type="submit" value="$lex{Continue}">\n};
    print qq{</td></tr>\n};


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

    exit;

} # end of start page.



#----------
sub doScore {
#----------

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

    if ( not $arr{template} or not $arr{userid} ) {
	print qq{<h3>$lex{Error}: $lex{'Missing Values'}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }


    # Load Template
    my $sth = $dbh->prepare("select title, category from pwalk_mst where id = ?");
    $sth->execute( $arr{template} );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    my ($title, $category) = $sth->fetchrow;

    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="2">\n};
    print qq{<input type="hidden" name="currdate" value="$arr{currdate}">\n};
    print qq{<input type="hidden" name="currtime" value="$arr{currtime}">\n};
    print qq{<input type="hidden" name="userid" value="$arr{userid}">\n}; # staff member
    print qq{<input type="hidden" name="template" value="$arr{template}">\n};

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

    print qq{<h3>$firstname $lastname<br>\n};

    # Display Template Title
    # print qq{ $lex{Template}\n};
    print qq{$title ($category)</h3>\n};

    # Display Date/Time but pass as hidden values.
    #print qq{$lex{Date} $lex{Time} $arr{currdate} $arr{currtime}</h3>\n};

    # Display Subject
    print qq{<h3>$lex{Subject} <input type="text" name="subject" size="40" maxlength="60"></h3>\n};


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

    print qq{<tr><th>Description / Score</th><th>$lex{'Areas of Strength'}</th>};
    print qq{<th>$lex{'Areas for Improvement'}</th></tr>\n};

    # Load each of the template values in turn.
    my $sth = $dbh->prepare("select * from pwalk_tpl where mstid = ? order by sequence");
    $sth->execute( $arr{template} );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

    while  ( my $ref = $sth->fetchrow_hashref ) {
	my %r = %$ref;
	print qq{<tr><td class="bra">$r{description}<br>\n};
	print qq{<input type="radio" name="score:$r{id}" value="0"> No Eval };
	for my $idx (1..4) { print qq{ <input type="radio" name="score:$r{id}" value="$idx">$idx }; }
	print qq{</td>\n};
	
	print qq{<td class="la"><textarea name="S:$r{id}" rows="5" cols="50"></textarea></td>\n};
	print qq{<td class="la"><textarea name="W:$r{id}" rows="5" cols="50"></textarea></td>\n};
	print qq{</tr>\n};

    }

    # General Comments
    print qq{<tr><td class="bra">General $lex{Comment}</td>\n};
    print qq{<td class="la" colspan="3"><textarea name="comment" rows="5" cols="100">};
    print qq{</textarea></td></tr>\n};

    # Continue Edit
    print qq{<tr><td class="bra">Continue Editing</td>\n};
    print qq{<td class="la" colspan="3"><input type="checkbox" name="continueedit" value="1">};
    print qq{</td></tr>\n};


    # Submit
    print qq{<tr><td></td><td class="la" colspan="3"><input type="submit" value="$lex{Save}">\n};
    print qq{</td></tr>\n};


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

    exit;

}


#------------
sub saveScore {
#------------

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

    my $authorid = $ENV{'REMOTE_USER'};
    my $datetime = "$arr{currdate} $arr{currtime}";

    # Load Template Master
    my $sth = $dbh->prepare("select title, description, category from pwalk_mst where id = ?");
    $sth->execute( $arr{template} );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    my ($mtitle, $mdescription, $mcategory) = $sth->fetchrow;

    # Load Teacher Information
    my $sth = $dbh->prepare("select lastname, firstname, certification1 from staff where userid = ?");
    $sth->execute( $arr{userid} );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    my ($lastname, $firstname, $cert) = $sth->fetchrow;

    # Insert Master Eval Record
    my $sth = $dbh->prepare("insert into pwalk_eval 
        (title, description, authorid, tuserid, tlastname, tfirstname, tcertnum, subject, 
         adatetime, comment, continueedit ) values ( ?,?,?,?,?,?,?,?,?,?,? ) ");
    $sth->execute($mtitle, $mcategory, $authorid, $arr{userid}, $lastname, $firstname,
		  $cert, $arr{subject}, $datetime, $arr{comment}, $arr{continueedit} );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

    # Get Master ID
    my $sth = $dbh->prepare("select id from pwalk_eval where adatetime = ? and tuserid = ?");
    $sth->execute( $datetime, $arr{userid} );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    my $mstid = $sth->fetchrow;
    if ( not $mstid ) { print qq{<h3>$lex{Error} Master Id not found</h3>\n}; exit; }

    # Prepare for Template Load
    my $sth = $dbh->prepare("select * from pwalk_tpl where id = ?");

    my $sth1 = $dbh->prepare("insert into pwalk_score 
      (mstid, description, category, sequence, score, strengths, weaknesses) values(?,?,?,?,?,?,?) ");


    foreach my $key ( keys %arr ) {
	my ($field, $tplid ) = split(':', $key);
	if ( $tplid and $field eq 'score' ) { # we have a filled value + possible comments
	    # Get a tpl record, add new score record
	    $sth->execute( $tplid );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my $tref = $sth->fetchrow_hashref;
	    my %t = %$tref;

	    my $strengths = $arr{"S:$tplid"};
	    my $weaknesses = $arr{"W:$tplid"};

	    $sth1->execute( $mstid, $t{description},$t{category},$t{sequence},
			    $arr{$key}, $strengths, $weaknesses );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	}
    }

    print qq{<h3>Evaluation Stored</h3>\n};
    print qq{[ <a href="$homepage">$lex{Main}</a> ]\n};    
    print qq{</body></html>\n};

    exit;

} # end of saveScore;
