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

#  This file is part of Open Admin for Schools.

#  Open Admin for Schools is free software; you can redistribute it 
#  and/or modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2 of 
#  the License, or (at your option) any later version.

my %lex = ('Assessment Entry' => 'Assessment Entry',
	   'Terms' => 'Terms',
	   'System Disabled. Please contact secretary' => 
	     'System Disabled. Please contact secretary',
	   'Grade' => 'Grade',
	   'Please Log In' => 'Please Log In',
	   'No User Id' => 'No User Id',
	   'No Password' => 'No Password',
	   'Main' => 'Main',
	   'Duration' => 'Duration',
	   'No Courses Found' => 'No Courses Found',
	   'Error' => 'Error',
	   'Course' => 'Course',

	   );

use DBI;
use CGI::Session;
use CGI;

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

eval require "../../lib/libsession.pl"; # contains login/ checkPassword/ checkCookieTime functions
if ( $@ ) {
    print $lex{Error}. " $@<br>\n";
    die $lex{Error}. " $@<br>\n";
}



my $q = CGI->new;
my %arr = $q->Vars;

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



# Get Session Information...
my $session = new CGI::Session("driver:mysql;serializer:FreezeThaw",
 undef,{Handle => $dbh}) or die CGI::Session->errstr;

# Get/Set  Session Values (a defined userid means it was passed)

my ($userid, $duration);
if ( $arr{userid} ){ # we want to login, passed userid/password pair.

    # Check password/userid against database (-1 no user, -2 wrong password;
    my $error = checkPassword($arr{userid}, $arr{password}, $dbh);
    if ($error == -1){ print $q->header( -charset, $charset ); login( $lex{'No User Id'}); }
    if ($error == -2){ print $q->header( -charset, $charset ); login($lex{'No Password'}); }

    $cookietime = checkCookieTime( $arr{duration} );

    # Set values for userid and logged_in in session
    $session->param('logged_in','1');
    $session->expire('logged_in',$cookietime );
    $session->param('userid', $arr{userid} );
    $session->param( 'duration', $cookietime );

    $userid = $arr{userid};
    $duration = $cookietime;

} else { # check logged_in value in session

    if ( not $session->param('logged_in') ){
	$userid = $session->param('userid');
        print $q->header( -charset, $charset );
        login( $lex{'Please Log In'}, $userid ); 
    }
    # Ok, we have a login. Values below we have in environment.

    $userid = $session->param('userid');
    $duration = $session->param('duration');
    if ( not ($duration =~ /\+/)) { # if not in +20m format, do so.
	$duration = checkCookieTime( $duration );
    }
    $session->expire('logged_in',$duration); # duration is in +20m format;

} # End of check for logged_in value

print $session->header( -charset, $charset );


# Print HTML Header
my $title = $lex{'Assessment Entry'};
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$tchcss" type="text/css">\n};

print qq{$chartype\n</head><body>\n};
print qq{[ <a href="$tchpage">$lex{Main}</a> ]\n};
print qq{$lex{Duration}: $duration<br>\n};

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


