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

#  This file is part of Open Admin for Schools.


my %lex=('Course' => 'Course',
	 'Edit' => 'Edit',
	 'Main' => 'Main',
	 'Report Card' => 'Report Card',
	 'Codes' => 'Codes',
	 'Other Codes' => 'Other Codes',
	 'Save' => 'Save',
	 'Course Code' => 'Course Code',
	 'Section' => 'Section',
	 'Description' => 'Description',
	 'Short Description' => 'Short Description',
	 'Max' => 'Max',
	 'char' => 'char',
	 'Grade' => 'Grade',
	 'Start Term' => 'Start Term',
	 'End Term' => 'End Term',
	 'Teacher' => 'Teacher',
	 'Sequence' => 'Sequence',
	 'Controls printing order on report card' => 
	   'Controls printing order on report card',
	 'Web Visible' => 'Web Visible',
	 'Y' => 'Y',
	 'N' => 'N',
	 'Instructional Mode' => 'Instructional Mode',
	 'Class' => 'Class',
	 'Distance' => 'Distance',
	 'Exam Mix' => 'Exam Mix',
	 'School' => 'School',
	 'Blended' => 'Blended',
	 'Faculty' => 'Faculty',
	 'Location' => 'Location',
	 'Mark Scheme' => 'Mark Scheme',
	 'Objective' => 'Objective',
	 'Credit' => 'Credit',
	 'Difficulty' => 'Difficulty',
	 'Subject Area' => 'Subject Area',
	 'Calc Average' => 'Calc Average',
	 'If your subject only has marks and comments, no objective entry' => 
	   'If your subject only has marks and comments, no objective entry',
	 'is required. If you have non-mark based objectives, please enter' =>
	   'is required. If you have non-mark based objectives, please enter',
	 'the description that will appear on the report card. These will' =>
	  'the description that will appear on the report card. These will',
	 'also appear for evaluation entry. Limit: 255 characters' =>
	   'also appear for evaluation entry. Limit: 255 characters',
	 'Changing Start/End Term will require adding/removing student mark records' =>
	 'Changing Start/End Term will require adding/removing student mark records',
	 'There is one mark record for every term for each student' =>
	   'There is one mark record for every term for each student',

	 'Contact' => 'Contact',
	 'Required' => 'Required',
	 'cannot be larger than' => 'cannot be larger than',
	 'Terms' => 'Terms',
	 'Error' => 'Error',
	 'Record(s) Updated' => 'Record(s) Updated',
	 'Letters' => 'Letters',
	 'Numbers' => 'Numbers',
	 'Only' => 'Only',
	 'No Spaces' => 'No Spaces',
	 'Required Field Missing' => 'Required Field Missing',
	 'Enrollments' => 'Enrollments',
	 'Master' => 'Master',

	 );

my $self = 'subjed.pl';
my $maxterms = 12;  # maximum value allowed in the start and end reporting period (terms)
my $reddot = q{<span style="color:red;">*</span>};

my $showMarkScheme = 0; # change to a 1 to display.

use DBI;
use CGI;
use Encode;

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;

if ( $arr{mrk} ) {
    $showMarkScheme = 1;
    delete $arr{mrk};
}


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


# Print Page Header
$title = qq{$lex{Edit} $lex{Course} $lex{Master}};

print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};
print qq{<style>textarea { height:1em;width:60ch;}</style>\n};
print qq{$chartype\n</head><body style="padding:1em 2em;">\n};

print qq{[ <a href="$homepage">$lex{Main}</a> |\n};
print qq{<a href="$reppage">$lex{'Report Card'}</a> | \n};
print qq{<a href="../sasked/coursecodeview.pl" target="_blank">SK Course $lex{Codes} };
print qq{(in new tab)</a> ]};

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


if ( $arr{flag} ) {
    delete $arr{flag};
    writeRecord();
}


