#!/usr/bin/perl
#  Copyright 2001-2025 Leslie Richardson
#  This file is part of Open Admin for Schools.

use DBI;
use CGI;


my $self = 'sendmarksMSS.pl';

# Used for Filename Date
my @smonth = ('', 'JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC');

my %lex = ( 'Main' => 'Main',
	    'Error' => 'Error',
	    );


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

#eval require "./slxmllibNew.pl";
#if ( $@ ) {
#    print $lex{Error}. " $@<br>\n";
#    die $lex{Error}. " $@\n";
#}

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

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



my @tim = localtime(time);
my $year = $tim[5] + 1900;
$tim[4]++;
$tim[6]++; # wday; not used.

# For Filename
my $fyear = $year - 2000;
my $filecurrdate = $tim[3]. $smonth[ $tim[4] ]. $fyear;
my $filecurrtime = $tim[2]. $tim[1];
# End of filename specific time

for (0..4){if (length($tim[$_]) == 1){ $tim[$_] = '0'.$tim[$_];}}
my $currdate = "$year-$tim[4]-$tim[3]";
my $currtime = "$tim[2]:$tim[1]:$tim[0]";

my $title = qq{Create MSS Student Marks File};
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">$chartype\n};
print qq{</head><body style="margin:1.5em;">[ <a href="$homepage">Main</a> |\n};
print qq{<a href="$reppage">Report Card</a> ]\n};
print qq{<h1>$title</h1>\n};

if ( not $arr{page} ) {
    showStartPage();

} elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    selectStudents();

} elsif ( $arr{page} == 2 ) {
    delete $arr{page};
    sendMarks();
}



#----------------
sub showStartPage {
#----------------

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

    # Minimum Mark
    print qq{<div style="margin:0.4em;">Minumum Mark <input type="text" style="width:4ch;" };
    print qq{name="minmark" value="35"><br>\n};
    print qq{Check Next Page <input type="checkbox" name="checked" value="checked"></div>\n};

    
    print qq{<div><input type="submit" value="Continue"></div>\n};
    
    print qq{<table cellpadding="3" border="1" cellspacing="0">\n};

    
    print qq{<tr><th>Subject</th><th>Code-Sec</th><th>Terms</th><th>Teacher</th>};
    print qq{<th>Grade</th><th>Enrol</th><th>Select</th></tr>\n};

    my $sth1 = $dbh->prepare("select count(distinct studnum) from eval where subjcode = ?");

    my $sth2 = $dbh->prepare("select firstname, lastname from staff where userid = ?");
    
    my $sth = $dbh->prepare("select description, grade, teacher, subjsec, startrptperiod, endrptperiod from subject 
     where grade = '10' or grade = '11' or grade = '12' order by startrptperiod, endrptperiod, grade, description");
    $sth->execute;
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }

    my ($currterms, $prevterms);


    while ( my ( $description, $grade, $teacher, $subjsec, $startterm, $endterm ) = $sth->fetchrow ) {

	if ( $currterms ) {
	    $prevterms = $currterms;
	}
	$currterms = "$startterm-$endterm";

	if ( $prevterms and $prevterms ne $currterms ) { 
	    print qq{<tr><td colspan="7" style="background-color:#888;"></td></tr>\n};
	}

	
	# skip if no enrollments.
	$sth1->execute( $subjsec );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	my $count = $sth1->fetchrow;
	if ( not $count ) { next; }; 

	$sth2->execute( $teacher );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	my ($fn,$ln) = $sth2->fetchrow;
	

	if ( not $teacher ){ $teacher = "<font color=red>No Teacher</font>"; }
	print qq{<tr><td>$description</td><td>$subjsec</td><td>$startterm-$endterm</td>};
	print qq{<td>$fn $ln ($teacher)</td><td>$grade</td><td>$count</td>\n};
	print qq{<td><input type="checkbox" name="$subjsec" value="1" $checked></td></tr>\n};
	
    }

    
    print qq{<tr><td colspan="7">};
    print qq{<input type="submit" value="Continue">};
    print qq{<input type="checkbox" name="checked" value="checked">Check Next Page\n};
    print qq{</td></tr>\n};

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

    exit;

}


