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

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;

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

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


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



my $title = qq{Student IEP Progress Report - 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 {
#----------------

    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<p>Please select School Term <select name="term"><option value=""></option>\n};
    foreach my $term ( @terms ) {
	print qq{<option>$term</option>};
    }
    print qq{</select></p>\n};
    print qq{<input type="submit" value="$lex{Continue}">\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;
    }

    
    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)
    my @students;
    while ( my $ref = $sth->fetchrow_hashref ) {
	my %r = %$ref;
	my $studnum = $r{studnum};
	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 = ?");

    my $sth7 = $dbh->prepare("select id, comment from evalprogress where goalid = ? and 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;
    
	# Subtable - left side - student info
	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{<h3>$categorydesc{$catnum}</h3>\n}; # ($catnum)

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

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

	    # 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>$gr{description}</td><td>};
	
		# Now load the mastery records for this goal
		$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
		    
		    print qq{<tr><td colspan="2"><b>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 ) {
			push @staff, $staffnames{$userid};
		    }
		    $staff = join(',', @staff);
		    print qq{$staff</td></tr>\n};

		    # Check for an existing record
		    $sth7->execute( $goalid, $term );
		    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
		    my ($id,$comment) = $sth7->fetchrow;
		    
		    print qq{<tr><td colspan="2"><span style="font-weight:bold;color:green;">};
		    print qq{Comment:</span> Enlarge box by dragging on lower right handle, };
		    print qq{if necessary<br>\n};
		    if ( $id ) { # we have an existing record
			print qq{<textarea name="$id" rows="4" cols="100">$comment};
		    } else { # add new record
			print qq{<textarea name="$goalid:$term" rows="4" cols="100">};
		    }
		    print qq{</textarea></td></tr>\n};
		}
	    
	    }
	    print qq{</table>\n};
	    
	}
	
	print qq{<div><input type="submit" value="$lex{Save}"></div>\n};
	
    } # end of student loop

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

    exit;
    
} #end of get Comments


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

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

    # insert
    my $sth = $dbh->prepare("insert into evalprogress (goalid,comment,term) values(?,?,?)");
    
    # update comment
    my $sth1 = $dbh->prepare("update evalprogress set comment = ? where id = ?");

    
    foreach my $key ( keys %arr ) {
	if ( not $arr{$key} ) { next; } # skip any blank comments
	
	my ($goalid, $term) = split(':', $key );
#	print "KEY:$key Goal:$goalid Term:$term Comment:$arr{$key}<br>\n";

	# Check for existing record and update.
	if ( not $term ) { # we have an existing record, since split above only single value
	    print qq{<div>Updating Record - $arr{$key}</div>\n};
	    $sth1->execute($arr{$key}, $key); # key is ID here
	    if ($DBI::errstr){ print $DBI::errstr; die; }

	} else { # we are adding a new record
	    print qq{<div>Adding Record - $arr{$key}</div>\n};
	    $sth->execute($goalid, $arr{$key}, $term);
	    if ($DBI::errstr){ print $DBI::errstr; die; }
	}
    }

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

    exit;
}
