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

#  This file is part of Open Admin for Schools.

my %lex = ('Add Transcript Records' => 'Add Transcript Records',
	   'Report Card' => 'Report Card',
	   'Main' => 'Main',
	   'Save Transcript Records' => 'Save Transcript Records',
	   'Student' => 'Student',
	   'Search' => 'Search',
	   'Student (Last,First/Last/Initials/Studnum)' => 
	     'Student (Last,First/Last/Initials/Studnum)',
	   'No Student(s) Found' => 'No Student(s) Found',
	   'Please search again' => 'Please search again',
	   'Action' => 'Action',
	   'Add Record' => 'Add Record',
	   'Subject Code' => 'Subject Code',
	   'Subject Name' => 'Subject Name',
	   'Subject Area' => 'Subject Area',
	   'Mark' => 'Mark',
	   'Letter Grade' => 'Letter Grade',
	   'Difficulty' => 'Difficulty',
	   'School Year' => 'School Year',
	   'Credits' => 'Credits',
	   'Term' => 'Term',
	   'Term Description' => 'Term Description',
	   'Transcript Record Added' => 'Transcript Record Added',
	   'Add More Transcript Records' => 'Add More Transcript Records',
	   'Missing Information' => 'Missing Information',
	   'Override' => 'Override',
	   'Error' => 'Error',

	   );

my $idfield = 'provnum'; # change to suit the fields using for state/provincial education #

my $self = 'tscadd.pl';
my $maxRecords = 6;  # Number of entry forms for courses for this student...
my $maxyears = 6; # maximum number of school years to go back.

use DBI;
use CGI;

# Read config variables; normally runs in /cgi/repcard
eval require "../../etc/admin.conf";
if ( $@ ) {
    print $lex{Error}. ": $@<br>\n";
    die $lex{Error}. ": $@\n";
}

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

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


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


# Print Page Header
my $title = $lex{'Add Transcript Records'};

print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{</title>\n<link rel="stylesheet" href="$css" type="text/css">
$chartype\n</head>\n};

print qq{<body>[ <a href="$homepage">$lex{Main}</a> |\n};
print qq{<a href="$reppage">$lex{'Report Card'}</a> ]\n};

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

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

} elsif ( $arr{page} == 1 ) {
    selectStudent( $arr{student} );

} elsif ( $arr{page} == 2 ) {
    enterRecord( $arr{studnum} );

} elsif ( $arr{page} == 3 ) {
    delete $arr{page};
    addRecord();
}



