#!/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 %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 = 'confadminedit.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;

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


# Page Header
my $title = "$lex{Edit} $lex{Configuration} - ADMIN VERSION";
print qq{$doctype\n<html><head><title>$title</title>
<link rel="stylesheet" href="$css" type="text/css">
$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} ) {
    showStartPage();

} elsif ( $arr{page} == 1 ) {
    delete $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 id, dataname, sectionname, sequenceval
      from conf_system where filename = ? order by sectionname, sequenceval, dataname"); 
    $sth->execute( $arr{filename} );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

    my $fileview = ucfirst $arr{filename};
    print qq{<h3 style="display:inline;">$fileview</h3>\n};

    # 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 ( $id, $dataname, $sectionname, $sequenceval ) = $sth->fetchrow ) {

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

	    print qq{<h3>$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><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}; }

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

    # 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 $fileview = ucfirst $arr{filename}. '.conf';
    print qq{<h3>$fileview</h3>\n};

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

    my ($prevsection, $currsection);

    while ( my ( $id, $groupname, $dataname, $datatype, $datavalue ) = $sth->fetchrow ) {

	$prevsection = $currsection;
	$currsection = $groupname;

	if ( $currsection ne $prevsection ) {
	    print qq{<tr><th></th><th>$lex{Name}</th><th>$lex{Section}</th><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>$groupname</td><td>$datatype</td><td>$datavalue</td></tr>\n};
	
    }

    print qq{</table></center></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="bra">$lex{File}</td><td>$rec{filename}</td></tr>\n};

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

    # Sequence Value
    print qq{<tr><td class="bra">$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="bra">$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="bra">$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="bra">$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="bra">$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="bra">$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="bra">$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;
    }
}

