#!/usr/bin/perl
#  Copyright 2001-2023 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 = ('Main' => 'Main',
	   'Report Card' => 'Report Card',
	   'Add' => 'Add',
	   'Grade' => 'Grade',
	   'Start Term' => 'Start Term',
	   'End Term' => 'End Term',
	   'Save' => 'Save',
	   'Error' => 'Error',
	   'Exists' => 'Exists',
	   'Record(s) Stored' => 'Record(s) Stored',
	   'cannot be larger than' => 'cannot be larger than',
	   'Terms' => 'Terms',
	   'Courses' => 'Courses',
	   'Continue' => 'Continue',
	   'Course' => 'Course',

	   );

my $studentCheck = 0; # check for students in that grade.
my $defaultSection = '1'; # default section value
my $maxterms = 12; # maximum size of term values.

use DBI;
use CGI;

my $self = 'courseadd.pl';

my $defaultsequence = 100; 
# Starting value for sequence number.

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

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

my $title = qq{$lex{Add} $lex{Courses}};
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\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};


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

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


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

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

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

} elsif ( $arr{page} == 3 ) {
    delete $arr{page};
    addObjectives();
    
} elsif ( $arr{page} == 4 ) {
    delete $arr{page};
    writeRecords();
}


#-----------
sub getGrade {  # get the grade for entry.
#-----------

    print qq{<h3>Select Grade</h3>\n};

    my @grades;
    $sth = $dbh->prepare("select distinct grade from student");
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    while ( my $grade = $sth->fetchrow ) {
	push @grades, $grade;
    }

    @grades = sort {$a <=> $b} @grades;

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

    foreach my $grade ( @grades ) {
	print qq{<tr><td>};
	print qq{<form action="$self" method="post">\n};
	print qq{<input type="hidden" name="page" value="1">\n};
	print qq{<input type="hidden" name="grade" value="$grade">\n};
	print qq{<input type="submit" value="$lex{Grade} $grade">\n};
	print qq{</form></td></tr>\n};
    }
    
    print qq{</table>\n};
    print qq{</body></html>\n};

    exit;

}