#--------------
sub enterRecord {
#--------------

    my $studnum = shift;

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

    # Get the student name
    my $sth = $dbh->prepare("select lastname, firstname from studentall where studnum = ?");
    $sth->execute( $studnum );
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    my ($lastname, $firstname) = $sth->fetchrow;

    # Get the terms
    my @terms;
    my $sth = $dbh->prepare("select distinct term from tscriptdata 
      where term is not null and term != ''");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    while (my $trm = $sth->fetchrow ) {
	push @terms, $trm;
    }

    # Get the credits
    my @credits;
    my $sth = $dbh->prepare("select distinct credit from tscriptdata 
     where credit is not null and credit != ''");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    while (my $cred = $sth->fetchrow ) {
	push @credits, $cred;
    }


    # Do the school years
    my @years;
    my ($prevyear, $curryear) = split /-/, $schoolyear; # defined in admin.conf
    foreach (1..$maxyears) {
	$tmp = $prevyear--;
	my $year = $prevyear. '-'. $tmp;
	push @years, $year;
    }


    # Start the form.
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="3">\n};
    print qq{<input type="hidden" name="studnum" value="$studnum">\n};
    print qq{<div style="padding:0.3em;">\n};
    print qq{<input type="submit" value="$lex{'Save Transcript Records'}"></div>\n};


    print qq{<table cellpadding="5" cellspacing="0" border="1">\n};

    print qq{<tr><td class="bra">$lex{'Student'}</td><td class="la">};
    print qq{<b>$firstname $lastname</b></td></tr>\n};

    print qq{<tr><td class="bra">$lex{'Subject Code'}</td><td class="la">};
    print qq{<input type="text" name="subjectcode" size="12"></td></tr>\n};

    print qq{<tr><td class="bra">$lex{'Subject Name'}</td><td class="la">};
    print qq{<input type="text" name="subjecttext" size="20"></td></tr>\n};

    print qq{<tr><td class="bra">$lex{'Subject Area'}</td><td class="la">};
    print qq{<select name="subjectarea"><option></option>\n};
    foreach my $area (sort keys %gradRequirements) {
	print qq{<option>$area</option>};
    }
    print qq{</select></tr></td>\n};
    #print qq{<input type="text" name="subjectarea" size="20"></td></tr>\n};


    print qq{<tr><td class="bra">$lex{Mark}</td><td class="la">};
    print qq{<input type="text" name="score_mark" size="6"></td></tr>\n};


    print qq{<tr><td class="bra">$lex{'Letter Grade'}</td><td class="la">};
    print qq{<select name="score_letter"><option></option>\n};
    foreach my $letter (sort keys %letterToQual) {
	print qq{<option>$letter</option>};
    }
    print qq{</select></tr></td>\n};
    #print qq{<input type="text" name="score_letter" size="4"></td></tr>\n};


    print qq{<tr><td class="bra">$lex{Difficulty}</td><td class="la">};
    print qq{<input type="text" name="score_diff" size="4"></td></tr>\n};


    print qq{<tr><td class="bra">$lex{Credits}</td><td class="la">};
    print qq{<select name="credit"><option></option>\n};
    foreach my $cr ( sort @credits ) {
	print qq{<option>$cr</option>};
    }
    print qq{</select> $lex{Override} <input type="text" name="overcredit" size="4"></td></tr>\n};

    print qq{<tr><td class="bra">$lex{'School Year'}</td><td class="la">};
    print qq{<select name="schoolyear"><option>$schoolyear</option>\n};
    foreach my $yr ( @years ) {
	print qq{<option>$yr</option>};
    }
    print qq{</select></tr></td>\n};


    print qq{<tr><td class="bra">$lex{Term}</td><td class="la">};
    print qq{<select name="term"><option></option>\n};
    foreach my $trm (sort @terms) {
	print qq{<option>$trm</option>};
    }
    print qq{</select> $lex{Override} <input type="text" name="overterm" size="4"></td></tr>\n};


    print qq{<tr><td class="bra">$lex{'Term Description'}</td><td class="la">};
    print qq{<select name="term_desc"><option></option>\n};
    foreach my $td (sort keys %term_desc) {
	print qq{<option>$term_desc{$td}</option>};
    }
    print qq{</select></tr></td>\n};

    print qq{</table>\n};
    
    print qq{<p><input type="submit" value="$lex{'Save Transcript Records'}"></p>\n};
    print qq{</form></body></html>\n};

    exit;

}