# Load teachers with classroom teacher value set.
my %teachers;
my $sth1 = $dbh->prepare("select count(*) from staff_multi where userid = ?
   and field_name = 'position' and field_value = 'Classroom Teacher'");

my $sth = $dbh->prepare("select lastname, firstname, userid from staff 
 order by lastname, firstname"); 
$sth->execute;
if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
while ( my ($ln, $fn, $uid) = $sth->fetchrow ) {
    
    # Check if classroom teacher
    $sth1->execute($uid);
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
    my $count = $sth1->fetchrow;
    if ( not $count ) { next; }
    
    $teachers{"$ln, $fn ($uid)"} = $uid;
}

# Now select and load the course
$sth = $dbh->prepare("select * from subject where id = ?"); 
$sth->execute( $arr{id} );
my $subjref = $sth->fetchrow_hashref;
my %subj = %$subjref;
my $termcount = $subj{endrptperiod} - $subj{startrptperiod} + 1;


# Now count the eval records for this subject (to see if any exist).
# Find the number of eval records depending on this...

my $noeditflag;
$sth = $dbh->prepare("select count(*) from eval where subjcode = ?");
$sth->execute( $subj{subjsec} ); # subjsec field
if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
my $count = $sth->fetchrow;

my $enrollments;
if ( $termcount ) {
    $enrollments= int( $count / $termcount );
} else { $enrollments = 0; }

if ( $count ){ $noeditflag = 1; }



# Now print the form.
print qq{<form action="$self" method="post">\n};
print qq{<input type="hidden" name="id" value="$arr{id}">\n};
print qq{<input type="hidden" name="flag" value="1">\n};
# Not used for updates. print "<input type="hidden" name="noeditflag" value="$noeditflag">\n";

print qq{<table cellpadding="3" cellspacing="0" border="0">\n};
print qq{<tr><td></td><td>};

print qq{<input type="submit" value="$lex{Save}">};
print qq{ (<span style="color:red">* = $lex{Required}</span>)</td></tr>\n};

print qq{<tr><td class="bra">$lex{Enrollments}</td><td>$enrollments</td></tr>\n};

# id for passing in command line.
print qq{<tr><td class="bra">Record Id</td><td>$subj{id}</td></tr>\n};


print qq{<tr><td class="bra">$lex{'Course Code'}$reddot</td><td>\n};
if ( $noeditflag ) {
    print $subj{subjcode};
    print qq{<input type="hidden" name="subjcode" value="$subj{subjcode}">\n};
   
} else {
    print qq{<input type="text" name="subjcode" size="10" value="$subj{subjcode}">};
}
print qq{</td></tr>\n};


print qq{<tr><td class="bra">$lex{Section}$reddot</td>\n<td>};
if ( $noeditflag ) {
    print $subj{section};
    print qq{<input type="hidden" name="section" value="$subj{section}">\n};
} else {
    print qq{<input type="text" name="section" size="6" value="$subj{section}">};
}
print qq{</td></tr>\n};


print qq{<tr><td class="bra">$lex{Description} $reddot</td>
<td><input type="text" name="description" size="50" maxlength="255" 
 value="$subj{description}"></td></tr>\n};

print qq{<tr><td class="bra">$lex{'Short Description'} $reddot</td>
<td><input type="text" name="smdesc" size="8" maxlength="8" value="$subj{smdesc}"> };
print qq{$lex{Max}: 8 $lex{char}</td></tr>\n};

print qq{<tr><td class="bra">$lex{Grade} $reddot</td>
<td><input type="text" Name="grade" size="4" maxlength="8" value="$subj{grade}"></td></tr>\n};

print qq{<tr><td class="bra">$lex{'Start Term'} $reddot</td>
<td><input type="text" name="startrptperiod" size="6" value="$subj{startrptperiod}"></td></tr>\n};

print qq{<tr><td class="bra">$lex{'End Term'} $reddot</td>
<td><input type="text" name="endrptperiod" size="6" value="$subj{endrptperiod}"></td></tr>\n};


print qq{<tr><td class="bra">$lex{'Teacher'} $reddot</td>\n};


# Get teacher name
my $sth = $dbh->prepare("select lastname, firstname from staff where userid = ?");
$sth->execute( $subj{teacher} );
if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
my ($ln, $fn) = $sth->fetchrow;
my $name = "$ln,$fn";

print qq{<td><select name="teacher"><option value="$subj{teacher}">$name ($subj{teacher})</option>\n};
foreach my $key ( sort keys %teachers ) { print qq{<option value="$teachers{$key}">$key</option>\n}; }
print qq{</select> Must have a <b>Classroom Teacher</b> position</td></tr>\n};

# Teacher 2
if ( $subj{teacher2} ) {
    $sth->execute( $subj{teacher2} );
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
    my ($ln, $fn) = $sth->fetchrow;
    $name = "$ln,$fn";
} else {
    $name = '';
}
print qq{<tr><td class="bra">$lex{'Teacher'} 2</td>\n};
print qq{<td><select name="teacher2"><option value="$subj{teacher2}">$name $subj{teacher2}</option>\n};
foreach my $key ( sort keys %teachers ) { print qq{<option value="$teachers{$key}">$key</option>\n}; }
print qq{<option value=""></option></select></td></tr>\n};


print qq{<tr><td class="bra">$lex{Sequence}</td>\n};
print qq{<td><input type="text" name="sequence" size="8" value="$subj{sequence}">\n};
print qq{$lex{'Controls printing order on report card'}</td></tr>\n};

print qq{<tr><td class="bra">$lex{'Web Visible'}</td>\n};
print qq{<td><select name="visible"><option>$subj{visible}</option>\n};
print qq{<option>$lex{Y}</option><option>$lex{N}</option>};
print qq{<option value=""></option></select></td></tr>\n};

print qq{<tr><td class="bra">$lex{'Instructional Mode'}</td>\n};
print qq{<td><select name="instmode"><option>$subj{instmode}</option>\n};
print qq{<option>$lex{'Class'}</option><option>$lex{Distance}</option>\n};
print qq{<option value=""></option></select></td></tr>\n};

print qq{<tr><td class="bra">$lex{'Exam Mix'}</td><td><select name="exammix">\n};
print qq{<option>$subj{exammix}</option><option>$lex{'School'}</option>\n};
print qq{<option>$lex{'Blended'}</option><option value=""></option></select></td></tr>\n};


print qq{<tr><td class="bra">$lex{Faculty}</td><td><input type="text" name="faculty" 
 size="12" maxlength="255" value="$subj{faculty}"></td></tr>\n};

print qq{<tr><td class="bra">$lex{Location}</td><td><input type="text" name="location" 
size="12" maxlength="255" value="$subj{location}"></td></tr>\n};


if ( $showMarkScheme ) {
    print qq{<tr><td class="bra">$lex{'Mark Scheme'}</td><td><textarea name="markscheme" };
    print qq{style="width:30ch;height:10ch;">$subj{markscheme}</textarea></td></tr>\n};
}
    

print qq{<tr><td class="bra">$lex{'Credit'}</td><td>};
if ( @creditValues ) { # from transcript.conf
    print qq{<select name="credit">\n};
    if ( $subj{credit} ) { print qq{<option>$subj{credit}</option>\n}; }
    foreach my $val ( @creditValues ) {	print qq{<option>$val</option>\n}; }
    print qq{<option value=""></option></select>\n};
} else {
    print qq{<input type="text" name="credit" size="4" };
    print qq{maxlength="8" value="$subj{credit}">};
}
print qq{</td></tr>\n};


print qq{<tr><td class="bra">$lex{'Difficulty'}</td>\n<td>};
print qq{<input type="text" name="difficulty" size="4" maxlength="8"};
print qq{ value="$subj{difficulty}"></td></tr>\n};

print qq{<tr><td class="bra">$lex{'Subject Area'}</td>\n};
if ( %gradRequirements ) {
    print qq{<td><select name="area"><option value="$subj{area}">$subj{area}</option>\n};
    foreach my $key ( sort keys %gradRequirements ) {
	print qq{<option>$key</option>\n};
    }
    print qq{<option value=""></option></select></td></tr>\n};
} else {
    print qq{<td><input type="text" name="area" size="20" maxlength="255"};
    print qq{ value="$subj{area}"></td></tr>\n};
}

print qq{<tr><td class="bra">$lex{'Calc Average'}</td>\n};
print qq{<td><select name="calcavg">\n};
if ( $subj{calcavg} ) { # We have an existing value...
    print qq{<option>$subj{calcavg}</option>\n};
}
print qq{<option>$lex{N}</option>\n};
print qq{<option>$lex{Y}</option>\n};
print qq{<option value=""></option></select></td></tr>\n};


print qq{<tr><td></td><td><div style="border:1px solid gray;margin:1em 0;padding:1em;width:60ch;">\n};
print qq{$lex{'If your subject only has marks and comments, no objective entry'}<br>\n};
print qq{$lex{'is required. If you have non-mark based objectives, please enter'}<br>\n};
print qq{$lex{'the description that will appear on the report card. These will'}<br>\n};
print qq{$lex{'also appear for evaluation entry. Limit: 255 characters'}.</div></td></tr>\n};

for my $i ( 1 .. 20 ) {
    my $j = 'q'. $i;
    print qq{<tr><td class="bra">$lex{Objective} $i</td><td><textarea };
    print qq{name="$j">$subj{$j}</textarea></td></tr>\n};
}

print qq{<tr><td></td><td><input type="submit" value="$lex{Save}"></td></tr>\n};
print qq{</table></form></body></html>\n};



#--------------
sub writeRecord {
#--------------

    # print "Passed Values to Write<br>\n";
    # foreach $key ( sort keys(%arr)) { print qq{K:$key V:$arr{$key}<br>\n}; }
    
    my $id = $arr{id};
    delete $arr{id}; # record id to edit.

    foreach my $chk ( qw(subjcode section )) {
	my $val = $arr{$chk};
	if ( $val =~ m/\W|\s+/ ) {
	    print qq{<h3>$lex{Letters},$lex{Numbers} $lex{Only}; $lex{'No Spaces'}: \n};
	    print qq{<span style="color:red;">$val</span></h3>\n};
	    print qq{</body></html>\n};
	    exit;
	}
    }

    foreach my $chk ( qw(description smdesc )) {
	my $val = $arr{$chk};
	if ( $val !~ m/\w|\s/ ) {
	    print qq{<h3>$lex{Letters},$lex{Numbers} $lex{Only}: \n};
	    print qq{<span style="color:red;">$val</span></h3>\n};
	    print qq{</body></html>\n};
	    exit;
	}
    }


    # Make sure it has the right fields filled in and no hyphens
    # not $arr{subjcode} or not $arr{section} or 
    if ( not $arr{description} or not $arr{startrptperiod} or 
	 not $arr{endrptperiod} or not $arr{grade} or 
	 not $arr{teacher} ) {

	print qq{<h1>$lex{'Required Field Missing'}</h1>\n};
	print qq{</body></html>\n};
	exit;
    }

    
    # load existing record values for subjcode, section, subjsec, periods
    my $sth = $dbh->prepare("select subjcode, section, subjsec,
     startrptperiod, endrptperiod, teacher from subject where id = ?");
    $sth->execute( $id );
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    my ($subjcode, $section, $subjsec,$startterm, $endterm, $teacher) = $sth->fetchrow;
    
    print qq{<b>Existing Record</b>: Code:$subjcode - Section:$section  - Subjsec:$subjsec<br>\n};
    print qq{Terms:$startterm / $endterm Teacher:$teacher  ID:$id<br><br>\n};


    

    # Find the number of eval records depending on this...
    $sth = $dbh->prepare("select count(*) from eval where subjcode = ?");
    $sth->execute( $subjsec );
    if ($DBI::errstr){ print $DBI::errstr; die;}
    my $subjcount = $sth->fetchrow;


    if ( ( $startterm != $arr{startrptperiod} and $subjcount )
	 or ( $endterm != $arr{endrptperiod} and $subjcount ) ) {
	print qq{<h1>};
	print qq{$lex{'Changing Start/End Term will require adding/removing student mark records'}!\n}; 
	print qq{$lex{'There is one mark record for every term for each student'}!</h1>\n};
    }


    # Check for start/end term errors: sequence, < 1, > maxterms
    if ( $arr{startrptperiod} > $arr{endrptperiod} or 
	 $arr{startrptperiod} < 1 or 
	 $arr{endrptperiod} < 1 ) {
	print qq{<h3>$lex{'Start Term'} $lex{'cannot be larger than'} $lex{'End Term'}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    if ( $arr{startrptperiod} > $maxterms or $arr{endrptperiod} > $maxterms ) {
	print qq{<h3>$lex{Terms} $lex{'cannot be larger than'} $maxterms</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    # update the subjsec field.
    $arr{subjsec} = $arr{subjcode}. q{-}. $arr{section};
    

    
    foreach my $key ( sort keys %arr ) {
	if ( not $arr{$key} ) {  # if no value now, set to NULL
	    $sth = $dbh->prepare("update subject set $key = NULL where id = ?");
	    $sth->execute( $id );
	} else {
	    $arr{$key} = encode('UTF-8',$arr{$key});
	    $sth = $dbh->prepare("update subject set $key = ? where id = ?");
	    $sth->execute( $arr{$key}, $id );
	}

	# print qq{Update: K:$key V:$arr{$key} ID:$id<br>\n};
	if ($DBI::errstr ) { print qq{$DBI::errstr;<br>\n}; }

    }

    if ( not $DBI::errstr ) {
	print qq{<h3>$lex{'Record(s) Updated'}</h3></p>\n};
    } else {
	print qq{<h3>$lex{Error}: $DBI::errstr<br>\n};
	print qq{$lex{Contact} $adminname (<a href="mailto:$adminemail">$adminemail</a> )</h3>\n};
    }

    print qq{<p>[ <a href="$reppage">$lex{'Report Card'}</a> | \n};
    print qq{<a href="subjdeled.pl">$lex{Course} $lex{Edit}</a> ]\n};
    print qq{</p></body></html>\n};

    exit;

}
