#! /usr/bin/perl
#  Copyright 2001-2024 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 $templatepath = '../template/';

my %lex = ('Main' => 'Main',
	   'Information' => 'Information',
	   'School' => 'School',
	   'Set' => 'Set',
	   'Error' => 'Error',
	   'Save' => 'Save',
	   'Path' => 'Path',
	   'Record(s)' => 'Record(s)',
	   'Updated' => 'Updated',
	   'File' => 'File',
	   'Edit' => 'Edit',
	   'Eoy' => 'Eoy',
	   'Not Found' => 'Not Found',
	   'Update' => 'Update',

	   );

my $self = 'confschoolinfo.pl';

my $filename = 'admin';
my $sectionname = 'schooladdress';

use DBI;
use CGI;

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

eval require "../../lib/liblatex.pl";
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{School} $lex{Information}";
print qq{$doctype\n<html><head><title>$title</title>
<link rel="stylesheet" href="$css" type="text/css">
$chartype\n</head><body>\n};

print qq{<p>[ <a href="$homepage">$lex{Main}</a> |\n};
print qq{ <a href="$eoypage">$lex{Eoy}</a> ]</p>\n};

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

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



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

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



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

    # 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="0">\n};


    # Load Existing Configuration Data.
    my $sth = $dbh->prepare("select * from conf_system 
      where filename = ? and sectionname = ? order by sequenceval"); 
    $sth->execute( $filename, $sectionname );
    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};

	print qq{<tr><td class="bra">$dataname</td>};
	print qq{<td class="la"><input type="text" size="40" name="$ref->{id}" value="$$dataname">\n};
	print qq{</td><td class="la">$ref->{description}</td></tr>\n};
    }

    print qq{<tr><td align="center" colspan="2">\n};
    print qq{<input type="submit" value="$lex{Save}"></td></tr>\n};
    print qq{</table></form>\n};

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

    exit;

}



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

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


    my $updatefile = $filename; # defined at top of script.
    # needed to write the file level update.

    foreach my $id ( keys %arr ) {


	# Get the original record
	my $sth = $dbh->prepare("select * from conf_system where id = ?");
	$sth->execute( $id );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $ref = $sth->fetchrow_hashref;

	my $type = $ref->{datatype};
	my $dataname = $ref->{dataname};
	my $value_ref = [ ];
	my $name_ref = [ ];


	my $sth = $dbh->prepare("update conf_system set datavalue = ? where id = ?");


	# only Scalar Value
	push @$name_ref, $dataname;
	push @$value_ref, $arr{$id};
    
	
	my $d = Data::Dumper->new( $value_ref, $name_ref );
	my $datavalue = $d->Dump;

	# print "Datavalue: $datavalue<br>\n";
	$sth->execute( $datavalue, $id );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

    }

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

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


    # Now write the file update, if requested.
#    if ( $updatefile ) {
#	print qq{Updating File<br>\n};
#	updateFiles( $updatefile );
#    }


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

    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'. " $lex{'Not Found'}</h3>\n};
	    }
	    system("cp -f $g_EtcPath/admin.conf.root $g_EtcPath/admin.conf");
	    # print qq{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 "\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;
    }
}

