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

#  This file is part of Open Admin for Schools.

# Add injury/accident record 


my %lex = ('Main' => 'Main',
	   'Error' => 'Error',
	   'Students' => 'Students',
	   'Continue' => 'Continue',
	   'Save' => 'Save',
	   'Select' => 'Select',
	   'Check' => 'Check',
	   'Next Page' => 'Next Page',
	   'Required' => 'Required',
	   'Test Date' => 'Test Date',

	   );


use DBI;
use CGI;
use Cwd;

my $self = 'accAdd.pl';

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

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

print $q->header( -charset, $charset );

my $mycss = $css;
if ( getcwd() =~ /tcgi/ ){ # we are in cgi
    $mycss = $tchcss;
}

# Page Header
my $title = qq{Add Injury/Accident Record};
print qq{$doctype\n<html><head><title>$title</title>\n}; 
print qq{<link rel="stylesheet" href="$mycss" type="text/css">\n};

if ( $arr{page} == 2 ) {
    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};
    selectStudent();

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


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

    # Get Grades
    my (%grades, %homerooms);
    my $sth = $dbh->prepare("select distinct grade from student 
	where grade != '' and grade is not NULL");
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    while ( my $gr = $sth->fetchrow ) {
	$grades{$gr} = 1;
    }
    my @grades = sort { $a <=> $b } keys %grades;

    # Homerooms
    my $sth = $dbh->prepare("select distinct homeroom from student 
	where homeroom != '' and homeroom is not NULL");
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    while ( my $hr = $sth->fetchrow ) {
	$homerooms{$hr} = 1;
    }
    my @homerooms = sort { $a <=> $b } keys %homerooms;

    
    print qq{<form action="$self" method="post"> \n};
    print qq{<input type="hidden" name="page" value="1">\n};
    
    print qq{<table cellpadding="4" cellspacing="0" border="0" style="border:1px solid gray;padding:0.5em;">\n};


    # Students - Grade
    print qq{<tr><td class="bla" colspan="2">$lex{Select} $lex{Students}</td></tr>\n};
    print qq{<tr><td class="ra">Grade</td><td><select name="grade"><option></option>};
    foreach my $grade ( @grades ) {
	print qq{<option>$grade</option>\n};
    }
    print qq{</select> <b>or</b></td></tr>\n};

    # Select Homeroom
    my $sth = $dbh->prepare("select lastname, firstname from staff s, staff_multi sm 
			    where s.userid = sm.userid and field_name = 'homeroom' 
			    and field_value = ?");

    print qq{<tr><td class="ra">Homeroom</td><td>};
    print qq{<select name="homeroom"><option></option>};
    foreach my $hr ( @homerooms ) {
	$sth->execute($hr);
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my ($lastname, $firstname) = $sth->fetchrow;
	my $hrname = $hr;
	if ( $lastname ) { $hrname = "$hr - $firstname $lastname"; }
	
	print qq{<option value="$hr">$hrname</option>\n};
    }
    print qq{</select></td></tr>\n};

    print qq{<tr><td colspan="2" style="font-size:80%;font-weight:bold;">Both Blank = All Students</td></tr>\n};
    
    # Continue
    print qq{<tr><td></td><td class="la">\n<input type="submit" value="$lex{Continue}"></td></tr>\n};

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


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

    exit;

} # end of showStartPage



#----------------
sub selectStudent {
#----------------

    # foreach my $key ( sort keys %arr ) { print "K:$key V:$arr{$key}<br>\n"; }
    # passed grade and homeroom
    
    my ($sth, $groupname);
    if ( $arr{grade} ) { # we're picking a group
	$sth = $dbh->prepare("select lastname, firstname, studnum from student
          where grade = ? order by lastname, firstname");
	$sth->execute( $arr{grade} );
	$groupname = qq{Grade $arr{grade}};
	
    } elsif ( $arr{homeroom} ) {
	$sth = $dbh->prepare("select lastname, firstname, studnum from student
          where homeroom = ? order by lastname, firstname");
	$sth->execute( $arr{homeroom} );
	$groupname = qq{Homeroom $arr{homeroom}};
	
    } else { # everyone
	$sth = $dbh->prepare("select lastname, firstname, studnum from student
          order by lastname, firstname");
	$sth->execute;
	$groupname = qq{Entire School};
    }
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }


    print qq{<h3>Select Student - $groupname</h3>\n};
    
    # Form Header
    print qq{<form action="$self" method="post"> \n};
    print qq{<input type="hidden" name="page" value="2">\n};

    print qq{<div><input type="submit" value="$lex{Continue}"></div>\n};
    
    print qq{<table cellpadding="3" cellspacing="0" border="0" style="border:1px solid gray;padding:0.4em;">\n};

    while ( my ( $lastname, $firstname, $studnum ) = $sth->fetchrow ) {
	print qq{<tr><td class="la" colspan="2">};
	print qq{<input type="checkbox" name="$studnum" value="1" $chk> \n};
	print qq{<b>$lastname</b>, $firstname ($studnum)</td></tr>\n};
    }

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

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

    exit;

} # end of selectStudents



#----------------
sub enterAccident {
#----------------

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

    # Save
    print qq{<div style="margin:0.3em;"><input type="submit" value="$lex{Save}"></div>\n};
    
    # Outer Table
    print qq{<table cellpadding="3" cellspacing="0" border="0" style="border:1px solid gray;padding:0.5em;">\n};

    
    # Date
    print qq{<tr><td>Date };
    print qq{<input type="text" name="date" id="date" style="width:10ch;">\n};
    print qq{<button type="reset" id="start_trigger">...</button>\n};
    print qq{(yyyy-mm-dd)</td></tr>\n};

    print qq{<tr><td>\n};
    
    
    # Get Student Record
    my $sth = $dbh->prepare("select * from studentall where studnum = ?");

    
    foreach my $studnum ( sort keys %arr ) {
	# print qq{SN:$studnum<br>\n};
	
	# Get student name and grade, 
	$sth->execute( $studnum );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $ref = $sth->fetchrow_hashref;
	my %r = %$ref;

	print qq{<h3>$r{firstname} $r{lastname}</h3>\n};
	
	# Print Table Header and Heading values
	print qq{<table cellpadding="3" cellspacing="0" border="1">\n};

	# Injury
	print qq{<tr><td class="bra">Injury</td>};
	print qq{<td><textarea name="$studnum:injury" rows="2" cols="60"></textarea></td></tr>\n};

	# Time
	print qq{<tr><td class="bra">Time</td><td class="la">};
	print qq{<input type="text" name="$studnum:time" style="width:10ch;"> };
	print qq{HH:MM am/pm </td></tr>\n};

	# Location
	print qq{<tr><td class="bra">Location</td><td class="la">};
	print qq{<input type="text" name="$studnum:location" style="width:30ch;"></td></tr>\n};

	# Action Taken
	print qq{<tr><td class="bra">Action Taken</td><td class="la">};
	print qq{<textarea name="$studnum:action" rows="2" cols="60"></textarea></td></tr>\n};

	print qq{</table>\n};

    }


    # Close Outer Table
    print qq{</td></tr>\n};
    print qq{</table>\n};

    # Save
    print qq{<div style="margin:0.3em;"><input type="submit" value="$lex{Save}"></div>\n};
    
    print qq{</form>\n};

    print qq{<script type="text/javascript">
     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 
    });
   </script>\n};

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

    exit;

}


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

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

    # Check for any Blanks in date
    if ( not $arr{date} ) {
	print qq{<h3>Date <b>$lex{Required}</b></h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    
    # Check for messed up Date Format
    my $errorflag;
    if ( $arr{date} =~ m/\// ) { # slashes rather than hyphens
	$errorflag = 1;
    } else {
	my ($y,$m,$d) = split('-', $arr{date});
	if ( not $m or ( $m < 1 or $m > 12 )) { $errorflag = 1; }
	if ( not $d or ( $d < 1 or $d > 31 )) { $errorflag = 1; }
    }
    if ( $errorflag ) {
	# print qq{<div>Year:$y Month:$m Day:$d</div>\n};
	print qq{<h3>$lex{'Test Date'} $lex{Error}: $arr{date}</h3>\n};
	print "</body></html>\n";
	exit;
    }

    my $date = $arr{date};
    delete $arr{date};
    # Done with date

    print qq{<h3>Date: $date</h3>\n};


    # Loop over students and get values into hash for each.
    my %rec;
    foreach my $key ( sort keys %arr ) {
	my ($sn, $field) = split(':', $key );
	$rec{$sn}{$field} = $arr{$key};
    }

    
    # Test
#    foreach my $studnum ( sort keys %rec ) {
#	foreach my $field (  keys %{ $rec{$studnum} }) {
#	    print qq{SN:$studnum FLD:$field VAL:$rec{$studnum}{$field}<br>\n};
#	}
#    }

    # Get full student record
    my $sth1 = $dbh->prepare("select * from student where studnum = ?");

    # Write the accident record
    my $sth = $dbh->prepare("insert into accident
    	 ( studnum, injury, date, time, author, location, action  ) 
         values ( ?, ?, ?, ?, ?, ?, ?) ");
    
    foreach my $studnum ( sort keys %rec ) {
	
	# Get Student Record
	$sth1->execute( $studnum);
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $ref = $sth1->fetchrow_hashref;
	my %s = %$ref;

	my %r = %{ $rec{$studnum} };

	
	# Add Accient Record
	$sth->execute( $studnum, $r{injury}, $date, $r{time}, $userid, $r{location}, $r{action} );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	print qq{<div>Record Added for <b>$s{firstname} $s{lastname} ($studnum)</b></div>\n};
	
    }

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

    exit;
}
