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

#  This file is part of Open Admin for Schools.

my %lex = ('Main' => 'Main',
	   'Error' => 'Error',
	   'Add' => 'Add',
	   'Student' => 'Student',
	   'Continue' => 'Continue',
	   'Date' => 'Date',
	   'Grade' => 'Grade',
	   'Homeroom' => 'Homeroom',
	   'Select' => 'Select',
	   'Students' => 'Students',
	   'Added' => 'Added',
	   'Or' => 'Or',
	   'Not Selected' => 'Not Selected',
	   'Comment' => 'Comment',
	   'Edit' => 'Edit',
	   'Discipline' => 'Discipline',
	   
	   );

use DBI;
use CGI;
use Cwd;


# Get current dir so know what path for config files.
my $configpath;
my $teachermode;
if ( getcwd() =~ /tcgi/ ){ # we are in tcgi
    $teachermode = 1;
    $configpath = '..'; # go back one to get to etc.

} else {
    $configpath = '../..'; # go back two to get to etc.
}


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


my $self = 'discComment.pl';


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

my @time = localtime(time);
my $year = $time[5] + 1900;
my $month = $time[4] + 1;
my $day = $time[3];
if ( length $month == 1 ) { $month = '0'. $month; }
if ( length $day == 1 ) { $day = '0'. $day; }
my ($hour,$minute) = ($time[2], $time[1]);
if ( length $hour == 1 ) { $hour = '0'. $hour; }
if ( length $minute == 1 ) { $minute = '0'. $minute; }

my $currdate = "$year-$month-$day";
my $currtime = "$hour:$minute";


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

# Get current dir so know what CSS to display and shift to teacher settings.
if ( getcwd() =~ /tcgi/ ) { # we are in tcgi

    $css = $tchcss;
    $homepage = $tchpage;
    $schpage = $tchpage;
}

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

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

# Page Header
my $title = qq{$lex{Add}/$lex{Edit} $lex{Discipline} $lex{Comment}};

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

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


