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

# Check the etc/coursemap.conf to make sure it's entered correctly.

my %lex = ('Main' => 'Main',
	   'Report Card' => 'Report Card',
	   'Grade' => 'Grade',
	   'Continue' => 'Continue',
	   'Error' => 'Error',
    );	   


use DBI;
use CGI;

my $self = 'checkPreCurrent.pl';


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

# load Course Map, also
eval require "../../etc/coursemap.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{Check Current Courses for Missing Prerequisites};
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{ <link rel="stylesheet" href="$css" type="text/css">\n};
print qq{$chartype\n</head><body>};

print qq{[ <a href="$homepage">$lex{Main}</a> | \n};
print qq{<a href="$reppage">$lex{'Report Card'}</a> ]\n};
print qq{<h1>$title - Find Credit Errors</h1>\n};

my %revmap = reverse %crsmap; # goes from code to shortname. %revmap{code} = shortname.


checkCurrentPrereq();



#---------------------
sub checkCurrentPrereq {
#---------------------

    # Load Course values needed
    # Reminder: crsmap{shortname} = coursecode;
    my %course; # all courses with prereq

#    foreach my $key ( sort keys %revmap ) {
#	print qq{K:$key VAL:$revmap{$key}\n};
#    }

    my %sort; # sort by grade and course title;
    
    # Load Course title, grade for prereq courses
    my $sth = $dbh->prepare("select title,grade from sasked_courses where code = ?");
    foreach my $code ( keys %revmap ) {

	# Get Course Title and Grade
	$sth->execute($code);
	if ($DBI::errstr){ print $DBI::errstr; die "$DBI::errstr\n"; }
	my ($title,$grade) = $sth->fetchrow;
	$sort{"$grade$title$code"} = $code;
	$course{$code} = $title;
    }


    my $sth1 = $dbh->prepare("select subjsec,startrptperiod,endrptperiod from subject
      where subjcode = ? order by subjsec");
    
    my $sth = $dbh->prepare("select distinct e.studnum from eval e, studentall s
      where subjcode = ? and s.studnum = e.studnum order by s.lastname,s.firstname");

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

    

    # Loop through each course, looking at their enrollments and making prereq's are found.
    my $count = 0;
    foreach my $key ( sort keys %sort ) {
	
	my $code = $sort{$key};
	my $shortname = $revmap{$code};
	my $pre = $prereq{$shortname};
	if ( not $pre ) { next; }
	
	
	my $first = 1;
	# Find all course sections for this subject
	$sth1->execute($code);
	if ($DBI::errstr){ print $DBI::errstr; die "$DBI::errstr\n"; }
	while ( my ($subjsec,$startterm, $endterm) = $sth1->fetchrow ) {
	    if ( not $first ) {
		print qq{<tr><th>$subjsec Trm $startterm-$endterm</th></tr>\n};
	    }
		
	    # find course enrollments for this course.
	    $sth->execute($subjsec);
	    if ($DBI::errstr){ print $DBI::errstr; die "$DBI::errstr\n"; }
	    while ( my $studnum = $sth->fetchrow ) {

		# Check for prerequisites here.
		if ( my $result = checkPrereq($studnum,$subjsec) ) {
		    if ( $first ) {
			print qq{<table cellspacing="0" cellpadding="3" border="1" };
			print qq{style="margin:1em;float:left;">\n};
			print qq{<caption style="font-size:120%;font-weight:bold;">};
			print qq{$course{$code} ($code)</caption>\n};
			print qq{<tr><th>Required  $pre</th></tr>\n};
			print qq{<tr><th>Section $subjsec Trm $startterm-$endterm</th></tr>\n};
			$first = 0;
		    }

		    # Get Name
		    $sth2->execute($studnum);
		    if ($DBI::errstr){ print $DBI::errstr; die "$DBI::errstr\n"; }
		    my ($ln,$fn) = $sth2->fetchrow;

		    # Show Result
		    print qq{<tr><td><b>$ln</b>, $fn ($studnum) - $result</td></tr>\n};
		}
		
	    }
	}

	if ( not $first ) {
	    print qq{</table>\n};
	    $count++;
	    if ( $count % 3 == 0 ) {
		print qq{<div style="clear:left;"></div>\n};
	    }
	}

    }

    print qq{<div style="clear:left;"></div>\n};
    print qq{<h3 style="margin:2em;">Missing Prerequisite Checking Complete.</h3>\n};

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

}




#--------------
sub checkPrereq {
#--------------

    # returns a failed course code, otherwise just a clean return.
    my ($studnum, $subjsec) = @_; # passed student and course
    my ($code,$section) = split('-', $subjsec);

    
    # Get name, provnum, program
    my $sth= $dbh->prepare("select lastname, firstname, provnum, program from studentall where studnum = ?");
    $sth->execute($studnum);
    if ($DBI::errstr){ print $DBI::errstr; die "$DBI::errstr\n"; }
    my ($ln,$fn,$provnum, $program) = $sth->fetchrow;
    if ( $program eq '09' ) {
#	print qq{<tr><td>Skipping $fn $ln ($studnum) - Adult Secondary</td></tr>\n};
	return;
    } # adult secondary program has no prerequisites
    
    my $sth2= $dbh->prepare("select * from sasked_completedcourses where provnum = ? and courseid = ?");

    my $shortname = $revmap{$code};
    my $prereq = $prereq{$shortname};

    if ( $prereq =~ m/or/ ) { # alternate course options
	my @prenames = split(/\s*or\s*/, $prereq);
		
	# Check to see if she/he has one of these courses; if so then display results to be fixed.
	# any passed course is enough to return
	foreach my $crsname ( @prenames ) {
	    my $crscode = $crsmap{ $crsname };
	    # Check if this course IS present and passed.
	    $sth2->execute($provnum, $crscode);
	    if ($DBI::errstr){ print $DBI::errstr; die "$DBI::errstr\n"; }
	    my $cref = $sth2->fetchrow_hashref;
	    my %c = %$cref;
	    if ( not %c or $c{creditsearned} == 0 ) {
		return qq{$crsname ($crscode)}; # return failed course code
	    } else { # we have a pass
		return; # nothing
	    }
		    
	} # end of prereq course loop for OR
	
	
    } elsif ( $prereq =~ m/and/ ) { # and condition
	my @prenames = split(/\s*and\s*/, $prereq);
	# Any one failure, will cause a return
	my @fails; # passed courses to fulfill prereq
	foreach my $crsname ( @prenames ) {
	    my $crscode = $crsmap{ $crsname };
	    $sth2->execute($provnum, $crscode);
	    if ($DBI::errstr){ print $DBI::errstr; die "$DBI::errstr\n"; }
	    my $cref = $sth2->fetchrow_hashref;
	    my %c = %$cref;
	    if ( $c{creditsearned} == 0 ) {
#		print qq{Code:$crscode Name:$crsname $c{creditsearned}<br>\n};
		push @fails, qq{$crsname ($crscode)};
	    }
	}
        if ( @fails ) {
	    my $failstring = join(',',@fails);
	    return $failstring;
	} else {
	    return; # nothing
	}


    } else { # only a single course prereq

	my $crscode = $crsmap{ $prereq };
	# Check to see if we have any prerequisite done
	$sth2->execute($provnum, $crscode);
	if ($DBI::errstr){ print $DBI::errstr; die "$DBI::errstr\n"; }
	while ( my $cref = $sth2->fetchrow_hashref ) { # they could have taken it several times....
	    my %c = %$cref;
	    if ( $c{creditsearned} > 0) { # we have the prereq and it's passed.
		return;
	    }
	}
	
	# if we got here without a clean return, return the course code
	return qq{$prereq ($crscode)};
    }

}
