#!/usr/bin/perl
#  Copyright 2001-2019 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=('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>};

use DBI;
use CGI;

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;

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} (in new tab)</a> ]};

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


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


# Load teachers
my %teachers;
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 ) {
    $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};

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};

my $userid; # of teacher
if ( $subj{teacher} =~ m/\((\w+)\)/ ) {
    $userid = $1;
} else {
    $userid = $subj{teacher};
}

# Get teacher name
$sth = $dbh->prepare("select lastname, firstname from staff where userid = ?");
$sth->execute( $userid );
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="$userid">$name ($userid)</option>\n};
foreach my $key ( sort keys %teachers ) { print qq{<option value="$teachers{$key}">$key</option>\n}; }
print qq{</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><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></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></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></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};

# print qq{<tr><td class="bra">$lex{'Mark Scheme'}</td><td><textarea name="markscheme" 
# rows="6" cols="40">$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></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>$subj{area}</option>\n};
    foreach my $key ( sort keys %gradRequirements ) {
	print qq{<option>$key</option>\n};
    }
    print qq{<option></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></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} ) { 
	    $sth = $dbh->prepare("update subject set $key = $sql{default} where id = ?");
	    $sth->execute( $id );
	} else {
	    $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;

}