print qq{$chartype\n</head><body style="padding:1em 2em;">\n};
print qq{<div>[ <a href="$homepage">$lex{Main}</a> \n};
if ( not $teachermode ) {
    print qq{| <a href="$discpage">$lex{Discipline}</a> \n};
}
print qq{] User:$userid</div>\n};
print qq{<h1>$title</h1>\n};


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

}  elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    selectStudents();
    
}  elsif ( $arr{page} == 2 ) {
    delete $arr{page};
    selectInfraction();

}  elsif ( $arr{page} == 3 ) {
    delete $arr{page};
    enterComments();
    
} elsif ( $arr{page} == 4 ) {
    delete $arr{page};
    writeComments();
}


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

    my (@homerooms, @grades );
    # Get Homerooms
    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;
    }
    @homerooms = sort {$a <=> $b} @homerooms;

    # Get Grades
    $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;

    
    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">\n};

    # Heading
    print qq{<tr><th>$lex{Select} $lex{Students}</th><th></th></tr>\n};
    
    # Select Grade
    print qq{<tr><td class="la"><b>$lex{Grade}</b> };
    foreach my $gr ( @grades ) {
	print qq{<input type="checkbox" name="grade:$gr" value="1">$gr };
    }
    print qq{</td></tr>\n};

    # OR
    print qq{<tr><td class="bla" style="color:blue;">$lex{Or}</td></tr>\n};


    # Select Homeroom
    print qq{<tr><td class="la" style="width:70ch;"><b>$lex{Homeroom}</b> };
    foreach my $hr ( @homerooms ) {
	print qq{<input type="checkbox" name="hroom:$hr" value="1">$hr \n};
    }
    print qq{</td></tr>\n};

    
    # Submit
    print qq{<tr><td colspan="2"><hr></td></tr>\n};
    print qq{<tr><td>\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 selectStudents {
#-----------------

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

    my (%grades, %homerooms);
    my $select;
    foreach my $key ( keys %arr ) {
	my ($type,$val) = split(':', $key);
	if ($type eq 'grade' ) { $grades{$val} = 1; };
	if ($type eq 'hroom' ) { $homerooms{$val} = 1; };
    }

    # Test
#    foreach my $gr ( sort keys %grades ) { print qq{Grade:$gr<br>\n}; }
#    foreach my $hr ( sort keys %homerooms ) { print qq{Homeroom:$hr<br>\n}; }

    if ( not %grades and not %homerooms ) {
	print qq{<h3>$lex{Students} $lex{'Not Selected'}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }


    my (%students, %sort);
    
    if ( %grades ) {
	
	my $sth = $dbh->prepare("select * from student where grade = ?");
	
        foreach my $gr ( keys %grades ) {
	    $sth->execute( $gr );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    
	    while ( my  $ref = $sth->fetchrow_hashref ) {
		my $studnum = $ref->{studnum};
		$students{$studnum} = $ref;
		$sort{"$ref->{lastname}$ref->{firstname}$studnum"} = $studnum;
	    }
	}
    }


    if ( %homerooms ) {
	
	my $sth = $dbh->prepare("select * from student where homeroom = ?");
	
        foreach my $hr ( keys %homerooms ) {
	    $sth->execute( $hr );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    
	    while ( my  $ref = $sth->fetchrow_hashref ) {
		my $studnum = $ref->{studnum};
		$students{$studnum} = $ref;
		$sort{"$ref->{lastname}$ref->{firstname}$studnum"} = $studnum;
	    }
	}
    }
    

#    print qq{<div style="font-size:130%;"><b>$lex{Date}</b> $arr{tdate}</div>\n};

    # Print Form Heading
    print qq{<form action="$self" method="post"> \n};
    print qq{<input type="hidden" name="page" value="2">\n};

    my $first = 1;

    my $sth1 = $dbh->prepare("select count(*) from disc_event e, disc_ident i  where 
			     e.id = i.eventid and i.studnum = ?");
	
    # Student Loop
    foreach  my  $key ( sort keys %sort  ) {
	my $studnum = $sort{$key};
	my %r = %{ $students{$studnum}};

	# Get Event Count
	$sth1->execute( $studnum );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $ecount = $sth1->fetchrow; # disc event count
	if ( not $ecount ) { next; } # skip those without an event
	
	if ( $first ) {
	    print qq{<div class="la"><input type="submit" value="$lex{Continue}"></div>\n};
	    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
	    print qq{<tr><th>$lex{Student}</th><th>$lex{Grade}</th><th>$lex{Homeroom}</th>};
	    print qq{<th>#Events</th></tr>\n};
	    $first = 0;
	}

	print qq{<tr><td class="la"><input type="checkbox" name="$r{studnum}" value="1" $checked> };
	print qq{<b>$r{lastname}</b>, $r{firstname}</td><td class="cn">$r{grade}</td>};
	print qq{<td class="cn">$r{homeroom}</td><td class="cn">$ecount</t></tr>\n};
    }

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

    exit;

} # end of selectStudent



#-------------------
sub selectInfraction {
#-------------------

    # print "<div>Enter Comment</div>\n";
    # foreach my $key ( sort keys %arr ) { print "K:$key V:$arr{$key}<br>\n"; }
  
    if ( not %arr ) {
	print qq{<h3>$lex{Error}: No Student Selection</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    my (%sort, %student);
    # Get events for student.
    my $sth1 = $dbh->prepare("select e.* from disc_event as e, disc_ident as i where 
			     e.id = i.eventid and i.studnum = ? order by e.date desc");

    my $sth = $dbh->prepare("select * from student where studnum = ?");
    foreach my $studnum  (keys %arr ) {
	$sth->execute( $studnum );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $ref = $sth->fetchrow_hashref;
	$student{$studnum} = $ref;
	my %r = %{ $ref };
	$sort{"$r{lastname}$r{firstname}$studnum"} = $studnum;
    }

    # Print Form Heading
    print qq{<form action="$self" method="post"> \n};
    print qq{<input type="hidden" name="page" value="3">\n};
    
    print qq{<div class="la" style="margin:1em;"><input type="submit" value="$lex{Continue}"></div>\n};

    # Student Loop    
    foreach my $key ( sort keys %sort ) {
	my $studnum = $sort{$key};
	my %r = %{ $student{$studnum}};

	print qq{<div style="font-size:120%;font-weight:bold;">};
	print qq{$r{firstname} $r{lastname} ($studnum)</div>\n};

	# Table start
	print qq{<table cellpadding="3" cellspacing="0" border="1" style="margin:1em;">\n};
	print qq{<tr><th>Select Events</th><th>Date</th><th>Description</th></tr>\n};

	# List all the events for the student
	$sth1->execute( $studnum );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	while ( my $eref = $sth1->fetchrow_hashref ) {
	    my %e = %$eref; # event records, newest first;
	    print qq{<tr><td style="width:30ch;">};
	    print qq{<input type="checkbox" name="$e{id}:$studnum" value="1"> };
	    print qq{$e{infraction}</td>};
	    print qq{<td style="width:10ch;">$e{date}</td><td>$e{description}</td></tr>\n};
	}
	print qq{</table>\n}; # end of event loop
	
    } # end of student loop
    
    print qq{<div class="la" style="margin:1em;"><input type="submit" value="$lex{Continue}"></div>\n};
    print qq{</form></body></html>\n};

    exit;

} # end of select Infraction


#---------------
sub enterComments {
#---------------
    
#    print "Enter Comment<br>\n";
#    foreach my $key ( sort keys %arr ) { print "K:$key V:$arr{$key}<br>\n"; }
    # values are passed as eventid:studnum key pairs, value is just 1;
    
    my $mode = 'add';
    my $id = $arr{id};
    if ( $arr{eventid} ) { # have a passed value from discView
	my $combined = qq{$arr{eventid}:$arr{studnum}};
	%arr = (); # empty %arr
	$arr{$combined} = 1;
	$mode = 'edit';
    }


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

    # Student Name
    my $sth = $dbh->prepare("select lastname, firstname from student where studnum = ?");

    # Get Event
    my $sth1 = $dbh->prepare("select * from disc_event where id = ?");

    # Edit Mode
    # Get comment for this student, this event by record id
    my $sth2 = $dbh->prepare("select comment, author from disc_comment where id = ?");

    # Get Demerit,detention,suspension for this student,event (unique)
    # my $sth3 = $dbh->prepare("select demerit from disc_ident
    # where eventid = ? and studnum = ?");
    my $sth3 = $dbh->prepare("select demerit, detention, suspension from disc_ident
			     where eventid = ? and studnum = ?");
    

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

    my $first = 1;
    
    foreach my $key ( keys %arr ) {
	
	my ($eventid, $studnum) = split(':',$key);

	# Get student name
	$sth->execute( $studnum );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my ($ln,$fn) = $sth->fetchrow;
	
	# Get Event record
	$sth1->execute( $eventid );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $ref = $sth1->fetchrow_hashref;
	my %e = %$ref;

	
	# Load the demerit,detention,suspension if any. There can only be one in the ident table.
	$sth3->execute( $eventid,$studnum );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my ($demerit,$detention,$suspension) = $sth3->fetchrow;

	
	if ( $mode eq 'edit' ) { # we also have id defined.
	    
	    # Load the Comment, by id. since there may be more than one by student,event
	    $sth2->execute( $id ); #$eventid,$studnum );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    ($comment,$author) = $sth2->fetchrow;


	    # Check if userid is the author of this record.
	    if ( $teachermode and ($author ne $userid) ) { # edit not allowed
		print qq{<h3>The author is userid <i>$author</i>. You are userid <i>$userid</i>.};
		print qq{<br><br>};
		print qq{Edit not allowed</h3>\n};
		

		print qq{<p><form><input type="hidden" name="none">\n};
		print qq{<input type="button" value="Close Tab" };
		print qq{onClick="parent.close()"></form></p>};
		
		print qq{</body></html>\n};
		exit;
	    }
	}

	
	# Table start
	print qq{<table cellpadding="3" cellspacing="0" border="1" style="margin:1em;">\n};
	# print qq{<tr><th>Student / Infraction / Date</th></tr>\n};
	print qq{<tr><th style="text-align:left;">$fn $ln ($studnum)</th></tr>\n};
	$first = 0;

	print qq{<tr><td style="width:100ch;">};
	print qq{<b>$e{infraction}</b> / $e{date} };
	if ( $author ) {
	    print qq{/ Author <b>$author</b>};
	}
	print qq{</td></tr>\n};

	print qq{<tr><td><b>Event Description</b>: $e{description}</td></tr>\n};

	# show demerit only if admin site, or userid is same as event author.
	if ( not $teachermode or ($userid eq $e{author}) ) {
	    print qq{<tr><td><b>Demerit</b> <input type="text" name="$key:D" value="$demerit" style="width:3ch;">\n};
	    print qq{ | <b>Detention</b> <input type="text" size="5" name="$key:T" value="$detention" style="width:3ch;">\n};
	    print qq{ | <b>Suspension</b> <input type="text" size="5" name="$key:S" value="$suspension" style="width:3ch;">\n};
	    print qq{</td></tr>\n};
	}

	
	print qq{<tr><td class="bla">Add/Edit Comment<br>};
	print qq{<textarea name="$key" rows="4" cols="100">$comment</textarea>};
	if ( $id ) { # an existing comment record to be updated.
	    print qq{<input type="hidden" name="id" value="$id">\n};
	}
	print qq{</td></tr>\n};
	print qq{</table>\n};

    }

    if ( $first ) {
	print qq{<div>No Records Found</div>\n};
    }
    
    print qq{<div class="la" style="margin:1em;">};
    print qq{<input type="submit" value="$lex{Continue}"></div>\n};

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


#----------------
sub writeComments {
#----------------

    # print "Write Comment<br>\n";
    # foreach my $key ( sort keys %arr ) { print "K:$key V:$arr{$key}<br>\n"; }
    # exit;
    # Normal eventid:studnum pairs; demerits,etc will have a trailing D/T/S as eventid:student:D|T|S

    my $id;
    if ( $arr{id} ) {
	$id = $arr{id};
	delete $arr{id};
    }

    
    # Insert Comment
    my $sth = $dbh->prepare("insert into disc_comment (eventid, studnum, author, comment) 
			    values(?,?,?,?)");

    # Get Event 
    my $sth1 = $dbh->prepare("select * from disc_event where id = ?");
    
    # Get Student Name
    my $sth2 = $dbh->prepare("select lastname, firstname from studentall where studnum = ?");

    # Update an existing comment by id
    my $sth3 = $dbh->prepare("update disc_comment set comment = ? where id = ?");

    my %sigilmap = ( 'D' => 'demerit', 'T' => 'detention', 'S' => 'suspension' );

    
    foreach my $key ( keys %arr ) {

	my ($eventid,$studnum,$sigil) = split(':',$key); # D is demerit, S is supension, T is detention

	# Get student name.
	$sth2->execute( $studnum );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my ($ln,$fn) = $sth2->fetchrow;
	
	if ( $sigil ) { # a demerit,etc. to update
	    my $field = $sigilmap{ $sigil };
	    
	    # Update Demerit, etc. by studnum, eventid
	    my $sth4 = $dbh->prepare("update disc_ident set $field = ? where studnum = ? and eventid = ?");
	    my $val = $arr{$key};
	    $sth4->execute( $val, $studnum, $eventid );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    print qq{<div style="font-weight:bold;font-size:120%;">};
	    my $fld = ucfirst $field;
	    print qq{$fld Updated to $val for $fn $ln ($studnum)</div>\n};
	    print qq{<hr style="width:40ch;margin-left:0;">\n};
	    next;
	}


	# Get Event Record
	$sth1->execute( $eventid );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $ref = $sth1->fetchrow_hashref;
	my %e = %$ref;
		 
	# Edit or Insert Comment Record
	if ( $id ) { # we are doing an edit to update record.
#	    print qq{Doing Edit ID:$id VAL:$arr{$key}<br>\n};
	    $sth3->execute( $arr{$key}, $id );
		    
	} else { # normal insert
	    $sth->execute( $eventid, $studnum, $userid, $arr{$key} );
	}

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

	print qq{<div style="font-weight:bold;font-size:120%;">};
	print qq{$fn $ln ($studnum) };
	print qq{<span style="font-weight:normal;">Comment $lex{Added}/Updated to</span> };
	#	print qq{$e{infraction}</div>\n};
	print qq{$arr{$key}</div>\n};
	print qq{<hr style="width:40ch;margin-left:0;">\n};
	
    } # students loop

    
    if ( $id ) { # we are doing an edit in a tab, so close the tab
	# Close Tab
	print qq{<p><form><input type="hidden" name="none">\n};
	print qq{<input type="button" value="Close Tab" };
	print qq{onClick="parent.close()"></form></p>};
	
    } else { # just a normal insert

	print qq{<p><form action="./discView.pl">\n};
	print qq{<input type="submit" value="View Discipline"> };
	print qq{</form></p>\n};
    }

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

    exit;

} # end of writeComments
