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

#  This file is part of Open Admin for Schools.


my %lex = ('View' => 'View',
	   'Staff' => 'Staff',
	   'Absences' => 'Absences',
	   'Main' => 'Main',
	   'Eoy' => 'Eoy',
	   'No Records Found' => 'No Records Found',
	   'Error' => 'Error',
	   'Edit' => 'Edit',
	   'Delete' => 'Delete',

	   );


use DBI;
use CGI;
use Cwd;
use Number::Format qw{round};

my $self = 'mssTranscriptView.pl';


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 $dsn = "DBI:$dbtype:dbname=$dbase";
my $dbh = DBI->connect($dsn,$user,$password);



# Print Page Header
my $title = qq{View MSS Transcript Table (TRN Import)};
print qq{$doctype\n<html><head><title>$title</title>
 <link rel="stylesheet" href="$css" type="text/css">
 </head>\n};

print qq{<body style="margin:1em;">[ <a href="$homepage">$lex{Main}</a> |\n};
print qq{<a href="$exppage">Export</a> ]\n};

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

if ( not $arr{page} ) {
    showRecords();
} elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    updateMssid();
}

#--------------
sub updateMssid {
#--------------

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

    $sth = $dbh->prepare("update studentwd set mssid = ? where studid = ?");
    $sth1 = $dbh->prepare("select lastname, firstname, provnum, studnum
			  from studentwd where studid = ?");
    
    foreach my $key ( sort keys %arr ) {
	my ($studid,$mssid,$tb) = split(':',$key);

	$sth1->execute($studid);
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my ($ln,$fn,$provnum,$studnum) = $sth1->fetchrow;
	
	if ($tb) { # must be a 1 to be a withdrawn student update
	    $sth->execute($mssid, $studid);
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    print qq{<div>$fn $ln ($studnum / $provnum) mssid $mssid updated</div>\n};
	}

    }

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

    exit;
}



#--------------
sub showRecords {
#--------------

    my $sth = $dbh->prepare("show columns from mss_transcript");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    while (my @cols = $sth->fetchrow ) {
	if ( $cols[0] eq 'id' or $cols[0] eq 'comment' or
	     $cols[0] eq 'integrationid' or  $cols[0] eq 'grade') { next; }
	push @fields, $cols[0];
    }


    $sth = $dbh->prepare("select * from mss_transcript order by mssid, date");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    
    # Find name by mssid
    my $sth1 = $dbh->prepare("select lastname, firstname, studnum, provnum from studentall
			     where mssid = ?");

    # Find name by provnum
    my $sth2 = $dbh->prepare("select lastname, firstname, studnum from studentall
			     where provnum = ?");

    
    my $first = 1;
    my %found;
    
    while ( my $ref = $sth->fetchrow_hashref ) {
	my %r = %$ref;

	if ( $first ) { # do header
	    print qq{<table border="1" cellpadding="3" cellspacing="0" };
	    print qq{style = "float:left;margin:1em;">\n};
	    print qq{<caption style="text-align:left;">Skipping Blank Date Records</caption>\n};
	    print qq{<tr><th>Name</th>};
	    foreach my $fld (@fields ) {
		print qq{<th>$fld</th>\n};
	    }
	    print qq{</tr>\n};
	    $first = 0;
	}
	
	if ( $r{date} eq '0000-00-00' ) { # skip blank records
	    next;
	}

	if ( $r{mark} ) {
	    $r{mark} = round($r{mark},0);
	}

	if ( $r{credit} ) {
	    $r{credit} = round($r{credit},0);
	}

	
	# Get Name by MSSID
	$sth1->execute( $r{mssid} );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my ($ln,$fn,$studnum,$provnum) = $sth1->fetchrow;
	if ( not $ln ) {

	    my $res = findStudent( $r{mssid} );
	    my ($pn,$confcount) = split(':',$res); # confidence count, courses the same

	    if ( $pn ) { # Find Name, info
		$sth2->execute( $pn );
		if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
		($ln,$fn,$studnum) = $sth2->fetchrow;
		if ( $ln ) { # found name
		    $ln = qq{<span style="color:red;" title="Found my provnum, not aspenid">}.
		    qq{FND</span> $ln};
		    $provnum = $pn;
		    $found{"$pn:$r{mssid}:$confcount"} = 1;
		} else { # not found on lookup
		    $ln = qq{<span style="color:red;">PN:$pn Not found</span>};
		}
	    }
	}

    
	print qq{<tr>};
	if ( not $fn ) {
	    print qq{<td>$ln</td>};
	} else {
	    print qq{<td><b>$ln</b>, $fn ($provnum / $studnum)</td>\n};
	}
	foreach my $field ( @fields ) {
	    print qq{<td class="cn">$r{$field}</td>};
	}

	print qq{</tr>\n};
    }


    if ($first ) {
	print qq{<p>$lex{'No Records Found'}</p>\n};
	print qq{</body></html>\n};
	exit;
    
    } else { # close table
	print qq{</table>\n};
    }


    
    # Found Provincial Numbers to Verify on MSS
    my $sth = $dbh->prepare("select lastname, firstname, studnum, studid from studentall
			    where provnum = ?");
    my $sth1 = $dbh->prepare("select count(*) from studentwd where provnum = ?");

    my %sort;
    foreach my $found ( keys %found ) {
	my ($pn,$mssid,$confcount) = split(':',$found);
	
	$sth->execute( $pn );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my ($ln,$fn,$studnum, $studid ) = $sth->fetchrow;
	$sort{"$ln$fn$studnum"} = $found;
    }

# Turn off from here
=head    
    # Start Form
    print qq{<form action="$self" method="post">};
    print qq{<input type="hidden" name="page" value="1">\n};
    
    print qq{<div><input type="submit" value="Update Selected"></div>\n};

    
    print qq{<table border="1" cellpadding="3" cellspacing="0" style="float:left;margin:1em;">\n};
    print qq{<caption style="text-align:left;">Found Provincial Numbers - Verify on MSS</caption>\n};
    print qq{<tr><th>Name</th><th>Prov#</th><th>MSSID</th>};
    print qq{<th title="Number of Matching Courses">Matching</th>};
    print qq{<th>Update</th></tr>\n};

    foreach my $key ( sort keys %sort ) {
	my $found = $sort{$key};
	my ($pn,$mssid,$confcount) = split(':',$found);

	# Find name by provnum
	$sth->execute( $pn );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my ($ln,$fn,$studnum, $studid ) = $sth->fetchrow;
	if ( not $ln ) { $ln = qq{<span style="color:red;">Not Found</span>}; }

	# Check if withdrawn
	$sth1->execute( $pn );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my $wd = $sth1->fetchrow;
	
	print qq{<tr><td><b>$ln</b>, $fn ($studnum)</td><td>$pn</td><td>$mssid</td>};
	print qq{<td class="cn">$confcount</td>};

	my $val = qq{$studid:$mssid:$wd};
	print qq{<td><input type="checkbox" name="$val" value="1"></td>\n};
	
#	print qq{<td><form action="/cgi-bin/studed.pl" method="post" target="_blank" };
#	print qq{style="display:inline;">\n};
#	print qq{<input type="hidden" name="id" value="$studid">\n};
#	if ( $wd ) {
#	    print qq{<input type="hidden" name="tb" value="wd">\n};
#	}
#	print qq{<input type="submit" name="submit" value="Edit"></form></td>};

	
	print qq{</tr>\n};

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

    print qq{</form>\n};
=cut    

    print qq{<div style="clear:left;"></div>\n};
    print qq{<p>[ <a href="$homepage">$lex{Main}</a> |\n};
    print qq{<a href="$exportpage">Export</a> ]</p>\n};

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

    exit;

}

#--------------
sub findStudent {
#--------------

    my $mssid = @_[0];

    # Get courses in mss_transcript with this mssid;
    my %courses; # courses this student has taken, to try to match.
    # courses{coursecode}{mark} = date
    my $sth = $dbh->prepare("select * from mss_transcript where mssid = ?");
    $sth->execute( $mssid );
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $ref = $sth->fetchrow_hashref ) {
	my %c = %$ref;
	$c{mark} =~ s/\.00//;
	$courses{ $c{coursecode} }{ $c{mark} }{ $c{date} } = 1;
    }


    # now look in normal transcripts (sasked_completedcourses) for a matching student.
    my $sth = $dbh->prepare("select provnum from sasked_completedcourses 
			    where courseid = ? and finalmark = ?");

    my %match; # match{provnum}{crs} = mark;
    foreach my $crs ( sort keys %courses ) {
	foreach my $mark ( sort keys %{ $courses{$crs}} ) {

	    if ( $mark < 2 ) { next; }  # some students have 1 as a DUD mark.
	    
	    $sth->execute( $crs,$mark );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    while ( my $provnum = $sth->fetchrow ) {
		if ( $provnum ) {
		    $match{$provnum}{$crs} = $mark;
		}
	    } # end of loop populating %match

	} # end of mark loop
    }

    my ($maxcount, $bestpn);
    foreach my $provnum (sort keys %match ) {
	foreach my $crs ( sort keys %{$match{$provnum}} ) {
#	    print qq{PN:$provnum CRS:$crs<br>\n};
	}
	my $count = scalar keys %{$match{$provnum}};
	if ($count > $maxcount) {
	    $maxcount = $count;
	    $bestpn = $provnum;
	}
#	print qq{Count:$count<br>\n};
    }

#    print "Best PN:$bestpn<br><br>\n";
    
    return qq{$bestpn:$maxcount};


}


    
