#!/usr/bin/perl
#  Copyright 2001-2021 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.

%lex = ('Edit' => 'Edit',
	'Staff Member' => 'Staff Member',
	'Main' => 'Main',
	'Eoy' => 'Eoy',
	'Contact' => 'Contact',
	'Update' => 'Update',
	'Error' => 'Error',
	'Password' => 'Password',
	'You MUST have a unique userid and a password' => 
	  'You MUST have a unique userid and a password',
	'Grades' => 'Grades',
	'Homeroom(s)' => 'Homeroom(s)',
	'Position' => 'Position',
	'Record Added/Updated' => 'Record Added/Updated',
	'Separate with Spaces' => 'Separate with Spaces',
	'Add' => 'Add',
	'Required' => 'Required',
	'Bold' => 'Bold',
	'Preregistration' => 'Preregistration',
	'Access Control(s)' => 'Access Control(s)',
	'Current' => 'Current',
	'Spaces Not Allowed' => 'Spaces Not Allowed',
	'Type' => 'Type',
	'Percent' => 'Percent',
	'Occupation' => 'Occupation',
	'Userid Already Exists' => 'Userid Already Exists',
	'Staff' => 'Staff',

	'Save' => 'Save',
	 );


my $self = 'staffEditSecondary.pl';

use CGI;
use DBI;
use Data::Password qw(:all);  # for password checking...
use Crypt::GeneratePassword qw(:all); # password generation.

# First Nations settings.
my $maxmulti = 4; # Occupation Limits for INAC First Nations occupations.
my $template = 'staff.tpl';
my $fnmode; # set below configuration load.



# Password config; rest in admin.conf
# For Generation
$g_staffpwd_minfreq = .001;
$g_staffpwd_avgfreq = .001;
$g_staffpwd_lang = 'en'; # only en or de available.


# For Checking
my $g_staffpwd_groups = 0; # turn off character group (uppercase, lowercase, symbols) checking
my $g_staffpwd_following = 0; # turn off following character checking (keyboard, same)


# WATCH: Only loading userids and passwords here!
eval require "../../etc/admin.conf.root";
if ( $@ ) {
    print $lex{Error}. ": $@<br>\n";
    die $lex{Error}. ": $@\n";
}

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


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


# Load Configuration Variables;
my $sth = $dbh->prepare("select id, datavalue from conf_system where filename = 'admin'");
$sth->execute;
if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
while (	my ($id, $datavalue) = $sth->fetchrow ) {
    eval $datavalue;
    if ( $@ ) {
	print "$lex{Error}: $@<br>\n";
	die "$lex{Error}: $@\n";
    }
}


# Print Page Header
my $title = qq{$lex{Add}/$lex{Edit} Secondary Users};
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 style="margin:1em;">\n};
print qq{[ <a href="$homepage">$lex{Main}</a> | };
print qq{<a href="$eoypage">$lex{Eoy}</a> ]\n};

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

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

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


