#!/usr/bin/perl
#  Copyright 2001-2023 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.

# Function: Display discipline info by date range and by type.
#  Accept: startdate, enddate, type, infrac

my %lex = ('Student Infractions' => 'Student Infractions',
	   'by Date' => 'by Date',
	   'Main' => 'Main',
	   'Discipline' => 'Discipline',
	   'Start Date' => 'Start Date',
	   'End Date' => 'End Date',
	   'School Days' => 'School Days',
	   'Category' => 'Category',
	   'Class' => 'Class',
	   'Grade' => 'Grade',
	   'Totals' => 'Totals',
	   'Infraction' => 'Infraction',
	   'Student' => 'Student',
	   'Count' => 'Count',
	   'Percent' => 'Percent',
	   'PerDay' => 'PerDay',
	   'View Report' => 'View Report',
	   'Type' => 'Type',
	   'No Records Found' => 'No Records Found',
	   'Homeroom' => 'Homeroom',
	   'Error' => 'Error',
	   'Statistical' => 'Statistical',
	   'Report' => 'Report',
	   'Demerits' => 'Demerits',
	   'Entry Error' => 'Entry Error',
	   'All' => 'All',

	   'Last,First/Last/First/Initials/Studnum', 'Last,First/Last/First/Initials/Studnum',
	   'Search' => 'Search',
	   
	   );

my $self = 'rptDisc3.pl';

use DBI;
use CGI;
use Number::Format qw{:all};

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


my $q = new CGI;
print $q->header( -charset, $charset );
my %arr = $q->Vars;

my $currdate;
my @time = localtime(time);
my $year = $time[5] + 1900;
my $month = $time[4] + 1;
if (length($month) == 1 ) { $month = '0'. $month; }
if (length($time[3]) == 1 ) { $time[3] = '0'. $time[3]; }
$currdate = "$year-$month-$time[3]";

my $dsn = "DBI:$dbtype:dbname=$dbase";
my $dbh = DBI->connect($dsn,$user,$password);



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

print qq{$chartype\n</head><body>\n};


print qq{[ <a href="$homepage">$lex{Main}</a> |\n};
print qq{<a href="$discpage">$lex{Discipline}</a> ]\n}; #D# = Demerits\n};

print qq{<h1>$title</h1>\n};

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

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


