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

#  This file is part of Open Admin for Schools.

# View Injury/Accient records in accident table


my %lex = ('Main' => 'Main',
	   'Error' => 'Error',
	   'Continue' => 'Continue',
	   'Select' => 'Select',
	   'Student' => 'Student',
	   'Homeroom' => 'Homeroom',
	   'Grade' => 'Grade',
	   'Start Date' => 'Start Date',
	   'End Date' => 'End Date',

	   );

use DBI;
use CGI;
use Cwd;

my $self = 'accView.pl';

my $editScript = './accEdit.pl';

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


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

if ( not $arr{page} ) { # calendar popup.
    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};
    showAccidents();
}


#----------
sub fmtDate {
#----------

    my ( $year, $mon, $day ) = split /-/, shift;
    return "$year-$s_month[$mon]-$day";
}



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

    my @tim = localtime(time);
    my $year = $tim[5] + 1900;
    my $month = $tim[4] + 1;
    my $currdate = "$year-$month-$tim[3]";
    
    
    # Find by Student Group
    my (@homerooms, @grades );
    my $sth = $dbh->prepare("select distinct homeroom from student 
			    where homeroom is not NULL and homeroom != ''");
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    while ( my $hr = $sth->fetchrow ) {
	push @homerooms, $hr;
    }

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

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

    # Select Grade
    print qq{<tr><td class="bra">$lex{Select} $lex{Grade}</td>\n};
    print qq{<td><select name="grade"><option></option>\n};
    foreach my $grade ( @grades ) {
	print qq{<option>$grade</option>\n};
    }
    print qq{</select></td></tr>\n};

    print qq{<tr><td colspan="2" class="cn">OR</td></tr>\n};


    # Select Homeroom and Teacher
    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="bra">$lex{Select} $lex{Homeroom}</td>\n};
    print qq{<td class="la"><select name="homeroom"><option></option>\n};
    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};

    # Start / End Dates
    print qq{<tr><td class="bra">$lex{'Start Date'}</td><td><input type="text" };
    print qq{name="startdate" id="sdate" size="10" value="$schoolstart">};
    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><td><input type="text" };
    print qq{name="enddate" id="edate" size="10" value="$currdate">};
    print qq{<button type="reset" id="end_trigger">...</button></td></tr>\n};

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

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

    print qq{<script type="text/javascript">
     Calendar.setup({
        inputField     :    "sdate", 
        ifFormat       :    "%Y-%m-%d",
        button         :    "start_trigger",
        singleClick    :    false,
        step           :    1
    });

    Calendar.setup({
        inputField     :    "edate",
        ifFormat       :    "%Y-%m-%d",
        button         :    "end_trigger",
        singleClick    :    false,
        step           :    1
    });

   </script>\n};

    
    my $sth1 = $dbh->prepare("select * from studentall where studnum = ?");
    
    # Find existing Records for this School Year
    my $sth = $dbh->prepare("select * from accident
       where to_days(date) > to_days('$schoolstart') and 
       to_days(date) < to_days('$schoolend') order by date");
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }

    print qq{<h3>Existing Records - this School Year</h3>\n};
    
    my $first = 1;
    while ( my $ref = $sth->fetchrow_hashref ) {
	my %r = %$ref;
	my $studnum = $r{studnum};
	
	if ( $first ) {
	    print qq{<table cellpadding="3" cellspacing="0" border="1" style="margin:0.5em;">};
	    print qq{<tr><th>Student</th><th>Injury/<br>Accident</th>};
	    print qq{<th>Action Taken</th>};
	    print qq{<th>Date/Time</th><th>Location</th><th>New<br>Tab</th></tr>\n};
	    $first = 0;
	}

	# Get student name
	$sth1->execute($studnum);
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $sref = $sth1->fetchrow_hashref;
	my %s = %$sref;

	my $fdate = fmtDate($r{date});
	print qq{<tr><td><b>$s{lastname}</b>, $s{firstname} <b>Gr</b>:$s{grade} <b>Hr</b>:$s{homeroom}</td>};
	print qq{<td>$r{injury}</td><td>$r{action}</td>};
	print qq{<td>$fdate $r{time}</td><td>$r{location}</td>};

	print qq{<td><form action="$editScript" method="post" target="_blank">\n};
	print qq{<input type="hidden" name="id" value="$r{id}">\n};
	print qq{<input type="submit" value="Edit"></form></td>\n};

	print qq{</tr>\n};
	
    }
    
    if ( not $first ) { # close table
	print qq{</table>\n};
    }

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

    exit;

} # end of showStartPage



#---------------
sub showAccidents {
#---------------

    # foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }
    # passed start and end dates, homeroom and grade

    # Loop through all students in that grade / homeroom and check for any existing injury records.

    # Find injury records for a student in this date range.
    my $sth1 = $dbh->prepare("select * from accident where studnum = ? and 
       to_days(date) >= to_days( '$arr{startdate}' ) 
       and to_days(date) <= to_days( '$arr{enddate}')");
    
    # Grade or Homeroom
    my ($select, $value, $heading);
    $heading = 'All Students';
    if ( $arr{grade} ) {
	$select = 'where grade = ?';
	$value = $arr{grade};
	$heading = qq{Grade $arr{grade}};
	
    } elsif ( $arr{homeroom} ) {
	$select = 'where homeroom = ?';
	$value = $arr{homeroom};
	$heading = qq{Homeroom $arr{homerom}};
    }


    my $first = 1;
    
    # Get Name, Student Number
    my $sth = $dbh->prepare("select * from student $select order by lastname, firstname");
    $sth->execute($value);
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    while ( my $sref = $sth->fetchrow_hashref ) {
	my %s = %$sref;
	my $studnum = $s{studnum};

	
	# Find any injury/accident records for this student.
	$sth1->execute( $studnum );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	while (my $ref = $sth1->fetchrow_hashref ) {
	    my %r = %$ref;

	    if ( $first ) { # start the table.
		print qq{<table cellpadding="3" cellspacing="0" border="1" };
		print qq{style="border:1px solid gray;padding:0.5em;margin:0.5em;">\n};
		print qq{<caption style="font-weight:bold;font-size:120%;">$heading</caption>\n};

		print qq{<tr><th>$lex{Student}</th><th>Date/Time</th>};
		print qq{<th>Injury<br>Accident</th><th>Action Taken</th><th>New<br>Tab</th></tr>\n};
		$first = 0;
	    }

	    print qq{<tr><td>$s{firstname} $s{lastname}</td><td>$r{date} $r{time}</td>\n};
	    print qq{<td>$r{injury}</td><td>$r{action}</td>};

	    # Edit
	    print qq{<td><form action="$editScript" method="post" target="_blank">\n};
	    print qq{<input type="hidden" name="id" value="$r{id}">\n};
	    print qq{<input type="submit" value="Edit"></form></td>\n};

	    print qq{</tr>\n};
	}
   
    }
    
    if ( not $first ) {
	print qq{</table>\n};
    } else {
	print qq{<h3>No Records Found</h3>\n};
    }


    print qq{<p>[ <a href="$self">View Others</a> ]\n};
    print qq{</body></html>\n};

    exit;

} # end of showAccident