#----------------
sub showStartPage { # add basic entry values
#----------------

    # Get Distinct Bands
    my @bands;
    my $sth = $dbh->prepare("select distinct band from student 
			    where band is not NULL and band != ''  order by band");
    $sth->execute;
    if (DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $band = $sth->fetchrow ) {
	push @bands, $band;
    }

    # select values from staff_secondary table.
    $sth = $dbh->prepare("select * from staff_secondary where id = ?");
    $sth->execute( $arr{id} );
    if (DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    my $ref = $sth->fetchrow_hashref;
    my %r = %$ref;

    
    if (not $r{access}) { $r{access} = 'Attendance'; }


    # Now set password, other config values at top of script
    if ( not $r{password} ) {
	my $pwd = word( $g_staffpwd_minlen, $g_staffpwd_genlen,
			$g_staffpwd_lang, $g_staffpwd_signs,
			$g_staffpwd_caps, $g_staffpwd_minfreq,
			$g_staffpwd_avgfreq );

	$r{password} = $pwd;
    }


    
    # 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" border="1" cellspacing="0">\n};
    
    print qq{<tr><td class="bra">First Name</td>};
    print qq{<td class="la"><input type="text" name="firstname" };
    print qq{style="width:30ch;" value="$r{firstname}"></td></tr>\n};

    print qq{<tr><td class="bra">Last Name</td>};
    print qq{<td class="la"><input type="text" name="lastname" };
    print qq{style="width:30ch;" value="$r{lastname}"></td></tr>\n};

    print qq{<tr><td class="bra">User Id</td>};
    print qq{<td class="la"><input type="text" name="userid" };
    print qq{style="width:15ch;" value="$r{userid}"></td></tr>\n};

    print qq{<tr><td class="bra">Password</td>};
    print qq{<td class="la"><input type="text" name="password" };
    print qq{style="width:10ch;" value="$r{password}"></td></tr>\n};

    print qq{<tr><td class="bra">Position/Role</td>};
    print qq{<td class="la"><input type="text" name="position" };
    print qq{style="width:30ch;" value="$r{position}"></td></tr>\n};

    print qq{<tr><td class="bra">Access</td>};
    print qq{<td class="la"><input type="text" name="access" };
    print qq{style="width:20ch;" value="$r{access}"></td></tr>\n};
    
    print qq{<tr><td class="bra">Band</td>};
    print qq{<td class="la"><select name="band"><option>$r{band}</option>\n};
    foreach my $band ( @bands ) {
	print qq{<option>$band</option>\n};
    }

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

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

    exit;
} # end of showStartPage



#--------------
sub writeRecord {
#--------------

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

    # Extract the Occupations Fields, if present
    my %occ; # occupation structure
    foreach my $key ( sort keys %arr) {
	my @vals = split(':', $key );
	if ( $vals[1] ) { # we have some stuff to take care of.
	    if ( $vals[0] eq 'm' ) { next; } # skip multirecs.
	    if ( $arr{$key} ) { # if a defined value, add to structure
		if ( $#vals == 2 ) {
		    $occ{"$vals[0]"}{"$vals[1]"}{"$vals[2]"} = $arr{$key};
		} else {
		    $occ{"$vals[0]"}{"$vals[1]"} = $arr{$key};
		}
	    }
	    delete $arr{$key};
	}
     }

    if ( %occ ) {
	my $value_ref = [ ];
	my $name_ref = [ ];

	$dataname = '*occ';
	push @$name_ref, $dataname;
	push @$value_ref, \%occ;

	my $d = Data::Dumper->new( $value_ref, $name_ref );
	my $occupations = $d->Dump;
	$arr{'occupations'} = $occupations;
    }

#    print qq{<br><div>After Occupations Removed</div>\n};
#    foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }
#    exit;
    
=cut
    
    
    # Make sure we have userid, password
    if ( not $arr{userid} or not $arr{password} ){
	print qq{<h1>$lex{'You MUST have a unique userid and a password'}</h1>\n};
	print qq{</body></html>\n};
	exit;
    }


    # Check for password quality using Data::Password module.
    $MINLEN = $g_staffpwd_minlen;  # from admin.conf settings.
    $MAXLEN = $g_staffpwd_maxlen;
    $FOLLOWING = $g_staffpwd_following;
    $GROUPS = $g_staffpwd_groups;
    if ( $g_staffpwd_dictionary ) {
	$DICTIONARY = $g_staffpwd_dictionary;
    } else {
	$DICTIONARY = 0; # turn it off.
    }

    if ( IsBadPassword( $arr{password} )) {
	print qq{<h1 style="color:red;">$lex{Password} $lex{Error}<br>\n};
	print IsBadPassword( $arr{password} );
	print qq{</h1></body></html>\n};
	exit;
    }

    
    # Check for identical userid, if record updated.
    if ( $arr{id} ) { # we are editing
	$sth = $dbh->prepare("select lastname, firstname from staff_secondary 
			     where userid = ? and id != ?");
	$sth->execute( $arr{userid}, $arr{id} );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	while ( my ($lastname, $firstname ) = $sth->fetchrow ) {
	    print qq{<h1 style="color:red;">$lex{Error}: };
	    print qq{$lex{'Userid Already Exists'}: $firstname $lastname</h1>\n};
	    print qq{</body></html>\n};
	    exit;
	}
    }


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

    if ( $id ) { # we are updating existing records.

	# Update staff table records
	foreach my $key ( keys %arr ) {
	    if ( not $arr{$key} ) { undef $arr{$key}; } # NULL records
	    $sth = $dbh->prepare("update staff_secondary set $key = ? where id = $id");
	    $sth->execute( $arr{$key} );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	}

	
    } else {  # we are adding a record.....
	
	my %new = %arr;
	
	my @values;
	my @fieldnames;

	# push in the passed values (skip blanks since an add process)
	foreach my $key ( sort keys %new ) { # run through all passed values.
	    if ( $new{$key} ) {    # if we have a value
		push @values, $new{$key};
		push @fieldnames, $key;
	    }
	}


	# Join values
	my $fields = join(',', @fieldnames );
	foreach my $val ( @values ) {
	    $val = $dbh->quote( $val );
	}
	my $values = join(',', @values );


	# print "Insert Fields: $fields  Values: $values<br>\n";
	my $sth = $dbh->prepare("insert into staff_secondary ( $fields ) values( $values )");
	$sth->execute;
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	
	
    } # end of inserting a staff record;


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

    } else {
	print qq{<h3>$lex{Error}: $DBI::errstr<br>$lex{Contact} };
	print qq{$adminname - <a href="mailto:$adminemail">$adminemail</a></h3>\n};
    }


    # Don't really need these....
    # print qq{<p>[ <a href="$homepage">$lex{Main}</a> |};
    # print qq{ <a href="$eoypage">$lex{Eoy}</a> ]</p>\n};
    print qq{[ <a href = "./staffViewSecondary.pl">View/Edit Secondary Users</a> |\n};
    print qq{ <a href="$self">Add Secondary Users</a> ]\n};

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

    exit;

}