#----------------
sub selectCourses {
#----------------

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

    
    print qq{<h3>Select Grade $arr{grade} Courses</h3>\n};
    
    # Start the form
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="2">\n};
    print qq{<input type="hidden" name="grade" value="$arr{grade}">\n};

    # Continue
    print qq{<div><input type="submit" value="$lex{Continue}"></div>\n};

    # Start Table
    print qq{<table cellpadding="3" cellspacing="0" border="1" style="margin:1em 0;">\n};

    # Max # of Objectives
    print qq{<tr><td class="bra">Maxiumum # Objectives (1-20)</td>\n};
    print qq{<td><input type="text" style="width:4ch;" name="maxobj"> Blank=Marks Only</td></tr>\n};

    # Default Section
    print qq{<tr><td class="bra">Default Section</td>};
    print qq{<td><input type="text" name="defsection" style="width:6ch;" value="1"></td></tr>\n};

    # Default Starting Term
    print qq{<tr><td class="bra">Default Start Term</td>};
    print qq{<td><input type="text" name="defstartterm" style="width:4ch;"></td></tr>\n};

    # Default Ending Term
    print qq{<tr><td class="bra">Default End Term</td>};
    print qq{<td><input type="text" name="defendterm" style="width:4ch;"></td></tr>\n};

    

    # Start the table.
    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
    print qq{<tr><th>Course</th><th>Code</th><th>Start Date</th></tr>\n};

    
    # Load the active courses for this grade;
    $sth = $dbh->prepare("select * from sasked_courses where grade = ? and 
			 enddate is NULL order by code, title");
    $sth->execute( $arr{grade} );
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    
CRS:    while ( my $ref = $sth->fetchrow_hashref ) {
	my %r = %$ref;

	my @text = split('', $r{title} );
#	print qq{<div>$r{title} };
	foreach my $val (@text) {
	    my $v = ord($val);
	    if ( $v > 200 ) { next CRS;}
#	    print qq{|$v};
	}
#	print qq{</div>\n};
			 
# A Unicode regex search	
#	if ( $r{title} =~ m/\x00c0|\x00ca/g  ){ #Agrav
#	    print qq{<div>Skipping:$r{title}</div>\n};
#	    next;
#	}
	
	print qq{<tr><td><input type="checkbox" name="$r{code}" value="1"> $r{title}</td>};
	print qq{<td>$r{code}</td>\n};
	print qq{<td>$r{startdate}</td></tr>\n};
    }

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

    exit;


}
    

#--------------
sub addCourses {
#--------------

    # print qq{<div>Add Courses</div>\n};
    #  foreach my $key ( sort keys %arr ) { print "K:$key V:$arr{$key}<br>\n"; }
    # Passed: grade, maxobj and then the course codes.
    
    my $grade = $arr{grade};
    delete $arr{grade};

   
    if ( $arr{maxobj} > 20 or $arr{maxobj} < 0 ) {
	print qq{<h3>Error in Maximum Number of objectives</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

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

    my $defsection = $arr{defsection};
    delete $arr{defsection};
    
    my $defstartterm = $arr{defstartterm};
    delete $arr{defstartterm};

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

    
    # Find the number of terms;
    my $track = $g_MTrackTermType{$grade};
    my $maxterm = scalar keys %{ $g_MTrackTerm{$track}};

    
    # Load teachers into hash
    my (%teachers, %teachername);
    $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 ( $lastname, $firstname, $userid) = $sth->fetchrow ) {
	$teachers{"$lastname, $firstname ($userid)"} = $userid;
	$teachername{$userid} = "$lastname, $firstname ($userid)";
    }


    # Display Current Courses.
    print qq{<h3>Current Courses - Grade $grade</h3>\n};
    $sth = $dbh->prepare("select * from subject where grade = ? order by subjcode");
    $sth->execute( $grade );
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    my $first = 1;
    while ( my $ref = $sth->fetchrow_hashref ) {
	my %r = %$ref;
	my $subjcode = $r{subjcode};
	
	foreach my $code ( keys %arr ) { # check if we already have this course.
	    if ( $code == $subjcode ) {
		print qq{<tr><td class="bcn" colspan="5" style="color:red;">};
		print qq{Duplicate Course Code $code - make sure section differs!</td></tr>\n};
	    }
	}

	
	if ( $first ) {
	    print qq{<table cellpadding="3" cellspacing="0" border="0" };
	    print qq{style="border:1px solid gray;">\n};
	    print qq{<tr><th>Description</th><th>Codes</th><th>Teacher</th>};
	    print qq{<th>Terms</th><th>Seq</th></tr>\n};
	    $first = 0;
	}

	print qq{<tr><td>$r{description}</td><td>$r{subjsec}</td><td>$r{teacher}</td>};
	print qq{<td>$r{startrptperiod} - $r{endrptperiod}</td><td class="cn">$r{sequence}</td></tr>\n};

    }

    if ( not $first ) {
	print qq{</table>\n};
    } else {
	print qq{<div style="font-weight:italic;margin:1em;">No Current Courses</div>\n};
    }


    print qq{<hr style="width:20ch;margin-left:0;">\n};
    print qq{<h3>New Courses to Add</h3>\n};
    
    
    # Start 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="maxobj" value="$maxobj">\n};
    print qq{<input type="hidden" name="grade" value="$grade">\n};
    
    # Start Table
    print qq{<table cellpadding="3" cellspacing="0" border="0" };
    print qq{style="border:1px solid gray;padding:0.3em;">\n};
    print qq{<tr><td colspan="10" class="la"><input type="submit" value="$lex{Continue}">};
    print qq{ <span style="color:red;padding:1em;font-weight:bold;">};
    print qq{Hover on title for description</span></td></tr>\n};

    # Table Titles
    print qq{<tr><th title="Title of the course from Sask Ed">Title</th>};
    print qq{<th title="The standard course code value from Sask Ed">Code</th>};
    print qq{<th title="Short Description version of the course">Sm Desc</th>};
    
    print qq{<th title="The unique text (numbers,letters; 1,2,3 or 1GR (teacher initials, etc)) };
    print qq{that identifies the particular group of students };
    print qq{and a teacher for this course. Limited to 8 characters, no spaces,dashes">Section</th>};

    print qq{<th title="The term in which the course starts.">Start<br>Term</th>};
    print qq{<th title="The term in which the course ends">End<br>Term</th>\n};
    print qq{<th title="The teacher of this section of this course">Teacher</th>};
    
    print qq{<th title="Controls printing order on Report Card">Sequence</th>};
    
    # print qq{<th title="This course gradebook will be visible on parent site">
    # Gradebook<br>Visible</th>};
    
    # print qq{<th title="Normally has a 'school' value, except for grade 12 Deptmental
    # exams which are 'blended'">};
    # print qq{Exam Mix</th></tr>\n};
    #    print qq{<th></th><th></th><th></th>

    print qq{</tr>\n};
    

    my $sth1 = $dbh->prepare("select title from sasked_courses where code = ?");
  
    
    # Table Loop for courses.
    foreach my $code ( sort keys %arr ) {
	
	# get title
	$sth1->execute( $code );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $title = $sth1->fetchrow;

	print qq{<tr><td>$title</td><td>$code};
	print qq{<input type="hidden" name="$code:description" value="$title"></td>\n};

	# Small Desc
	print qq{<td><input type="text" style="width:8ch;" name="$code:smdesc" };
	print qq{maxlength="8" value=""></td>\n};
	
	# Section
	print qq{<td><input type="text" style="width:40px;" name="$code:section" };
	print qq{maxlength="8" value="$defsection"></td>\n};

	# Start Term
	print qq{<td><select name="$code:startrptperiod">};
	print qq{<option value="$defstartterm">$defstartterm</option>};
	for my $trm ( 1..$maxterm ) { print qq{<option>$trm</option>}; }
	print qq{</select></td>\n\n};
				     
	# End Term
	print qq{<td><select name="$code:endrptperiod">\n};
	print qq{<option value="$defendterm">$defendterm</option>};
	for my $trm ( 1..$maxterm ) { print qq{<option>$trm</option>}; }
	print qq{</select></td>\n\n};
	
	# Teacher
	print qq{<td><select name="$code:teacher"><option value=""></option>};
	for my $key ( sort keys %teachers ) {
	    my $userid = $teachers{$key};
	    my $name = $teachername{$userid};
	    print qq{<option value="$userid">$name</option>};
	}
	print qq{</select></td>\n\n};

	# Sequence
	# print qq{<td><input type="text" size="4" name="$code:sequence"></td>};

	# Gradebook Visible (ie. web visible)
	# print qq{<td><select name="$code:visible"><option value="N">No</option>\n};
	# print qq{<option value="Y">Yes</option></select></td>\n};

	# Exam Mix (Mark Mix)
	#print qq{<td><select name="$code:exammix"><option></option>};
	#print qq{<option>School</option><option>Blended</option>\n};
	#print qq{</select></td>};

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

    }

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

}


#----------------
sub addObjectives {
#----------------
    
    # print qq{<div>Add Objectives</div>\n};
    # foreach my $key ( sort keys %arr ) { print "K:$key V:$arr{$key}<br>\n"; }
    
    my $maxobj = $arr{maxobj};
    delete $arr{maxobj}; # maximum number of objectives needed.
    
    # Check for any missing values; these are the fields to check
    my %fields = (description => 1, endrptperiod => 1, startrptperiod => 1,
		  section => 1, smdesc => 1, teacher => 1); # skip sequence requirement
    
    my $missingflag;
    foreach my $key ( sort keys %arr ) {
	my ($code, $field) = split(':', $key);
	if ( not $arr{$key} and $field) {  # no value and it's one of the fields in courses
	    print qq{<div>Missing Value in course code <b>$code</b> for field <b>$field</b></div>\n};
	    $missingflag = 1;
	}
    }
    if ( $missingflag ) {
	print qq{<div>Please go back</div>\n};
	print qq{</body></html>\n};
	exit;
    }

    
    # Find the code and course names (description)
    my %coursename;
    my %sort; # sort by code value
    foreach my $key ( keys %arr ) {
	my ($code, $temp) = split(':', $key );
	$sort{$code} = 1;
	if ( $temp eq 'description' ) {
	    $coursename{$code} = $arr{$key};
	}
    }
   
    print qq{<table cellpadding="3" cellspacing="0" border="0" };
    print qq{style="border:1px solid gray;padding:0.5em;margin:1em;">\n};
    print qq{<tr><td>};
    print qq{If your course only has only marks, <b>no objectives/outcomes entry<br>\n};
    print qq{is required.</b> If you have non-mark based objectives, please enter<br>\n};
    print qq{the description that will appear on the report card. These will<br>\n};
    print qq{also appear for evaluation entry. <b>Note: The first objective should <br>\n};
    print qq{be the numeric value if a mix of mark and other outcomes.</b> };
    print qq{Limit: 255 characters</td></tr>\n};
    print qq{</table>\n};
    
    # Start Form
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="4">\n};
    foreach my $key (keys %arr ) {
	print qq{<input type="hidden" name="$key" value="$arr{$key}">\n};
    }
    
    # Save
    print qq{<input type="submit" value="$lex{Save} $lex{Courses}">\n};
    
    foreach my $code ( sort keys %sort ) {
	my $description = $coursename{$code};

#	print qq{<h3>$description ($code)</h3>\n};
    
	# Start Table
	print qq{<table cellpadding="3" cellspacing="0" border="0">\n};
	print qq{<tr><th colspan="2" style="text-align:left;">$description ($code) Objectives};
	print qq{</th></tr>\n};
	if ( not $maxobj ) { print qq{<tr><td>Marks Only</td></tr>\n}; }
	foreach my $obj ( 1..$maxobj ) {
	    print qq{<tr><td>$obj.</td><td><input type="text" name="$code:q$obj" };
	    print qq{style="width:50em;" maxlength="255"></td></tr>\n};
	}


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

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

    exit;

}



#---------------
sub writeRecords {
#---------------

    # print qq{<div>Write Records</div>\n};
    #foreach my $key ( sort keys %arr ) { print "K:$key V:$arr{$key}<br>\n"; }
    
    my $grade = $arr{grade};
    delete $arr{grade};
    

    # push all data into %data.
    my %data;
    foreach my $key ( sort keys %arr ) {
	$arr{$key} =~ s/^\s+//g; # strip leading and trailing spaces in values.
	$arr{$key} =~ s/\s+$//g;
	my ($code, $field) = split(':', $key);
	$data{$code}{$field} = $arr{$key};
    }


    foreach my $code ( sort keys %data ) {
	my %r = %{ $data{$code}};
	$r{grade} = $grade;
	$r{subjcode} = $code;

	# Check objectives, remove any blank values
	foreach my $val (1..20) {
	    my $field = 'q'. $val;
	    if ( not exists $r{$field} ) { # doesn't exist, skip
		next;
	    }
	    if ( not $r{$field} ) { # no value, delete
		delete $r{$field};
	    }
	}

=head	
	# Blank Values Check
	my @missing;
	foreach my $field ( sort keys %r ) {
	    if ( not $r{$field} ) {
		push @missing, $field;
	    }
	}
	if ( @missing ) {
	    my $fields = join(',', @missing);
	    print qq{<h3>Missing Fields for $code: $fields. Skipping!</h3>\n};
	    next;
	}
=cut
	
	# Section Stripping (spaces, non alphanumerics)
	$r{section} =~ s/\s//g; # strip any spaces in the section value.
	$r{section} =~ s/\W//g; # strip any non-alphanumerics.
	
	# Join Subject and Section to make Subjsec
	my $subjsec = $r{subjsec} = $code. '-'. $r{section};


	# Check for existing subject-section ( subjsec )
	my $sth = $dbh->prepare("select count(*) from subject where subjsec = ?");
	$sth->execute( $subjsec );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	my $count = $sth->fetchrow;
	if ( $count > 0 ){
	    print qq{<h3>$lex{Course} $lex{Exists} - $subjsec. Skipping!</h3>\n};
	    next;
	}

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

	if ( $r{startrptperiod} > $maxterms or $r{endrptperiod} > $maxterms ) {
	    print qq{<h3>$code: $lex{Terms} $lex{'cannot be larger than'} $maxterms. Skipping</h3>\n};
	    next;
	}


	$sth = $dbh->prepare("insert into subject ( subjcode, description, grade, teacher,
         sequence , section, subjsec, smdesc,
         q1, q2, q3, q4, q5, q6, q7, q8, q9, q10,
         q11, q12, q13, q14, q15, q16, q17, q18, q19, q20,
         visible, startrptperiod, endrptperiod, location, exammix )
         values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,
                ?,?,?,?,?,?,?,?,?,?,?,?,?)");
	# 33 fields;

	$sth->execute( $r{subjcode}, $r{description}, $r{grade}, $r{teacher}, $r{sequence},
		       $r{section}, $subjsec, $r{smdesc},
		       $r{q1}, $r{q2}, $r{q3}, $r{q4}, $r{q5}, $r{q6}, $r{q7}, $r{q8}, $r{q9}, $r{q10},
		       $r{q11}, $r{q12}, $r{q13}, $r{q14}, $r{q15}, $r{q16}, $r{q17}, $r{q18}, $r{q19},
		       $r{q20},
		       $r{visible}, $r{startrptperiod}, $r{endrptperiod}, $r{location}, $r{exammix} );

    } # next code (course)

	
    if (not $DBI::errstr ) {
	print qq{<h3>$lex{'Record(s) Stored'}</h3>\n};
    } else { 
	print qq{<h3>$lex{Error}: $DBI::errstr</h3>};
    }

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

    exit;

}