#-----------------
sub selectStudents {
#-----------------
    
    # passed a list of subjects to submit marks for.
    my $checked;
    if ( $arr{checked} ) {
	$checked = qq{checked = "checked"};
    }
    delete $arr{checked};

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

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

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

    print qq{<div style="font-weight:bold;">Minumum Mark $minmark</div>\n};

    
    print qq{<p><input type="submit" value="Create Student Marks File"></p>\n};

    my $count;
    foreach my $subjsec ( sort keys %arr ){

	# Get Subject Name
	my $sth = $dbh->prepare("select description, endrptperiod from subject where subjsec = ?");
	$sth->execute( $subjsec );
	if ($DBI::errstr) { print $DBI::errstr; die;}
	my ($subjectname, $endterm) = $sth->fetchrow;

	# Get Enrolled Students List
	$sth = $dbh->prepare("select distinct eval.studnum,studentall.lastname,
         studentall.firstname from eval,studentall where
         studentall.studnum = eval.studnum and eval.subjcode = ?
         order by studentall.lastname, studentall.firstname");

	$sth->execute( $subjsec );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my $rows = $sth->rows;
	if ($rows < 1){ next;}

	# print qq{<h3>$subjectname ($subjsec)</h3>\n};
	print qq{<table cellpadding="3" cellspacing="0" border="1" style="float:left;margin:1em;">\n};
	print qq{<caption style="font-weight:bold;font-size:120%;">$subjectname ($subjsec)</caption>\n};
	print qq{<tr><th>Name</th><th>Mark</th><th>Select</th></tr>\n};

	# Prep for checking existence in table.
	my $sth1 = $dbh->prepare("select count(studid) from studentwd where studnum = ?");
	my $sth2 = $dbh->prepare("select a1 from eval where studnum = ? and subjcode = ? and term = ?");

	
	while ( my ( $studnum,$lastname,$firstname ) = $sth->fetchrow ) {

	    # Check if enrolled!
	    $sth1->execute( $studnum );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    my $count = $sth1->fetchrow;
	    my $wd;
	    if ( $count ) { $wd = qq{<span style="color:red;font-weight:bold;">WD</span>\n}; }

	    # Get mark to be sent
	    $sth2->execute( $studnum, $subjsec, $endterm );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    my $mark = $sth2->fetchrow;

	    $mark =~ s/\%//; # strip any percent signs;
	    my $hasletters = 0; # if the mark contains no A-Z letters;
	    if ( $mark =~ m/[a-zA-Z]/ ) {
		$hasletters = 1;  # it HAS letters in it.
	    }
	    
	    print qq{<tr><td class="la">$wd <b>$lastname,</b> $firstname</td><td>$mark</td>\n<td>};
	    if ( $mark and not $hasletters ) {

		if ( $mark < $minmark ) { # no check box option>
		    print qq{<span style="color:red;">$mark</span>\n};
		} else {
		    print qq{<input type="checkbox" name="$subjsec:$studnum" value="1" $checked>};
		}
	    }
	    print qq{</td></tr>\n};


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

	$count++;

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

    print qq{<p style="clear:left;"><input type="submit" value="Create Student Marks File"></p>\n};
    print qq{</form></body></html>\n};

    exit;

} # end of selectStudents



#------------
sub sendMarks {  # actually just create the export file
#------------

    use Text::CSV_XS;

    my $csv = Text::CSV_XS->new( {binary => 1} );

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

#    print "School Year:$schoolyear<br>\n";
#    print "School Number:$schoolnumber<br>\n";

    my ($sy,$ey) = split('-',$schoolyear);
    my $year = $ey; # testing; changed to end year.
    

    my $filename = 'MARKS_'. $schoolnumber. '_'. $filecurrdate. '_'. $filecurrtime. '.txt';
    open(FH,">",$filename) or die "Cannot Open CSV file\n";

    # Write the Header
    print FH qq{"StudentGUID","SchoolID","YearID","CourseCode","SubSection","ReportingTermNumber","FinalGrade"\r\n}; 

    my $studcount = 1;
    
    # Main Loop - once for each student-subject.
STUDENT:
    foreach my $key ( sort keys %arr ) {

	my ( $subjsec, $studnum ) = split ':',$key;

	# Get Student Bdate and ProvNum, and Name
	$sth = $dbh->prepare("select lastname, firstname, provnum,birthdate, mssid, grade
               from studentall where studnum = ?");
	$sth->execute( $studnum );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my ($lastname, $firstname, $provnum,$bdate, $mssid, $grade) = $sth->fetchrow;
	my $name = "<b>$lastname</b>, $firstname ($studnum)";
	
	if ( not $mssid or not $provnum ) {
	    print qq{<div style="font-weight:bold;font-size:120%;margin:0.5em;">};
	    print qq{Missing Data: $name / Provnum: $provnum / MSSid: $mssid</div>\n};
	    next STUDENT;
	}
	    
	# Get Course Data
	my $sth = $dbh->prepare("select subjcode, section, description, subjsec, 
             	startrptperiod, endrptperiod, grade from subject where subjsec = ?");
	$sth->execute( $subjsec );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	my ( $subjcode, $section, $description, $subjsec, $startterm, $endterm, $grade ) = $sth->fetchrow;


	# test
	# $endterm = 1;
	
#	    my $subject = "$description ($subjsec)";

	# Get Mark Information
	# Need subject/section (subjsec), studnum, and end term
	$sth = $dbh->prepare("select a1 from eval where subjcode = ? and term = ? and studnum = ?");
	$sth->execute( $subjsec, $endterm, $studnum );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my $mark = $sth->fetchrow;

	if ( not $mark ) {
	    print qq{<div style="font-weight:bold;font-size:120%;margin:0.5em;">};
	    print qq{<b>No Mark found</b> for <b></b> in course $description ($subjsec)</div>\n};
	    next STUDENT;
	}

	# Get rid of spaces and any percent symbols.
	$mark =~ s/\%//;
	$mark =~ s/^\s+//;
	$mark =~ s/\s+$//;

	print "$studcount. $firstname $lastname GR: $grade MSS:$mssid PN:$provnum Grad Yr:$year<br>\n";
	$studcount++;

	my @line;
	push @line, $mssid;
	push @line, $schoolnumber;
	push @line, $year;
	push @line, $subjcode;
	push @line, $section;
	push @line, $endterm;
	push @line, $mark;
	
	# qq{'$mssid','$schoolnumber',$year,$subjcode,'$section',$endterm,'$mark'\n};

	if ( $csv->combine( @line ) ) {
	    my $record = $csv->string;
	    print FH $record, "\r\n";

	} else {
	    my $err = $csv->error_input;
	    print qq{Combine failed: $err\n\n};
	}

	# print FH qq{'$mssid','$schoolnumber',$year,$subjcode,'$section',$endterm,'$mark'\n};
    
    } # End of this student-subjsec


    close FH;
	
    # File upload stuff here.
    system("mv $filename $downloaddir");

    print qq{<h1>View/Download Mark File</h1>\n};
    print qq{<div style="font-size:120%;">[ <a href="$webdownloaddir/$filename">$filename</a> ]</div>\n};
	
        
    print qq{</body></html>\n};

    exit;

}

