#!/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.

%lex = ( 'Edit' => 'Edit',
	 'Main' => 'Main',
	 'Record Updated' => 'Record Updated',
	 'Bold' => 'Bold',
	 'Required Field' => 'Required Field',
	 'Cannot open' => 'Cannot open',
	 'Edit Another Student' => 'Edit Another Student',
	 'Main' => 'Main',
	 'Contact' => 'Contact',
	 'Update' => 'Update',
	 'Withdrawn' => 'Withdrawn',
	 'Preregistration' => 'Preregistration',
	 'Record' => 'Record',
	 'Error' => 'Error',
	 'Students' => 'Students',
	 'Student' => 'Student',
	 'Password' => 'Password',
	 
	 );

use CGI;
use DBI;
use Data::Password qw(:all);


# Config values for password Check; Other values minlen, maxlen
# loaded from configuration; See Data::Password docs for meaning.
my $g_studentpwd_groups = 0; # turn off character group (uppercase, lowercase, symbols) checking
my $g_studentpwd_following = 0; # turn off following character checking (keyboard, same)
# my $g_studentpwd_dictionary = 4; # if leave blank here, zeroed below.


my $self = 'studed.pl';

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

# Need r_ShowStudentPicture value
eval require "../etc/repcard.conf";
if ( $@ ) {
    print $lex{Error}. ": $@<br>\n";
    die $lex{Error}. ": $@\n";
}

eval require "../lib/libmeta.pl";
if ( $@ ) {
    print $lex{Error}. " $@<br>\n";
    die $lex{Error}. " $@\n";
}


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


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


# Select table to Edit.
my ($table, $sth, $wd);
if ( not $arr{tb} ) { # no passed table to edit...
    $arr{tb} = 'student';
}

if ( $arr{tb} eq 'wd' ){ # if passed a tb=wd param, then edit alt table.
    $sth = $dbh->prepare("select * from studentwd where studid = ?");
    $wd = qq{<span style="color:red;">$lex{Withdrawn}</span>};
    $table = 'studentwd';

} elsif ( $arr{tb} eq 'prereg' ){ # if tb=pre then edit prereg table.
    $sth = $dbh->prepare("select * from prereg where studid = ?"); 
    $wd = qq{<span style="color:red;">$lex{Preregistration}</span>};
    $table = 'prereg';
} else {
    $sth = $dbh->prepare("select * from student where studid = ?"); 
    $table = 'student';
}

my $title = qq{$lex{Edit} $lex{Student}};
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="padding:1em;">\n};

print qq{[ <a href="$homepage">$lex{Main}</a> ]\n};
print qq{<h1>$title</h1>\n};


# Update the record
if ( $arr{writeflag} ) {
    delete $arr{writeflag};
    updateRecord();
}


# Load the record into a hash.
$sth->execute( $arr{id} );
if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr;}
my $ref = $sth->fetchrow_hashref;
my %rec = %$ref;
$studnum = $rec{studnum};

# Populate password field if blank.
if ( not $rec{password} ) { # Add a password.
    use Crypt::GeneratePassword qw(:all); # password generation.

    $g_studentpwd_minfreq = .001;
    $g_studentpwd_avgfreq = .001;
    $g_studentpwd_lang = 'en'; # only en or de available.

    my $password = word( $g_studentpwd_minlen, $g_studentpwd_maxlen,
			 $g_studentpwd_lang, $g_studentpwd_signs,
			 $g_studentpwd_caps, $g_studentpwd_minfreq,
			 $g_studentpwd_avgfreq );
    $rec{password} = $password
}


print qq{<form action="$self" method="post">\n};
print qq{<input type="hidden" name="id" value="$arr{id}">};
print qq{<input type="hidden" name="tb" value="$table">};
print qq{<input type="hidden" name="writeflag" value="1">\n};

print qq{<p><input type="submit" value="$lex{Update} $lex{Student}">\n};
print qq{ [ <span style="font-weight:bold;">$lex{Bold}</span> = };
print qq{$lex{'Required Field'} ]</p>\n};


# Read in Template
unless ( open (FH,"<../template/student.tpl") ) {
    print qq{$lex{'Cannot open'} template - $!\n};
    die qq{$lex{'Cannot open'} template - $!\n};
}
my $formtext;
{ local $/; $formtext = <FH>; close FH;}


# Create hash for fieldnames from meta.
my $sth = $dbh->prepare("select fieldid, fieldname, required from meta where tableid = ?");
$sth->execute( 'student' );
if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

my %fieldnames;
while ( my ( $fieldid, $fieldname, $required ) = $sth->fetchrow ) {
    if ( $required ) { # has any value
	$fieldname = qq{<span style="font-weight:bold;">$fieldname</span>};
    }
    $fieldnames{$fieldid} = $fieldname;
}

# Now put replacement fieldnames back in.
$formtext =~ s{\<\*(.*?)\*\>}
  { exists( $fieldnames{$1} ) 
	? $fieldnames{$1} 
	: $1
  }gsex;


# Find all fields , so we only wrap forms around them (typically
# faster than doing all fields in the table )
my @fields;
while ( $formtext =~ m/\<\@(.*)\@\>/g){
    push @fields, $1;
}


# get replacement values for fields, %rec holds values
my %values;
foreach my $fieldid ( @fields ) {
    $values{$fieldid} = metaInputField(
	'student', $fieldid, $rec{ $fieldid }, $dbh,'' );
}

# now put field values back into $text variable...
$formtext =~ s{ \<\@(.*?)\@\> }
  { exists($values{$1}) 
	? $values{$1} 
	: "$values{$1}-$1"
  }gsex;

