#!/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 = 'mssCourseView.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);
$dbh->{mysql_enable_utf8} = 1;


# Print Page Header
my $title = qq{View MSS Current Courses};
print qq{$doctype\n<html><head><title>$title</title>
 <link rel="stylesheet" href="$css" type="text/css">
 </head>\n};

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

print qq{<form action="$self" method="post">\n};
print qq{<input type="hidden" name="sort" value="course">\n};
print qq{<input type="submit" value="Sort by Course"></form>\n};

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



showRecords();


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

#  We are only using 2 fields from mss_currcourse: mssid and coursecode.    
#    my @fields;
#    my $sth = $dbh->prepare("show columns from mss_currcourse");
#    $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 'date' or $cols[0] eq 'credit' or
#	     $cols[0] eq 'integrationid' or  $cols[0] eq 'mark') { next; }
#	push @fields, $cols[0];
#    }

    
    # Setup Queries
    # Get student name
    my $sth1 = $dbh->prepare("select lastname, firstname, studnum, provnum from studentall
			     where mssid = ?");

    # Get course description
    my $sth2 = $dbh->prepare("select title,grade from sasked_courses where code = ?");
    
    my $sort =  qq{order by mssid, coursecode};
    if ( $arr{sort} eq 'course' ) {
	$sort = qq{order by coursecode,mssid};
    }

    
    my $sth = $dbh->prepare("select * from mss_currcourse $sort");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    
    # Start Table
    my $first = 1;
    my %courses; # courses{coursecode} = title:grade;

    # Loop through records
    while ( my $ref = $sth->fetchrow_hashref ) {
	my %r = %$ref;


	if ( $first ) {
	    print qq{<table border="1" cellpadding="3" cellspacing="0">\n};
#	    print qq{<caption style="text-align:left;">Skipping Blank Date Records</caption>\n};
    
	    # Table Headings
	    print qq{<tr><th>Student</th><th>MSSID</th><th>Course</th></tr>\n};
	    $first = 0;
	}


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

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

	# Get Name
	$sth1->execute( $r{mssid} );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my ($ln,$fn,$studnum,$provnum) = $sth1->fetchrow;
	if ( not $ln ) {
	    my $pn = findStudent( $r{mssid} );
	    $ln = qq{<span style="color:red;">PN:$pn Not found</span>};
	}

	if ( not $courses{ $r{coursecode} }) { # populate the hash
	    $sth2->execute( $r{coursecode} );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    my ($title,$grade) = $sth2->fetchrow;
	    $title =~ s/\://;
	    $courses{ $r{coursecode} } = qq{$title:$grade};
	}
	my ($title,$grade) = split(':', $courses{$r{coursecode}});


	
	#	$first = 0;
	# Name
	print qq{<tr>};
	if ( not $fn ) {
	    print qq{<td>$ln</td>};
	} else {
	    print qq{<td><b>$ln</b>, $fn ($provnum / $studnum)</td>\n};
	}

	# mssid and course
	
	print qq{<td class="cn">$r{mssid}</td>};
	print qq{<td class="la">$title ($r{coursecode}/Gr $grade)</td></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};
    }


    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 @level1;
    foreach my $crs ( sort keys %courses ) {
	foreach my $mark ( sort keys %{ $courses{$crs}} ) {
	    if ( not $mark ) { next; }
	    $sth->execute( $crs,$mark );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    while ( my $provnum = $sth->fetchrow ) {
		if ( $provnum ) {
		    push @level1, $provnum;
		}
	    }
	}
    }

    if ( not @level1 ) {
	return;
    }
    
    return $level1[0];


#    return $provnum;
}


    
