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

my %lex = ('Main' => 'Main',
	   'Family' => 'Family',
	   'Name' => 'Name',
	   'Homeroom' => 'Homeroom',
	   'Grade' => 'Grade',
	   'Error' => 'Error',
	   'Continue' => 'Continue',

	   );

my $self = 'editFamily.pl';

use DBI;
use CGI;
use Cwd;


# Read config variables
eval require "../etc/admin.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;
my %arr = $q->Vars;
print $q->header( -charset, $charset );


my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, 
 $iddst) = localtime(time);
$year = $year + 1900;
$mon++;
$wday++;
my $currdate = "$dow[$wday], $month[$mon] $mday, $year";

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


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



my $title = qq{Edit Family};

# print page head
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><a name="top"></a>\n};

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

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

} elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    selectChanges();

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


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

    my @students;
    foreach my $key ( sort keys %arr ) {
	if ( $key !~ m/\D/ ) {
#	    print qq{K:$key V:$arr{$key}<br>\n};
	    push @students, $key;
	    delete $arr{$key};
	}
    }

    # only fields from parent section left here.
    my %newfields;
    foreach my $key ( sort keys %arr ) {
	if ( $arr{$key} ) { $newfields{$key} = $arr{$key}; }
    }

#    print "Students:", @students, "<br>\n";
#    print "Fields", %newfields, "<br>\n";

    if ( not @students or not %newfields ) {
	print qq{<h3>Missing Selections</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    print qq{<h3>Records Updated</h3>\n};
    
    print qq{<table border="1" cellpadding="3" cellspacing="0">\n};
    print qq{<tr><th>Student</th><th>Field</th><th>Original<br>Value</th><th>New<br>Value</th></tr>\n};
    
    foreach my $studnum ( @students ) {

	# Get student record
	my $sth = $dbh->prepare("select * from student where studnum = ?");
	$sth->execute( $studnum );
	if ($DBI::errstr) {print $DBI::errstr; die $DBI::errstr; }
	my $ref = $sth->fetchrow_hashref;
	my %r = %$ref;
	my ($firstname, $lastname) = ( $r{firstname}, $r{lastname} );

	# Loop over all fields to update.
	foreach my $field ( sort keys %newfields ) {
	    my $value = $newfields{$field};

	    my $sth = $dbh->prepare("update student set $field = ? where studnum = ?");
	    $sth->execute( $value, $studnum );
	    if ($DBI::errstr) {print $DBI::errstr; die $DBI::errstr; }
	    print qq{<tr><td>$firstname $lastname</td><td>$field</td> };
	    print qq{<td>$r{$field}</td><td>$value</td></tr>\n};

	}
    }

    print qq{</table>\n};

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

    exit;

}




#----------------
sub selectChanges {
#----------------
    
    # foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }
    # passed family value which is hphone1;
    
    my $phone = $arr{family};
    
    my (@student, %student, %lastnames );
    $sth = $dbh->prepare("select * from student 
      where hphone1 = ? order by lastname, firstname");
    $sth->execute( $phone );
    if ($DBI::errstr) {print $DBI::errstr; die $DBI::errstr; }

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

    my $first = 1;
    # Select Students to change (default is all).
    while ( my $ref = $sth->fetchrow_hashref ) {
	my %r = %$ref;
	my $studnum = $r{studnum};

	push @student, $studnum; # maintain name order.
	$student{$studnum} = $ref;
	$lastnames{$ref->{lastname}} = 1;

	if ( $first ) {
	    print qq{<table border="1" cellpadding="3" cellspacing="0" };
	    print qq{style="margin-bottom:1em;">\n};
	    print qq{<caption style="font-weight:bold;">Select Students to Update</caption>\n};
	    print qq{<tr><th>$lex{Name}</th>};
	    print qq{<th>$lex{Homeroom}</th><th>$lex{Grade}</th></tr>\n};
	    $first = 0;
	}

	print qq{<tr><td><input type="checkbox" name="$studnum" value="1" checked="checked">\n};
	print qq{<b>$r{lastname}</b>, $r{firstname}</td><td>$r{homeroom}</td>\n};
	print qq{<td>$r{grade}</td></tr>\n};
	
    }

    if ( not $first ) {
	print qq{</table>\n};
    }

    
    my $familyname = join('/', keys %lastnames);
    
    # put in new values for fields: Parent 1,2,Emergency
    print qq{<h3>Enter new value(s) to replace existing ones</h3>\n};



    # Read in Parent Template
    unless ( open (FH,"<../template/parent.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;

    #print "Formtext:$formtext\n";
    #print qq{<div>Here!</div>\n};

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

    print $formtext,"\n";
    
    print qq{<input type="submit" value="$lex{Continue}">\n};
    print qq{</form>\n};

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



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

    #foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }
    
    my $linksize = scalar @g_FamilyGroupLinkList;
    if ( not $arr{groupFld} and $linksize > 1 ) { # put up variable to select.
	print qq{<form action="$self" method="post">\n};
	#print qq{<input type="hidden" name="page" value="1">\n};
	print qq{<div>Select Family Link Field <select name="groupFld">}; #<option></option>};
	foreach my $fld ( @g_FamilyGroupLinkList ) {
	    print qq{<option value="$fld">$meta{$fld}</option>};
	}
	print qq{</select>\n <input type="submit" value="$lex{Continue}"></form>\n};
	exit;
    }
    my $groupFld = $arr{groupFld};
    my $altNameField = $g_FamilyGroupNameField;

    print qq{<h3>Group Students by $meta{$groupFld} ($groupFld)</h3>\n};
    
    
    # Display groups (families) and select one.
    my $sth = $dbh->prepare("select distinct $groupFld from student 
      where $groupFld != '' and $groupFld is not null");
    $sth->execute;
    if ($DBI::errstr) {print $DBI::errstr; die $DBI::errstr; }
    my @groupFields;
    # my $count;
    while ( my $fld = $sth->fetchrow ) {
	push @groupFields, $fld; #
    }

    # Now get family groupings by the field chosen
    # family groupings are in %family hash with {groupFld} -> @studnum array.

    my (@family, %familysize,%familyname, %altfamilyname);
    $sth = $dbh->prepare("select lastname, firstname, studnum, $altNameField from student 
      where $groupFld = ? order by lastname, firstname");

    foreach my $gfield ( @groupFields ) {

	# Get the family group based on this field value
	$sth->execute( $gfield );
	if ($DBI::errstr) {print $DBI::errstr; die $DBI::errstr; }

	my %familynames;
    
	# All of these people have the same group field value ($gfield)
	while ( my ( $lastname, $firstname, $studnum, $altname ) = $sth->fetchrow ) {

	    if ( $altname ) { $altfamilyname{$gfield} = $altname; };
	    
	    $familynames{$lastname} = 1; # all lastnames into a hash.
	    
	    if ( @{$family{$gfield}} ) { # that family already has studnums.
		push @{$family{$gfield}}, $studnum;
	    } else {
		$family{$gfield} = [ $studnum ];
	    }
	}

	my $famname = join('/', keys %familynames);
	$familyname{$gfield} = $famname;

	my $childcount = scalar @{ $family{$gfield} };
	$familysize{$childcount}{$famname}{$gfield} = $gfield;

    }

    print qq{<h3>Please Select Family</h3>\n};
    
    # Start the Form.
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<input type="submit" value="$lex{Continue}">\n};

    
    my $sth = $dbh->prepare("select lastname, firstname, homeroom, grade from student 
      where studnum = ?");

    foreach my $childcount ( sort {$b <=> $a}  keys %familysize ) {
	my $first = 1;
	my $famcount;
	foreach my $famname ( sort keys %{ $familysize{$childcount} } ) {
	    foreach my $gfield ( sort keys %{ $familysize{$childcount}{$famname} } ) {

		if ( $first ) {
		    print qq{<table border="1" cellpadding="3" cellspacing="0" };
		    print qq{style="margin-bottom:1em;">\n};
		    print qq{<caption style="font-weight:bold;font-size:120%;">};
		    print qq{$childcount Children</caption>\n};
		    print qq{<tr><th>$lex{Name}</th>};
		    print qq{<th>$lex{Homeroom}</th><th>$lex{Grade}</th></tr>\n};
		    $first = 0;
		}
	    
		print qq{<tr><td colspan="4"><input type="radio" name="family" value="$gfield">};
		my $famname;
		if ( $altfamilyname{$gfield} ) {
		    $famname = $altfamilyname{$gfield};
		} else {
		    $famname = $familyname{$gfield};
		}
		    
		print qq{<b>$famname</b> - $meta{$groupFld} $gfield</td></tr>\n};
		foreach my $studnum ( @{ $family{$gfield} } ) {
		    $sth->execute($studnum);
		    if ($DBI::errstr) {print $DBI::errstr; die $DBI::errstr; }
		    my ($lastname, $firstname, $homeroom, $grade ) = $sth->fetchrow;

		    print qq{<tr><td>$firstname $lastname ($studnum)</td>\n};
		    print qq{<td>$homeroom</td><td>$grade</td></tr>\n};
		}

		$famcount++;
		if ( $famcount % 8 == 0 ) { # print continue input.
		    print qq{<tr><td colspan="3">};
		    print qq{<input type="submit" value="$lex{Continue}"></td></tr>\n};
		}
		
	    } # gfield loop
	} # family name loop
	print qq{</table>\n};
	print qq{<input type="submit" value="$lex{Continue}">\n};
	
    } # count

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

} # end of showStartPage
