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

#  This file is part of Open Admin for Schools.

# Edit ALL configuration values in a single screen.

my %lex = ('Eoy' => 'Eoy',
	   'Configuration' => 'Configuration',
	   'Error' => 'Error',
	   'Edit' => 'Edit',
	   'View' => 'View',
	   'Section' => 'Section',
	   'Name' => 'Name',
	   'Value' => 'Value',
	   'Type' => 'Type',
	   'Update Record(s)' => 'Update Record(s)',
	   'Version' => 'Version',
	   'Description' => 'Description',
	   'Sequence' => 'Sequence',
	   'File' => 'File',
	   'Linked' => 'Linked',
	   'Record(s) Updated' => 'Record(s) Updated',
	   'No Change' => 'No Change',
	   'Eoy' => 'Eoy',
	   'Variable' => 'Variable',
	   'Admin' => 'Admin',
	   'Main' => 'Main',
	   'Start' => 'Start',
	   'Set' => 'Set',
	   'Save' => 'Save',
	   'Update' => 'Update',

	   );

my $self = 'confadminedall.pl';

my @types = qw( scalar scalaronoff array hash hashofarray arrayofhash ); # data types


use DBI;
use CGI;

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

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

#$dbase = 'temp';
#$user = 'root';
#$password = 'rootpwd';


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


# Page Header
my $title = qq{$lex{Edit} $lex{Configuration} - ADMIN VERSION};
print qq{$doctype\n<html><head><title>$title</title>
<link rel="stylesheet" href="$css" type="text/css">
<style type="text/css">td.ra { text-align:right;font-weight:bold;}</style>
$chartype\n</head><body>\n};
print qq{[ <a href="$homepage">$lex{Main}</a> |\n};
print qq{<a href="$eoypage">$lex{Eoy}</a> |\n};
print qq{<a href="$self">$lex{Start}</a> ]\n};

print qq{<h1 style="display:inline;">$title</h1>\n};

#foreach my $key ( keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }

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

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

} elsif ( $arr{page} == 3 ) {
    delete $arr{page};
    writeValues();

} elsif ( $arr{page} == 4 ) { # reset filename records (sectionname sequenceval)
    delete $arr{page};
    getField(); 

} elsif ( $arr{page} == 5 ) {
    delete $arr{page};
    setField(); # write reset to all records.

} elsif ( $arr{page} == 6 ) {
    delete $arr{page};
    updateFiles(); # rewrite files from conf_system table;
}



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

    # Select Main Filename Sections to Display
    my $sth = $dbh->prepare("select distinct filename from conf_system order by filename"); 
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

    print qq{<p></p><table cellpadding="10" cellspacing="0" border="1" style="margin:2em;">\n};
    while ( my $filename = $sth->fetchrow ) {

	my $fileview = ucfirst $filename. '.conf';

	print qq{<tr><td><form action="$self"  method="post">\n};
	print qq{<input type="hidden" name="filename" value="$filename">\n};
	print qq{<input type="hidden" name="page" value="1">\n};
	print qq{<input type="submit" value="$lex{Edit} $fileview"></form></td></tr>\n};

    }

    # Update Files
    print qq{<tr><td><form action="$self"  method="post">\n};
    print qq{<input type="hidden" name="page" value="4">\n};
    print qq{<input type="submit" value="$lex{Update} $lex{Files}"></form></td></tr>\n};


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

}

#-----------
sub getField { # page 4
#-----------

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

    my $sth = $dbh->prepare("select * from conf_system 
			    order by filename, sectionname, sequenceval, dataname"); 
    $sth->execute;
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

    # Start Form
    print qq{<form action="$self"  method="post">\n};
    print qq{<input type="hidden" name="page" value="5">\n};

    print qq{<h3><input type="submit" value="$lex{Save}"></h3>\n};

    my $prevname = '';
    my $first = 1;

    while ( my $ref = $sth->fetchrow_hashref ) {
	my %r = %$ref;
	my $id = $r{id};
	my $dataname = $r{dataname};
	my $sectionname = $r{sectionname};
	my $sequenceval = $r{sequenceval};

	if ( $prevname ne $sectionname or not $sectionname ) {
	    if ( not $first ) { print qq{</table>\n}; } else { $first = 0; }

	    print qq{<h3>$r{filename} - $sectionname</h3>\n};
	    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
	    print qq{<tr><th>$lex{Name}</th><th>$lex{Section}</th><th>Sequence $lex{Value}</th></tr>\n};
	}
	$prevname = $sectionname;

	print qq{<tr><td>$dataname</td>};
	print qq{<td><input type="text" name="S:$id" size="20" value="$sectionname"></td>};
	print qq{<td><input type="text" name="V:$id" value="$sequenceval" size="4"></td></tr>\n};

    }

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

    exit;

}  # end of getField




#-------------
sub showValues {
#-------------

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


    # Section Form
    print qq{<form action="$self"  method="post" style="display:inline">\n};
    print qq{<input type="hidden" name="page" value="4">\n};
    print qq{<input type="hidden" name="filename" value="$arr{filename}">\n};
    print qq{<input type="submit" value="$lex{Set} $lex{Section}"></form>\n};


    my $sth = $dbh->prepare("select * from conf_system 
			    order by filename, sectionname, sequenceval, dataname"); 
    $sth->execute;
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }


    # Print Table Heading.
    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};

    my ($prevsection, $currsection);

    while ( my $ref = $sth->fetchrow_hashref ) {
	my %r = %$ref;
	my $id = $r{id};
	my $dataname = $r{dataname};
	my $datatype = $r{datatype};
	my $datavalue = $r{datavalue};
	my $sectionname = $r{sectionname};

	$prevsection = $currsection;
	$currsection = $sectionname;

	if ( $currsection ne $prevsection ) {
	    print qq{<tr><th>$r{filename}</th><th>$lex{Name}</th><th>$lex{Section}</th>};
	    print qq{<th>$lex{Type}</th><th>$lex{Value}</th></tr>\n};
	}

	$datavalue =~ s/\</&lt;/g;
	$datavalue =~ s/\>/&gt;/g;

	print qq{<tr><td><form action="$self"  method="post">\n};
	print qq{<input type="hidden" name="id" value="$id">\n};
	print qq{<input type="hidden" name="page" value="2">\n};
	print qq{<input type="submit" value="$lex{Edit}"></form></td>\n};

	print qq{<td>$dataname</td><td>$sectionname</td><td>$datatype</td><td>$datavalue</td></tr>\n};
	
    }

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

    exit;

}  # end of showValues