#------------
sub addRecord {
#------------

    # Exit if missing data
    if (not $arr{subjectcode} or (not $arr{score_mark} and not $arr{score_letter}) ) {
	print qq{<h1>$lex{'Missing Information'}</h1>\n};
	exit;
    }


    # Update letter score from mark
    my ($score_flag, $letter);	
    if ( not $arr{score_letter} ) {

	if ( $arr{score_mark} =~ /[a-zA-Z]/ ) { # if it's a letter
	    $letter = $arr{score_mark};
	} else { # we have a number
	    foreach my $threshold (reverse sort keys %markToLetter ) { 
		# from large to small...
		if ( $arr{score_mark} >= $threshold ) {
		    $letter = $markToLetter{$threshold};
		    last;
		}
	    }
	}

	$arr{score_letter} = $letter;
	$score_flag = 1;
    }


    # Check for an existing ident record...add one if not present...
    my $sth = $dbh->prepare("select count(*) from tscriptident where studnum = ?");
    $sth->execute( $arr{studnum} );
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    my $count = $sth->fetchrow;
    my ( $lastname, $firstname, $middlename, $birthdate);
    if ( $count < 1 ) { # add a new ident record.
	my $sth2 = $dbh->prepare("select lastname,firstname, initial, birthdate, $idfield 
          from studentall where studnum = ?"); 
	$sth2->execute( $arr{studnum} );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	($lastname, $firstname, $middlename, $birthdate, $idfield ) = $sth2->fetchrow;

	my $sth2 = $dbh->prepare("insert into tscriptident values (
          $sql{default}, '$arr{studnum}','$lastname','$firstname','$middlename',
          '$birthdate','$idfield','$graddate')");
	$sth2->execute;
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

    }


    # Check for overrides for term and credit
    if ( $arr{overcredit} ) { 
	$arr{credit} = $arr{overcredit}; 
    }

    if ( $arr{overterm} ) { 
	$arr{term} = $arr{overterm}; 
    }


    # Quote all passed fields.
    foreach my $key ( keys %arr ) {
	if ( $arr{$key} ) {
	    $arr{$key} = $dbh->quote( $arr{$key} );
	} else {
	    $arr{$key} = $sql{default};
	}
    }

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

    my $sth = $dbh->prepare("insert into tscriptdata values ( $sql{default}, $arr{studnum}, 
      $arr{subjectcode}, $arr{subjecttext},  $arr{subjectarea}, $arr{score_mark}, $arr{score_letter},
      $arr{score_diff}, $arr{schoolyear}, now(), $arr{credit},  $arr{term}, $arr{term_desc} ) ");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }


    print qq{<h3>$lex{'Transcript Record Added'}</h3>\n};
    if ( $score_flag ) {
	print qq{<b>$lex{'Letter Grade'}</b>: $arr{score_letter}&nbsp;&nbsp;-&nbsp;<b>};
	print qq{$lex{Mark}</b> $arr{score_mark}</b><br>\n};
    }


    print qq{<p>[ <a href="$reppage">$lex{'Report Card'}</a> |\n};
    print qq{<a href="$self">$lex{'Add More Transcript Records'}</a> ]</p>\n};
    print qq{</body></html>\n};

    exit;

} # End of writeRecord()


#----------------
sub selectStudent {
#----------------

    my $student = shift;

    # Setup the Search
    if ($student =~ /\d+/) {  # we have a student number
	$sth = $dbh->prepare("select lastname, firstname, studnum from studentall 
          where studnum = ?");
	$sth->execute( $student );

    } else { # we have words possibly with a comma
	($lastname,$firstname)  = split /\,/, $student;
	$firstname =~ s/^\s*//;
	$lastname =~ s/^\s*//;
	if ($lastname and $firstname){ # both entered.
	    $sth = $dbh->prepare("select  lastname, firstname, studnum from studentall 
             where lastname = ? and firstname = ?");
	    $sth->execute( $lastname, $firstname );

	} elsif ($lastname and not $firstname){ # only lastname (no comma)
	    if (length($lastname) == 2){ # search by initials: fi, li.
		my $fi = substr($lastname,0,1). '%'; 
		my $li = substr($lastname,1,1). '%';
		$sth = $dbh->prepare("select lastname, firstname, studnum from studentall 
                 where lastname $sql{like} ? and firstname $sql{like} ?");
		$sth->execute( $li, $fi );

	    } else {
		$sth = $dbh->prepare("select lastname, firstname, studnum from studentall 
                  where lastname = ? order by firstname");
		$sth->execute( $lastname );
	    }
	} else { # print an error....
	    showSearchForm();
	    print qq{</body></html>\n};
	    die;
	}

    } # Last Else
    # We should now have a $sth defined.

    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    my $rows = $sth->rows;

    if ($rows < 1) { 
	print qq{<h1>$lex{'No Student(s) Found'}. $lex{'Please search again'}</h1>\n};
	showSearchForm();
	print qq{</body></html>\n};
	exit; 
    }
 
    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
    print qq{<tr><th>$lex{Student}</th><th>$lex{Action}</th></tr>\n};


    for (1..$rows){
	my ($lastname, $firstname, $studnum) = $sth->fetchrow;
	print qq{<tr><td>$firstname $lastname ($studnum)</td><td>\n};

	print qq{<form action="$self" method="post">\n};
	print qq{<input type="submit" value="$lex{'Add Record'}">\n};

	print qq{<input type="hidden" name="page" value="2">\n};

	print qq{<input type="hidden" name="studnum" value="$studnum">\n};
	print qq{</form></td></tr>\n};

    }

    print qq{</table>\n};
    if ( $rows > 20 ) { # only show if lots of records
	showSearchForm();
    }
    print qq{</body></html>\n};

    exit;
}



#----------------
sub showSearchForm {
#----------------

    print qq{<div style="padding:1em 0.2em;">\n};

    print qq{<form action="$self" method="post" style="display:inline;">\n};
    print qq{<input type="submit" value="". $lex{Search}. "">\n};
    print qq{<input type="text" name="student" size="30"><br>\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{$lex{'Student (Last,First/Last/Initials/Studnum)'}\n};

    print qq{</form></div>\n};

    exit;

}
