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

#  This file is part of Open Admin for Schools.


my %lex = ('Main' => 'Main',
	   'Mark Entry' => 'Mark Entry',
	   'School' => 'School',
	   'Set' => 'Set',
	   'Error' => 'Error',
	   'Save' => 'Save',
	   'Path' => 'Path',
	   'Record(s)' => 'Record(s)',
	   'Updated' => 'Updated',
	   'File' => 'File',
	   'Edit' => 'Edit',
	   'Not Found' => 'Not Found',
	   'Update' => 'Update',
	   'Track' => 'Track',
	   'Entry Term' => 'Entry Term',
	   'Grades' => 'Grades',
	   'Report Card' => 'Report Card',
	   'Disable' => 'Disable',
	   
	   );

my $self = 'termmarkentry.pl';


use DBI;
use CGI;

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

# Setup Database access
my $dsn = "DBI:mysql:dbname=$dbase";
my $dbh = DBI->connect($dsn,$user,$password);
$dbh->{mysql_enable_utf8} = 1;

# Load variables of interest from DB.
my @fieldnames = qw(doctype charset css r_MarkEntryTerm g_MTrackTerm g_MTrackTermType 
    g_TermDisplay g_TrackDisplay g_EtcPath homepage reppage);
my $sth = $dbh->prepare("select datavalue from conf_system where dataname = ?");
foreach my $var ( @fieldnames ) {
    $sth->execute( $var );
    my $datavalue = $sth->fetchrow;
    eval $datavalue;
    if ( $@ ) {
	print "$lex{Error}: $@<br>\n";
	die "$lex{Error}: $@\n";
    }
}





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





# Page Header
my $title = "$lex{Set} $lex{'Mark Entry'} $lex{Term}";
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>\n};

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

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




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

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


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

    
    # Starting Note
    print qq{<p>This setting controls which term teachers may enter marks and comments };
    print qq{for report cards.<br>\n};
    print qq{Setting a track entry term to <i>Disable</i> will prevent mark entry by teachers.</p>\n};

    
    # Start Form
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};

=head
    # Load Existing Configuration Data.
    my $sth = $dbh->prepare("select * from conf_system 
			    where (filename = 'repcard' and sectionname = 'Config' ) or 
			    dataname = 'r_MarkEntryTerm' order by sequenceval");
    $sth->execute;
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

    while ( my $ref = $sth->fetchrow_hashref ) {

	# put value into namespace
	my $datavalue = $ref->{datavalue};
	eval $datavalue;
	if ( $@ ) {
	    print $lex{Error}. " $@<br>\n";
	    die $lex{Error}. " $@\n";
	}
	my $dataname = $ref->{dataname};

    }
=cut
    
    print qq{<tr><th>$lex{Track}</th><th>$lex{Grades}</th><th>$lex{'Entry Term'}</th></tr>\n};

    foreach my $trk ( sort keys %g_MTrackTerm ){
	# populate %terms,@terms for this track.
	my %terms; # for this track.
	foreach my $trm ( keys %{ $g_MTrackTerm{$trk} } ){
	    $terms{$trm} = 1;
	}
	my @terms = sort keys %terms;

	# populate the grades.
	my @grades;
	foreach my $gr ( keys %g_MTrackTermType ) {
	    if ( $g_MTrackTermType{$gr} eq $trk ) { # this grade is a member of current track
		push @grades, $gr;
	    }
	}
	my $grades = join(',',sort {$a <=> $b} @grades);		 
	
	    
	print qq{<tr><td class="bla">$g_TrackDisplay{$trk}</td><td>$grades</td>\n};
	print qq{<td class="la">};

	print qq{<select name="$trk">};
	if ( $r_MarkEntryTerm{$trk} == 0 ) {
	    print qq{<option value="0">$lex{Disable}</option>\n};
	} else {
	    print qq{<option>$r_MarkEntryTerm{$trk}</option>\n};
	}
	foreach my $trm ( @terms ) {
	    if ( $trm eq $r_MarkEntryTerm{$trk} ) { next; }
	    print qq{<option>$trm</option>};
	}
	print qq{\n<option value="0">$lex{Disable}</option></select></td></tr>\n};
    }
    
    print qq{</table>\n};
    print qq{<input type="submit" value="$lex{Save}">\n};
    print qq{</form>\n};

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

    exit;

}



#--------------
sub writeValues {
#--------------

    # foreach my $key ( sort keys %arr ) { print "K:$key V:$arr{$key}<br>\n"; }
    
    use Data::Dumper;
    $Data::Dumper::Purity = 1;
    $Data::Dumper::Indent = 0;

    my $value_ref = [ ];
    my $name_ref = [ ];

    # only Scalar Value
    push @$name_ref, '*r_MarkEntryTerm';
    push @$value_ref, \%arr;
	
    my $d = Data::Dumper->new( $value_ref, $name_ref );
    my $datavalue = $d->Dump;

    
    # print "Datavalue: $datavalue<br>\n";
    my $sth = $dbh->prepare("update conf_system set datavalue = ? 
			    where dataname = 'r_MarkEntryTerm'");
    $sth->execute( $datavalue );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

    
    if ( not $DBI::errstr  ) {
	print qq{<h3>$lex{'Mark Entry'} $lex{Updated}</h3>\n};

    } else {
	print qq{<h3>$lex{Error}:$DBI::errstr;</h3>\n};
    }

    # Now write the file update
    updateFiles('repcard');

    print qq{<form action="$self" method="post">\n};
    print qq{<input type="submit" value="$lex{Edit}"></form>\n};
    print qq{</body></html>\n};

    exit;

} # End of Update



#--------------
sub updateFiles {
#--------------

    # Note: needs file path $g_EtcPath to write files to.

    if ( not -e $g_EtcPath ) {
	print qq{<h3>$lex{Path} $lex{'Not Found'}</h3>\n};
	exit;
    }

    my $singlefile = shift;

    my @files;
    if ( $singlefile ) {
	push @files, $singlefile;

    } else { # do them all
	my $sth = $dbh->prepare("select distinct filename from conf_system 
				where filename is not NULL and filename != ''  
				order by filename");
	$sth->execute;
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	while ( my $filename = $sth->fetchrow ) {
	    push @files, $filename;
	}
    }


    foreach my $updatefile ( @files ) {

	my $filename = "$g_EtcPath/$updatefile.conf";
	
	print qq{<div>$lex{Update}: $filename</div>\n};

	# special case for admin.conf
	if ( $updatefile eq 'admin' ) { # use the admin.conf.root file.
	    unless ( -e "$g_EtcPath/admin.conf.root" ) {
		print qq{<h3>$g_EtcPath}. '/admin.conf.root'. qq{ $lex{'Not Found'}</h3>\n};
	    }
	    system("cp -f $g_EtcPath/admin.conf.root $g_EtcPath/admin.conf");
	    # print "Result:", $? >> 8, "<br>\n";

	    open(FH,">>$filename") or
		die "Cannot open file $filename: $!\n"; # open for append
	} else {
	    open(FH,">$filename") or
		die "Cannot open file $filename: $!\n";
	}


        my $sth = $dbh->prepare("select id, datavalue from conf_system 
				where filename = ? order by dataname");
	$sth->execute( $updatefile );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

	while ( my ($id, $value) = $sth->fetchrow ) {
	    print FH $value, "\n";
	}

	print FH qq{\n1;\n};
	close FH;

	print qq{<h3>$lex{File} $lex{Updated}: $updatefile</h3>\n};
    }

    if ( $singlefile ) { 
	return; 
    } else { # did them all
	print qq{</body></html>\n};
	exit;
    }
}

