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

# Add comments to the goals set. It goes into iep_comment in local database.


my %lex = ('View Special Needs Students' => 'View Special Needs Students',
	   'Main' => 'Main',
	   'Name' => 'Name',
	   'Id' => 'Id',
	   'Description' => 'Description',
	   'Designation' => 'Designation',
	   'DDPF Level' => 'DDPF Level',
	   'Des Date' => 'Des Date',
	   'Medical' => 'Medical',
	   'Medication' => 'Medication',
	   'Equipment' => 'Equipment',
	   'Adaptations' => 'Adaptations',
	   'History' => 'History',
	   'View Detailed Report' => 'View Detailed Report',
	   'Error' => 'Error',
	   'Bdate' => 'Bdate',
	   'Grade' => 'Grade',
	   'School' => 'School',
	   'Gender' => 'Gender',
	   'Studnum' => 'Studnum',
	   'ProvNum' => 'ProvNum',
	   'Continue' => 'Continue',
	   'Save' => 'Save',
	   
	   );


use DBI;
use CGI;
use Cwd;

my $self = 'specedComment.pl';

# Set prepath for config file: (/tcgi or cgi/schedule)
my $prepath = '../..';
if ( getcwd() =~ /tcgi/){ # we are in tcgi
    $prepath = '..';
}

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


if ( getcwd() =~ m/tcgi/){ # we are in tcgi
    $css = $tchcss;
    $homepage = $tchpage;
}

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


my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, 
 $iddst) = localtime(time);
$year = $year + 1900;
$mon++;
$wday++;
my $currdate = "$dow[$wday], $month[$mon] $mday, $year";
my $date = qq{$year-$mon-$mday};

my $schooldbase = $dbase; # from admin.conf

my %staffnames;
# Get Staff Names
my $dsn = "DBI:$dbtype:dbname=$dbase";
my $dbh = DBI->connect($dsn,$user,$password);

my $sth = $dbh->prepare("select lastname, firstname, userid from staff");
$sth->execute;
if ($DBI::errstr){ print $DBI::errstr; die; }
while ( my ($lastname,$firstname, $userid) = $sth->fetchrow ) {
    $staffnames{$userid} = qq{$firstname $lastname};
}

# Get all school terms.
my (@terms,%terms);
foreach my $track ( keys %g_MTrackTerm ) {
    foreach my $term ( keys %{ $g_MTrackTerm{$track}} ) {
	$terms{$term} = 1;
    }
}
my @terms = sort keys %terms; # ordered terms.


# Disable for associate schools.
if ( not $iepdir ) { # associate school only, using local IEP system.
    print qq{$doctype\n<html><head><title>$title</title>\n};
    print qq{<link rel="stylesheet" href="$css" type="text/css">\n};
    print qq{<h2>Global IEP records not available</h2>\n};
    print qq{</body></html>\n};
    exit;
}

# don't move this up...
require "$iepdir/cgi/ppp.conf" || die "Cannot read the Special Ed ppp.conf file!";

# Reset these values;
if ( getcwd() =~ m/tcgi/){ # we are in tcgi
    $css = $tchcss;
    $homepage = $tchpage;
}

# make copy of dbh for local access when storing local values
my $dbhlocal = $dbh;


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

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

if (not $arr{page} ) {
    print "School:$arr{school}  Student:$arr{studnum}<br>\n";
}

my $title = qq{Student IEP Comments - Add/Edit};
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};


print qq{<style>td.rat { text-align:right;vertical-align:top; }};
print qq{ td.brat { text-align:right;vertical-align:top;font-weight:bold; }</style>\n};
print qq{$chartype</head><body>\n};

print qq{[ <a href="$homepage">$lex{Main}</a> ]\n};
print qq{<span><b>Userid</b> $userid</span>\n};

print qq{<h1>$title - $schoolname</h1><h3>$currdate</h3>\n};


if ( not $arr{page} ) {
    showStartPage(); # get term for entry;
    
} elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    getComments();
    
} elsif ( $arr{page} == 2 ) {
    delete $arr{page};
    writeComments();
}