# Load configuration value
my $sth = $dbh->prepare("select * from conf_system where filename = 'repcard' 
			and sectionname = 'Config'");
# loads r_MarkEntryTerm, also
$sth->execute;
if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

while ( my $ref = $sth->fetchrow_hashref ) {

    # put value into namespace
    eval $ref->{datavalue};
    if ( $@ ) {
	print $lex{Error}. " $@<br>\n";
	die $lex{Error}. " $@\n";
    }
}


# Disable entry if all tracks set to zero entry term.
my $disableentry = 1; # stop entry by default.
foreach my $trk ( sort keys %g_MTrackTerm ){
    if ( $r_MarkEntryTerm{$trk} ) { $disableentry = 0; } # any nonzero value to enable mark entry.
}

if ( $disableentry ) { # only if all tracks are zero
    print qq{<h3>$lex{'System Disabled. Please contact secretary'}</h3></body></html>\n};
    exit;
}


# Convert track->entry term to grade-> entry term.
#my %gradeterms;
#foreach my $gr ( keys %g_MTrackTermType ) { # key is grade, value is track
#    my $trk = $g_MTrackTermType{$gr};
#    $gradeterms{$gr} = $r_MarkEntryTerm{$trk}; # gives grade -> entry term;
#}


showSubjects( $userid );



#---------------
sub showSubjects {  # show the teacher his/her subjects
#---------------

    my $userid = shift; # passed teacher userid.


    my $sth = $dbh->prepare("select sal, firstname, lastname from staff where userid = ?");
    $sth->execute( $userid );
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
    my ($sal, $firstname, $lastname) = $sth->fetchrow;
    print "<h1>$sal $firstname $lastname</h1>\n";


    # Load the SupressSubject data
    $sth = $dbh->prepare("select datavalue from conf_system where dataname = ?");
    $sth->execute( 'r_SupressSubject');
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
    my $dv = $sth->fetchrow;
    eval $dv;


    my @subjects;
    my %subjectname;
    my %subjectentryterm;
    my %subjectentrytrack;
    my %sortsubject;

    $sth = $dbh->prepare("select subjsec, grade from subject 
			 where teacher = ? and ? >= startrptperiod and ? <= endrptperiod ");

    
    foreach my $trk ( sort keys %g_MTrackTerm ) {
	if ( $r_MarkEntryTerm{$trk} == 0 ) { next; } # skip if this track has entry term set to zero.
	my $term = $r_MarkEntryTerm{$trk};

	$sth->execute( $userid, $term, $term ); # find subjects this term (set for this track)
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	while ( my ($subjsec, $grade ) = $sth->fetchrow ) {
	    
	    if ( $g_MTrackTermType{$grade} != $trk ) { next; } # skip if grade not on this track.

	    push @subjects, $subjsec;
#	    print "Sub:$subjsec Track:$trk Term:$term<br>\n";
	    $subjectentryterm{$subjsec} = $term;
	    $subjectentrytrack{$subjsec} = $trk;
	}
    }
    # now have all subjsecs in @subjects;


    $sth = $dbh->prepare("select description, grade, subjcode, startrptperiod, endrptperiod 
			 from subject where subjsec = ?");
    my (%coursegrades, %courseterms);
    
    foreach my $subjsec ( @subjects ) {
	$sth->execute( $subjsec );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	my ($desc, $grade, $subjcode, $startterm, $endterm ) = $sth->fetchrow;
	$sortsubject{"$desc$subjsec"} = $subjsec;
	$subjectname{$subjsec} = $desc;
	$coursegrades{$subjsec} = $grade;
	$courseterms{$subjsec} = "$startterm-$endterm";
    }


    # Start the Table Layout
    print qq{<table cellspacing="0" cellpadding="3" border="0" style="border:1px solid gray;">\n};
    print qq{<caption style="font-weight:bold;">Click on Course Name</caption>\n};
    print qq{<tr><th>$lex{Course}</th><th>$lex{Grade}</th><th>$lex{Terms}</th></tr>\n};
    
    my $first = 1;
    foreach my $key ( sort keys %sortsubject ) {

	my $subjsec = $sortsubject{$key};
	my ($subjcode, $dud) = split(/-/, $subjsec);

	if ( $r_SupressSubject{ $subjsec } or $r_SupressSubject{ $subjcode } ) { next; }

		
	print qq{<tr><td><form action="markadd1.pl" method="post">\n};
	print qq{<input type="hidden" name="subjsec" value="$subjsec">\n};
	print qq{<input type="hidden" name="entryterm" value="$subjectentryterm{$subjsec}">\n};
	print qq{<input type="hidden" name="track" value="$subjectentrytrack{$subjsec}">\n};
	print qq{<input type="submit" value="$subjectname{$subjsec} ($subjsec)"></form></td>\n};
	print qq{<td>$coursegrades{$subjsec}</td><td>$courseterms{$subjsec}</td></tr>\n};
	$first = 0;

    }


    if ( $first ) { # no records
	print qq{<tr><td>$lex{'No Courses Found'}</td></tr>\n};
    }

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

} # end of showSubjects