#-------------
sub editValues { # edit record whose is id passed
#-------------

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


    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="3">\n};
    print qq{<input type="hidden" name="id" value="$arr{id}">\n};
    print qq{<p><input type="submit" value="$lex{'Update Record(s)'} "></p>\n};

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


    print qq{<table cellpadding="3" cellspacing="0" border="0">\n};

    # File Name
    print qq{<tr><td class="ra">$lex{File}</td><td>$rec{filename}</td></tr>\n};

    # Section Name
    print qq{<tr><td class="ra">$lex{Section}</td>\n};
    print qq{<td><input type="text" name="sectionname" size="20" value="$rec{sectionname}">};
    print qq{</td></tr>\n};

    # Sequence Value
    print qq{<tr><td class="ra">$lex{Sequence}</td>\n<td>};
    print qq{<input type="text" name="sequenceval" size="5" value="$rec{sequenceval}"></td></tr>\n};

    # Data Name
    print qq{<tr><td class="ra">$lex{Name}</td>\n<td>};
    print qq{<input type="text" name="dataname" size="20" value="$rec{dataname}"></td></tr>\n};

    # Data Value
    print qq{<tr><td class="ra">$lex{Value}</td>\n<td>};
    print qq{<textarea name="datavalue" rows="4" cols="60">$rec{datavalue}</textarea></td></tr>\n};


    # Datatype
    print qq{<tr><td class="ra">$lex{Type}</td>\n<td>};
    print qq{<select name="datatype"><option>$rec{datatype}</option>\n};
    foreach my $type ( @types ) {
	if ( $type ne $rec{datatype} ) { print qq{<option>$type</option>\n}; }
    }
    print qq{<option></option></select>\n};


    # Linked hashvar  (which supplies values)
    print qq{<tr><td class="ra">$lex{Linked} $lex{Variable}</td>\n<td>};
    print qq{<input type="text" name="hashvar" value="$rec{hashvar}" size="15"></td></tr>\n};


    # Version
    print qq{<tr><td class="ra">$lex{Version}</td>\n<td>};
    print qq{<input type="text" name="version" size="20" value="$rec{version}"></td></tr>\n};


    # Description
    print qq{<tr><td class="ra">$lex{Description}</td>\n<td>};
    print qq{<textarea rows="4" cols="80" name="description">$rec{description}</textarea></td></tr>\n};


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

    print qq{<input type="submit" value="$lex{'Update Record(s)'} ">\n};
    print qq{</form></body></html>\n};

    exit;


} # end of editValues



#--------------
sub writeValues {
#--------------
    
    # foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }

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

    # 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 %orig = %$ref;
    my $filename = $orig{filename};

    print qq{<table cellpadding="3" cellspacing="0" border="0">\n};
    my $count;

    foreach my $key ( sort keys %arr ) {

	# Check for update, skip if no change.
	if ( $arr{$key} eq $orig{$key} ) { next; }

	my $sth = $dbh->prepare("update conf_system set $key = ? where id = ?");
	$sth->execute( $arr{$key}, $id );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }

	# print line for this record.
	$count++;
	print qq{<tr><td>$count. <b>$key</b>: $orig{$key}</td><td>=> $arr{$key}</td></tr>\n};

	
    } # Next Field;

    print qq{</table>\n};

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

    } else {
	print qq{<h3>$lex{'No Change'}</h3>\n};
    }

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

    exit;

} # End of writeValues;


#-----------
sub setField {
#-----------
    
    # foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }

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

    # Set SQL
    my $sth1 = $dbh->prepare("update conf_system set sectionname = ? where id = ?");
    my $sth2 = $dbh->prepare("update conf_system set sequenceval = ? where id = ?");


    foreach my $key ( sort keys %arr ) {

	my ($type, $id) = split(':', $key );

	if ( $type eq 'S' ) { # sectionname
#	    print qq{S ID:$id Value:$arr{$key}<br>\n};
	    $sth1->execute( $arr{$key}, $id );
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }

	} elsif ( $type eq 'V' ) { # sequenceval
#	    print qq{V ID:$id Value:$arr{$key}<br>\n};
	    $sth2->execute( $arr{$key}, $id );
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	}
	
    } # Next Field;

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

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

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



#--------------
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 = qq{$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 qq{Cannot open file $filename: $!\n}; # open for append
	} else {
	    open(FH,">$filename") or
		die qq{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, qq{\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;
    }
}