# Check for a picture and picture mode (ShowStudentPicture)
if ( $r_ShowStudentPicture ) { # put in a table value with a picture link.
    if ( $rec{pic} ) {
	my $pictureform = qq{<div><img style="width:250px;" src="/pic-big/}. $studnum.
	    qq{.jpg"></div>\n};
	$formtext =~ s/\<a name=\"picture\"\>\<\/a\>/$pictureform/;
    }
}

# Print Student Record
print $formtext,"\n";

print qq{<input type="submit" value="$lex{Update} $lex{Student}">\n};
print qq{</form>\n\n};

# Display any medical information, put in Add / Edit buttons.
my $first = 1;
my %medical;
my $sth = $dbh->prepare("select * from student_medical where studnum = ?");
$sth->execute($studnum);
if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

while ( my $ref = $sth->fetchrow_hashref ) {
    $medical{$ref->{id}} = $ref;
    $first = 0;
}

print qq{<table style="background-color:#D8D8D8;border:1px solid black;margin:0.3em;};
print qq{margin-bottom:3em;padding:1em;">\n};
print qq{<tr><td colspan="3" style="font-size:120%;font-weight:bold;">Medical Information</td></tr>\n};

print qq{<tr><td>};
print qq{<form action="medical/medadd.pl" method="post" target="_blank">\n};
print qq{<input type="hidden" name="$studnum" value="1">};
print qq{<input type="hidden" name="page" value="2">};
print qq{<input type="submit" value="Add"></form></td>\n};

print qq{<td colspan="2" class="bcn">Open in New Tabs</td></tr>\n};

#print qq{<a href="medical/medadd.pl?$studnum=1&page=2" target="_blank">Add (new tab)</a></td></tr>\n};

foreach my $id ( keys %medical ) {
    my %r = %{$medical{$id}};
    print qq{<tr><td>};
    print qq{<form action="medical/meddeled.pl" method="post" target="_blank">\n};
    print qq{<input type="hidden" name="page" value="6">};
    print qq{<input type="hidden" name="id" value="$r{id}">};
    print qq{<input type="submit" value="Edit"></form></td>\n};

    print qq{<td class="bla">$r{category}</td><td>$r{description}</td></tr>\n};
}
print qq{</table>\n};
print qq{<p> </p>\n};

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



#---------------
sub updateRecord {
#---------------

    # foreach my $key ( sort keys %arr ) { print qq{K:$key VAL:$arr{$key}<br>\n}; }
    
    my $table = $arr{tb};
    delete $arr{tb}; # delete table value
    my $id = $arr{id};
    delete $arr{id};

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

    # check for Password Quality... rest of configs at top of script
    $MINLEN = $g_studentpwd_minlen;
    $MAXLEN = $g_studentpwd_maxlen;
    $GROUPS = $g_studentpwd_groups;
    $FOLLOWING = $g_studentpwd_following;
    if ( $g_studentpwd_dictionary ) {
	$DICTIONARY = $g_studentpwd_dictionary;
    } else {
	$DICTIONARY = 0; # turn it off.
    }

    
    if ( IsBadPassword( $arr{password} ) ) {
	print qq{<div style="color:red;font-size:150%;">};
	print qq{$lex{Password} $lex{Error}<br>\n};
	print IsBadPassword( $arr{password} );
	print qq{</div></body></html>\n};

	exit;
    }


    # update for any leading/trailing spaces in name, hsn, psn, and treaty.
    foreach my $field ( 'lastname', 'firstname', 'initial', 'treaty','provnum' ) {
	
	if ( $arr{$field} =~ m/^\s+/ ) { # leading spaces.
	    print qq{<div>Leading Space Found in $field. Removing.</div>\n};
	    $arr{$field} =~ s/^\s+//;
	    
	}
	
	if ( $arr{$field} =~ m/\s+$/ ) { # trailing spaces.
	    print qq{<div>Trailing Space Found in $field. Removing.</div>\n};
	    $arr{$field} =~ s/\s+$//;
	}
    }

    

    # Checkbox updates (since no returned values for these)
    my %checkboxfields;
    my $sth = $dbh->prepare("select distinct fieldid from meta 
      where tableid = 'student' and formtype = 'checkbox'");
    $sth->execute;
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr }
    while ( my $fieldid = $sth->fetchrow ) {
        $checkboxfields{$fieldid} = 1;
    }

    if ( not $arr{mssid} ) {
	$arr{mssid} = 0;
    }

    
    # Update Fields in Record
    foreach my $key ( keys %arr ) {

	# don't need to do these fields below
	if ( $checkboxfields{$key} ) { delete $checkboxfields{$key}; } 

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


    # Update any checkbox fields.
    foreach my $fieldid ( keys %checkboxfields ) {

	# if field HAS a value, then make it NULL, since checkboxes not passed in forms.
	# Load the field.
	my $sth = $dbh->prepare("select $fieldid from student where studid = ?");
	$sth->execute( $id );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr }
	my $val = $sth->fetchrow;

	# Null field if present
	if ( $val ) {
	    my $sth1 = $dbh->prepare("update student set $fieldid = NULL where studid = ?");
	    $sth1->execute( $id );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr }
	}
    }	


    if ( not $DBI::errstr ) {
	print qq{<span style="fontsize:120%;font-weight:bold;padding:1em;">};
	print qq{$lex{'Record Updated'}.</span>\n};
	
    } else { # we have an error
	print qq{<div><strong>$lex{Error}</strong><br>\n};
	print qq{$lex{Error}: $DBI::errstr</b></div>\n};
    }

    print qq{<p>[ <a href="studeled.pl">$lex{Edit} $lex{Students}</a> |\n};
    print qq{ <a href="$homepage">$lex{Main}</a> ]</p>\n};

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

    exit;

} # End of updateRecord