#----------------
sub showStartPage {  # get term and select students that have this user as a team member.
#----------------

    # Student Teams with this userid
    my $sth1 = $dbh->prepare("select lastname, firstname from special where studnum = ?");
    
    my $sth = $dbh->prepare("select * from team where schooldbase = ? and userid = ?");
    $sth->execute($schooldbase, $userid);
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    
    my (%teamsort, %studname);
    while ( my $ref = $sth->fetchrow_hashref ) {
	my %r = %$ref;
	my $studnum = $r{studnum};

	# Get student name
	$sth1->execute($studnum);
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my ($ln, $fn) = $sth1->fetchrow;
	$teamsort{"$ln$fn$studnum"} = $studnum;
	$studname{$studnum} = qq{<b>$ln</b>, $fn};
    }

    
    
    print qq{<hr style="width:60ch;margin-left:0;">\n};
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<div style="margin:1em 0;font-weight:bold;font-size:120%;">School Term };
    print qq{<select name="term"><option value=""></option>\n};
    foreach my $term ( @terms ) {
	print qq{<option>$term</option>};
    }
    print qq{</select></div>\n};


    print qq{<table cellpadding="4" cellspacing="0" border="0">\n};
    print qq{<tr><th>Select Students</th></tr>\n};

    foreach my $key ( sort keys %teamsort ) {
	my $studnum = $teamsort{$key};

	print qq{<tr><td><input type="checkbox" name="$studnum" value="1">$studname{$studnum}</td></tr>\n};
    }
    
    print qq{</table>\n};
    
    print qq{<div style="margin:1em;"><input type="submit" value="$lex{Continue}"></div>\n};
    print qq{</form>\n};

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

    exit;

}



