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

#  This file is part of Open Admin for Schools.

my %lex = ('Import' => 'Import',
	   'Upload' => 'Upload',
	   'File' => 'File',
	   'Main' => 'Main',
	   'Timetable' => 'Timetable',
	   'Term(s)' => 'Term(s)',
	   'Separate with Spaces' => 'Separate with Spaces',
	   'Cannot open file' => 'Cannot open file',
	   'Maximum File Upload size exceeded' => 'Maximum File Upload size exceeded',
	   'Parsing Error' => 'Parsing Error',
	   'Teacher' => 'Teacher',
	   'Day' => 'Day',
	   'Period' => 'Period',
	   'Subject' => 'Subject',
	   'Term' => 'Term',
	   'Error' => 'Error',

	   );


my $self = 'importfetdata.pl';
my $maxbufcount = 4096; # max file upload size in K. 5MB default.
my $term = 1;

use DBI;
use CGI;
use XML::LibXML;


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

eval require "../../etc/schedule.conf";
if ( $@ ) {
    print $lex{Error}. ": $@<br>\n";
    die $lex{Error}. ": $@\n";
}
# load periods from schedule configuration.
for my $period (1..$#ptime) {
    $rev_ptime{$ptime[$period]} = $period;
}

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

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


my $title = "FET $lex{Import}";

print qq{$doctype\n<html><head><title>$title</title> 
<link rel="stylesheet" href="$css" type="text/css">
<style type="text/css">
body { padding: 1em 3em;}</style>
$chartype\n</head><body>\n};
print qq{[ <a href="$homepage">$lex{Main}</a> | \n};
print qq{<a href="$schpage">$lex{Timetable}</a> ]\n};

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


my @tim = localtime(time);
my $year = $tim[5] + 1900;
$tim[4]++;
for (0..4){if (length($tim[$_]) == 1){ $tim[$_] = '0'.$tim[$_];}}
my $currdate = "$year-$tim[4]-$tim[3]";
my $currtime = "$tim[2]:$tim[1]:$tim[0]";


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

} else {
    delete $arr{page};
    getFile();
}


#----------------
sub showStartPage {
#----------------

    print qq{<form action="$self" method="post" enctype="multipart/form-data">\n};
    print qq{<input type="hidden" name="page" value="1">\n};

    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
    print qq{<tr><td class="bra">FET $lex{Timetable}</td>\n};
    print qq{<td class="la"><input type="file" name="filename"></td></tr>\n};

    print qq{<tr><td class="bra">$lex{'Term(s)'}</td>\n};
    print qq{<td class="la"><input type="text" name="term" size="10"> };
    print qq{$lex{'Separate with Spaces'}</td></tr>\n};

    print qq{<tr><td colspan="2" class="cn">};
    print qq{<input type="submit" value = "$lex{Upload} FET $lex{Timetable}"></td></tr>\n};

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

    exit;

}



#----------
sub getFile {
#----------

    my @terms = split /\s/, $arr{term};
    delete $arr{term};

    # This is magical in terms of the CGI module.
    my $file = $q->param("filename"); 

    if ($file) {
	$filename = $file;  # fileName is output filename, file is input handle.
	$filename =~ s!^.*(\\|\/)!!; 
	$filename = lc($filename);
	#print qq{The filename is: $filename<br>\n};
	
   
	unless (open (OUTFILE, ">$filename")) {
	    print $lex{'Cannot open file'}. " $filename";
	    die $lex{'Cannot open file'}. " $filename";
	}
	my $bufcount = 0;
	while (my $bytesread = read($file, my $buffer, 1024)) { 
	    print OUTFILE $buffer;
	    $bufcount++;
	    if ($bufcount > $maxbufcount){
		print qq{<h3>$lex{'Maximum File Upload size exceeded'} };
		print qq{($maxbufcount K)</h3>\n};
		print qq{</body></html>\n};
		exit;
	    }
	} 
        close (OUTFILE);
    }

    unless (open (FH,"<",$filename)) {
	print qq{$lex{Error}: $filename $@\n};
	print qq{</body></html>\n};
	exit;
    }

    # slurp file
    my $data;
    { local $/; $data = <FH>; close FH;}
    # print qq{The data is: $data \n";
    system ("rm -f $filename");


    my $parser = XML::LibXML->new();

    my $doc;    
    eval { $doc = $parser->parse_string($data) };
    if ($@){
	print qq{$lex{'Parsing Error'}: $@<br>\n};
	print qq{<pre>$lex{'Parsing Error'}:\n}, $data, qq{</pre><br>\n};
	print qq{</body></html>\n}; 
        exit;
    }

    $doc->setEncoding('UTF-8');
    my $root = $doc->getDocumentElement;
    #$root->setNamespace("http://fet.org","fet",0);


    # Parse the node tree
    @nodes = $root->findnodes('Teacher');
    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
    print qq{<tr><th>$lex{Teacher}</th><th>$lex{Day}</th><th>$lex{Period}</th>};
    print qq{<th>$lex{Subject}</th><th>$lex{Term}</th></tr>\n};

    foreach my $teachernode (@nodes) { # teacher nodes
	my $teacherid = $teachernode->findvalue('@name');
	#print qq{\nThe teacherid is: $teacherid\n";
	
	my @days = $teachernode->findnodes('Day');
	foreach my $daynode (@days) {
	    my $dayname = $daynode->findvalue('@name');
	    my $day = $dayname;
	    $day =~ s/\D+|\s+//g;
	    #print qq{\nThe day is: $day\n";
	    

	    @hours = $daynode->findnodes('Hour');
	    foreach my $hournode (@hours) {
		my $hourname = $hournode->findvalue('@name');
		my $period = $rev_ptime{$hourname};
		#print qq{Period is: $period ";
		
		my $subjectname = $hournode->findvalue('Week1/Subject/@name');
		my ($sname, $subjsec) = split /\(/,$subjectname;
		$subjsec =~ s/\)//; # strip trailing bracket.
		#print qq{Sub: $subjsec\n";

		my @studnodes = $hournode->findnodes('Week1/Students');
		foreach my $studnode (@studnodes) {
		    my $grade = $studnode->findvalue('@name');
		    $grade =~ s/\D//g;
		    #print qq{Grade is: $grade\n";
		
		    foreach my $term (@terms) {
			my $sth = $dbh->prepare("insert into schedat values(
                        $sql{default},'$day', '$period', '$subjsec', '$grade', '$term')");
			$sth->execute;
			if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
		    }

		    print qq{<tr><td>$teacherid</td><td>$day</td><td>$period</td>};
		    print qq{<td>$subjectname</td><td>$grade</td></tr>\n}; 

		} # End of Student (Grades)
	    } # End of Hour (and matching Subjsec... possibly if not prep period.
	} # End of Days
    } # End of Teachers

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