#-------------
sub showReport {
#-------------

    use Time::JulianDay; # get dates in julian format.
    
    # foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }
    # startdate, enddate, student.
    my $startjd = julian_day(split('-',$arr{startdate}));
    my $endjd = julian_day(split('-',$arr{enddate}));
    
    my $student = $arr{student};
    my $sth;
    my $fields = 'lastname,firstname,studnum';
    
    # Setup the Search
    if ($student =~ /\d+/) {  # we have a student number
	$studentnumber = $student;
	$sth = $dbh->prepare("select $fields from studentall where studnum = ?");
	$sth->execute( $student );

    } else { # we have words hopefully with a comma

	my ( $lastname,$firstname )  = split(',', $student);
	# $firstname =~ s/^\s*//;  # don't strip spaces from names
	# $lastname =~ s/^\s*//;
	if ( $lastname and $firstname ){ # both entered.
	    $sth = $dbh->prepare("select $fields from studentall 
				 where lastname = ? and firstname = ?");
	    $sth->execute( $lastname, $firstname );

	} elsif ($lastname and not $firstname){ # only lastname (no comma)

	    if ( length($lastname) == 2 ){ # search by initials: fi, li.
		my $fi = substr($lastname,0,1). '%'; 
		my $li = substr($lastname,1,1). '%';
		$sth = $dbh->prepare("select $fields from studentall 
				     where lastname $sql{like} ? and firstname $sql{like} ?");
		$sth->execute( $li, $fi );

	    } else { # a single value; could be lastname or firstname

#		print "Lastname $lastname<br>\n";
		$sth = $dbh->prepare("select $fields from studentall 
				     where lastname = ? or firstname = ? order by lastname, firstname");
		$sth->execute( $lastname, $lastname );
	    }
	} else { # print an error....
	    print qq{<h3>$lex{'No Student(s) Found'}</h3>\n};
	    print qq{</body></html>\n};
	    exit; 
	}

    } # Last Else

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

    
    # Get the student ident records
    my $sth1 = $dbh->prepare("select * from disc_event where id = ?");
    my $sth2 = $dbh->prepare("select * from disc_action where eventid = ? and studnum = ?");
    my $sth3 = $dbh->prepare("select * from disc_ident where studnum = ? order by id");
    my $sth4 = $dbh->prepare("select * from disc_comment where eventid = ? and studnum = ?");


    
    my $firststud = 1; 
    while ( my ($lastname,$firstname, $studnum ) = $sth->fetchrow ) { # loop over students found

	# Get Ident Records
	$sth3->execute( $studnum );
	if ($DBI::errstr) {print $DBI::errstr; die $DBI::errstr; }

	my $firstrec = 1;
	while ( my $ref = $sth3->fetchrow_hashref ) { # ident record
	    
	    my %s = %$ref;
	    my $eventid = $s{eventid};

	    # Get Matching event record, only one.
	    $sth1->execute( $eventid );
	    if ($DBI::errstr) {print $DBI::errstr; die $DBI::errstr; }
	    my $eref = $sth1->fetchrow_hashref;
	    my %e = %$eref;

	    # Skip if outside date range.
	    my $currjd = julian_day(split('-', $e{date}));
	    if ( $currjd > $endjd or $currjd < $startjd ) {
#		print "Start: $startjd Curr:$currjd End:$endjd DATE:$e{date}<br>\n";
#		print qq{<div>Skipping Event $e{date} - $e{infraction}</div>\n};
		next;
	    }

	    if ( $firstrec ) {
		print qq{<table cellpadding="3" cellspacing="0" border="1" };
		print qq{style="margin-bottom:1em;">\n};
		print qq{<caption style="font-weight:bold;text-align:left;font-size:120%;">};
		print qq{$firstname $lastname ($studnum)</caption>\n};
		print qq{<tr><th>Infraction/Description</th><th>Comment/Demerit</th>};
		print qq{<th>Actions</th></tr>\n};
		$firstrec = 0;
		$firststud = 0;
	    }

	    my (%actions, %comments);
	    
	    # Get Action record, may be several.
	    $sth2->execute( $eventid, $studnum );
	    if ($DBI::errstr) {print $DBI::errstr; die $DBI::errstr; }
	    while ( my $aref = $sth2->fetchrow_hashref ) {
#		print "Action:$aref->{action}<br>\n";
		$actions{ $aref->{id} } = $aref;
	    }

	    # Get Comment records, may be several.
	    $sth4->execute( $eventid, $studnum );
	    if ($DBI::errstr) {print $DBI::errstr; die $DBI::errstr; }
	    while ( my $cref = $sth4->fetchrow_hashref ) {
#		print "Comment:$cref->{comment}<br>\n";
		$comments{ $cref->{id} } = $cref;
	    }
	    

	    
	    # Display results in event, ident, comments, and actions
	    print qq{<tr><td style="width:60ch;vertical-align:top;">};
	    print qq{<b>$e{date}</b> $e{infraction} - $e{description}<br><b>$e{author}</b></td>\n};

	    # Center Comment/Demerit Column
	    print qq{<td style="width:40ch;vertical-align:top;">\n};
	    foreach my $id ( sort keys %comments ) {
		my %c = %{ $comments{$id}};
		print qq{$c{comment} <b>$c{author}</b>};
		print qq{<br>\n};
	    }
	    if ( $s{demerit} ) { print qq{<b>$s{demerit} Demerit(s)</b>}; }
	    print qq{</td>\n};

	    # Right Actions Column
	    print qq{<td style="vertical-align:top;">};
	    foreach my $id ( sort keys %actions ) {
		my %a = %{ $actions{$id}};
		print qq{$a{action} };
		if ( $a{comment} ) {
		    print qq{- $a{comment}};
		}
		print qq{<br>\n};
	    }
	    print qq{</td></tr>\n};

	} # end of event loop
	    
	if ( not $firstrec ) {
	    print qq{</table>\n};
	}

    } # end of student loop

    if ( $firststud ) { # no students;
	print qq{<h3>No Students Found</h3>\n};
    }
	
} # end of showReport




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


    # Setup Calendar
    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{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    
    print qq{<table style="border:1px solid gray;" cellpadding="3" cellspacing="0" border="1">\n};
    print qq{<tr><th colspan="2">Student Search</th></tr>\n};

    print qq{<tr><td class="bra">$lex{'Last,First/Last/First/Initials/Studnum'}</td>\n};
    print qq{<td><input type="text" name="student" style="width:40ch;"></td></tr>\n};
    
    print qq{<tr><td class="bra">$lex{'Start Date'}</td>\n};
    print qq{<td><input type="text" size="10" id="sdate" name="startdate" value="$schoolstart">\n};
    print qq{<button type="reset" id="start_trigger">...</button>};
    print qq{</td></tr>\n};

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


    print qq{<tr><td></td><td class="la"><input type="submit" value="$lex{Search}"></td></tr>\n};
    
    print qq{</table>\n};
    print qq{</form>\n};
    
        print qq{<script type="text/javascript">
     Calendar.setup({
        inputField     :    "sdate", // 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 
    });};

    print qq{Calendar.setup({
        inputField     :    "edate", // 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 
    });};

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

}



#-------------
sub formatDate {
#-------------    
    my $date = $_[0];
    my ($y,$m,$d) = split('-', $date);
    my $month = $s_month[$m];
    $date = qq{$month $d, $y};
    return $date;
}

#-------------
sub formatTime {
#-------------    
    my $time = $_[0];
    my ($h,$m,$s) = split(':', $time);
    my $suffix = 'AM';
    if ( $h > 11 ) { $suffix = 'PM'; }
    if ( $h > 12 ) {
	$h = $h - 12;
    }
    $time = qq{$h:$m $suffix};
    return $time;
}