#--------------
sub getComments {
#--------------

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

    my $term = $arr{term};
    delete $arr{term};

    if ( not $term ) {
	print qq{<p>$lex{Error}: No Term Selected</p>\n};
	print qq{</body></html>\n};
	exit;
    }


    %teamstudents = %arr; # all other values in %arr are student numbers.

=head    
    # Student Teams with this userid
    my $sth = $dbh->prepare("select * from team where schooldbase = ? and userid = ?");
    $sth->execute($schooldbase, $userid);
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    
    my %teamstudents; # students for this user in teams
    while ( my $ref = $sth->fetchrow_hashref ) {
	my %r = %$ref;
	my $studnum = $r{studnum};
	#	print qq{<div>$r{firstname} $r{lastname} / $studnum / $r{jobtitle}</div>\n};
	$teamstudents{$studnum} = 1
    }
=cut


    
    my $sth1 = $dbh->prepare("select id,catnum from evmst_main where studnum = ?");
    my $sth2 = $dbh->prepare("select id, strategy from evmst_staff where userid = ? and mainid = ?"); 

    my $sth = $dbh->prepare("select * from special where school = ? order by lastname, firstname");
    $sth->execute($schooldbase);
    if ($DBI::errstr){ print $DBI::errstr; die; }

    my %goals; # goals{studnum}{mainid} = $strategy
    my %category; # category{mainid} = catnum (in subject table)
    while ( my $ref = $sth->fetchrow_hashref ) {
	my %r = %$ref;
	my $studnum = $r{studnum};
	if ( not $teamstudents{$studnum} ) { next; } # skip student if staff member not on team.
	
	push @students, $studnum;
	
	# Loop over all evmst_main records for this student and check if
	# this userid has a responsibility for this group of goals.

	# Get evmst_main record id and catnum
	$sth1->execute($studnum);
	if ($DBI::errstr){ print $DBI::errstr; die; }
	my ($mainid,$catnum) = $sth1->fetchrow;
	$category{$mainid} = $catnum;

	# check if any goals for this staff member
	$sth2->execute( $userid, $mainid);
	if ($DBI::errstr){ print $DBI::errstr; die; }
	my ($staffid,$strategy) = $sth2->fetchrow;
	if ( $staffid ) { # we have a hit; userid has a goal to report on.
	    $goals{$studnum}{$mainid} = $strategy;
	}
    }

    if ( not %goals ) {
	print qq{<h2 style="color:red;">No Goals Found</h2>\n};
	print qq{</body></html>\n};
	exit;
	
    } else {
	#    print qq{<div>A Member of these Student Teams: @students</div>\n};
    }


    my $sth1 = $dbh->prepare("select * from evmst_goal where mainid = ?");
    my $sth2 = $dbh->prepare("select * from evmst_main where catnum = ? and studnum = ?");

    my $sth3 = $dbh->prepare("select category from subject where catnum = ?");
    my $sth4 = $dbh->prepare("select catnum from evmst_main where studnum = ?");

    my $sth5 = $dbh->prepare("select term, mastery from evmst_mastery where goalid = ? order by term");
    my $sth6 = $dbh->prepare("select userid,strategy from evmst_staff where mainid = ?");

    # Note: Local School DB, not IEP DB.
    my $sth7 = $dbhlocal->prepare("select id, comment from iep_comment
       where goalid = ? and term = ? and author = ?");

    my $sth8 = $dbhlocal->prepare("select * from iep_comment
       where goalid = ? and term = ?"); # ignore userid, since we want all other comments for this goal, this term.
    

    my $sth = $dbh->prepare("select * from special where studnum = ?");

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

    
    
    foreach my $studnum ( @students ) { # not all will have goals

	if ( not $goals{$studnum} ) { next; } # skip any without goals for this userid.

	# Get Student Record
	$sth->execute( $studnum );
	if ($DBI::errstr){ print $DBI::errstr; die; }
	my $ref = $sth->fetchrow_hashref;
	my %r = %$ref;
    
	# Student / Term
	print qq{<h2 style="color:blue;">$r{firstname} $r{lastname} ($studnum) Term $term</h2>\n};

    
	my (%categorysort, %category);
	# Get his/her goal groups.
	$sth4->execute( $studnum) ;
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	while ( my $catnum = $sth4->fetchrow ) {
    
	    $sth3->execute( $catnum ) ;
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my $category = $sth3->fetchrow;
	    
	    $categorysort{"$category$catnum"} = $catnum;
	    $categorydesc{$catnum} = $category;
	}


	# Loop through all goals for this student.
	foreach my $catkey ( sort keys %categorysort ) {

	    my $catnum = $categorysort{$catkey};

	    $sth2->execute( $catnum, $studnum );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    my $evref = $sth2->fetchrow_hashref; 
	    my %evm = %$evref;
	    my $mainid = $evm{id};
	
	    print qq{<div style="font-size:120%;font-weight:bold;color:green;margin:0.5em;">};
	    print qq{$categorydesc{$catnum}</div>\n}; # ($catnum)

	
	    print qq{<table cellpadding="4" cellspacing="0" border="0" style="margin-bottom:0.4em;width:60ch;">\n};

	    # IF goals{studnum}{mainid} exists, we can display an entry form field

	    my $count = 1; # goal count to display
	    # get goals for this goal group (ie. category)
	    $sth1->execute( $mainid );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    while ( my $gref = $sth1->fetchrow_hashref ) {
		my %gr = %$gref;  # goal master.
		my $goalid = $gr{id};

		print qq{<tr><td class="bla">$count. $gr{description}</td><td style="width:20ch;">};
	
		# Now load the mastery records for this goal, if any
		$sth5->execute( $goalid );
		if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
		while ( my ($term, $mastery) = $sth5->fetchrow ) {
		    print qq{Term $term - $mastery<br>\n};
		}
		print qq{</td></tr>\n};

		if ( $goals{$studnum}{$mainid} ) { # we have persons responsible

		    # Responsible Staff
		    print qq{<tr><td colspan="2"><b>Responsible Staff</b>:};
		    my %staff;
		    # show the staff responsible
		    $sth6->execute( $mainid );
		    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
		    while ( my ($userid, $strategy) = $sth6->fetchrow ) {
			$staff{$userid} = $staffnames{$userid};
		    }
		    $staff = join(',', values %staff);
		    print qq{$staff</td></tr>\n};

		    
		    # Check for existing record (same goalid, same author, same term 
		    $sth7->execute( $goalid, $term, $userid );
		    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
		    my ($commentid,$comment) = $sth7->fetchrow;
		    
		    print qq{<tr><td colspan="2"><span style="font-weight:bold;color:green;">};
		    print qq{Comment - Term $term</span> };

		    if ( $count == 1 ) { print qq{Enlarge box by dragging on lower right handle, if necessary }; }
		    
		    if ( $commentid ) { # we have an existing record
			print qq{<textarea name="$commentid" rows="4" cols="100">$comment};
		    } else { # add new record
			print qq{<textarea name="$studnum:$catnum:$goalid:$term" rows="4" cols="100">};
		    }
		    print qq{</textarea></td></tr>\n};

		    # Any other comments for this goal
		    $sth8->execute( $goalid, $term );
		    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
		    my $first = 1;
		    while ( my $ref = $sth8->fetchrow_hashref ) {
			my %r = %$ref;
			if ( $r{author} eq $userid ) { next; } # skip existing user
			if ( $first ) {
			    print qq{<tr><td colspan="2"><span style="font-weight:bold;color:green;">};
			    print qq{Other Comments</span><br>\n};
			    $first = 0;
			}

			print qq{<b>$r{author}</b> $r{comment}<br>\n};
		    }
				    
		}

		# Blank row
		print qq{<tr><td colspan="2"><hr></td></tr>\n};

		$count++;
	    }
	    print qq{</table>\n};
	    print qq{<div style="margin:0 0.5em;"><input type="submit" value="$lex{Save} All"></div>\n};
	    
	}
	
	
    } # end of student loop

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

    exit;
    
} #end of get Comments


#----------------
sub writeComments { # into the evalprogress table (id, goalid, comment, term)
#----------------

    # passed values are id values for the goals (from evmst_goal table).
    # values are either goalid:term OR have the id only for the previous comment record.
#    foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }
#    print qq{<br>\n};

    # split passed values into the 2 groups: comment id or studnum:catnum:goalid:term
    my ( @existing, %newrec );
    foreach my $key ( sort keys %arr ) {

	my ($studnum, $catnum, $goalid, $term) = split(':', $key);

#	print "SN:$studnum / $catnum / $goalid / $term<br>\n";
	
	if ( not $term ) { # must be id of an existing comment record
	    push @existing, $studnum;  # REALLY id of record in the iep_comment table
	    
	} else { # we are adding a new record, if we have a comment
	    if ( not $arr{$key} ) { next; } # skip any empty comments.
	    $newrec{$key} = 1;
	}
    }

#    print qq{Existing:@existing<br>\n};
#    print qq{NewRec}, %newrec, qq{<br>\n};

    
    # insert new record
    my $sth = $dbhlocal->prepare("insert into iep_comment  (studnum, catnum, goalid, author, date, term, comment)
       values(?,?,?,?,?,?,?)");
    
    # update the comment
    my $sth1 = $dbhlocal->prepare("update iep_comment set comment = ? where id = ?");

    # delete the comment
    my $sth2 = $dbhlocal->prepare("delete from  iep_comment where id = ?");


    # Do the updates first
    foreach my $commentid ( @existing ) {
	my $comment = $arr{$commentid};

#	print "Comment ID:$commentid / $comment<br>\n";
	
	if ( not $comment ) { # erase the record
	    $sth2->execute($commentid);
	    if ($DBI::errstr){ print $DBI::errstr; die; }
	    print qq{<div><b>Deleted</b> Id $commentid</div>\n};
	    next;
	    
	} else { # we have an update
	    $sth1->execute($comment, $commentid);
	    if ($DBI::errstr){ print $DBI::errstr; die; }

	}
	print qq{<div><b>Updated:</b> $comment</div>\n};
    }

    
    # Add New Comment Records 
    foreach my $key ( keys %newrec ) {

	my $comment = $arr{$key};
	my ($studnum, $catnum, $goalid, $term) = split(':', $key);

#	print qq{<div>REC: $studnum / $catnum / $goalid / $userid / $date / $term / $comment</div>\n};
	
	$sth->execute($studnum, $catnum, $goalid, $userid, $date, $term, $comment);
	if ($DBI::errstr){ print $DBI::errstr; die; }

	print qq{<div><b>Added:</b> $comment</div>\n};

    }

    print qq{<h3>Records Added/Updated/Deleted</h3>\n};
    print qq{[ <a href="$homepage">$lex{Main}</a> |\n};
    print qq{<a href="$self">Add/Edit More</a> ]\n};
    
    print qq{</body></html>\n};
    
    exit;
}
