#!/usr/bin/perl
#  Copyright 2001-2018 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 = ('Withdraw' => 'Withdraw',
	   'Staff' => 'Staff',
	   'Not Found' => 'Not Found',
	   'Withdrawn' => 'Withdrawn',
	   'Main' => 'Main',
	   'Error' => 'Error',
	   'Search' => 'Search',
	   'Name' => 'Name',
	   'Birthdate' => 'Birthdate',
	   'Grade' => 'Grade',
	   'Homeroom' => 'Homeroom',
	   'Description' => 'Description',
	   'Reason' => 'Reason',
	   'Code' => 'Code',
	   'Transfer' => 'Transfer',
	   'Date' => 'Date',
	   'Yes' => 'Yes',
	   'Delete' => 'Delete',
	   'Insert' => 'Insert',
	   'Select' => 'Select',
	   'Userid' => 'Userid',
	   'Position' => 'Position',
	   'Eoy' => 'Eoy',

	   );

use DBI;
use CGI;

my $self = 'staffwithdraw.pl';

eval require qq{../../etc/admin.conf};
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 = qq{DBI:$dbtype:dbname=$dbase};
my $dbh = DBI->connect($dsn,$user,$password);



# Page Header
my $title = qq{$lex{Withdraw} $lex{Staff}};
print qq{$doctype\n<html><head><title>$title</title>
<link rel="stylesheet" href="$css" type="text/css">\n};

if ( $arr{page} == 1 ) { # calendar popup.
    print qq{<link rel="stylesheet" type="text/css" media="all" };
    print qq{href="/js/calendar-blue.css" title="blue">\n};
    print qq{<script type="text/javascript" src="/js/calendar.js"></script>\n};
    print qq{<script type="text/javascript" src="/js/lang/calendar-en.js"></script>\n};
    print qq{<script type="text/javascript" src="/js/calendar-setup.js"></script>\n};
}

print qq{$chartype\n</head>\n};
if ( not $arr{page} ) {
    print qq{<body onload="document.forms[0].elements[1].focus()">\n};
} else {
    print qq{<body>\n};
}


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


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

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

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




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

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

    print qq{<table cellpadding="3" cellspacing="0" border="0" };
    print qq{style="padding:0.5em;border:1px solid gray;">\n};
    print qq{<tr><th></th><th>$lex{Staff}</th><th>$lex{Position}</th></tr>\n};
    print qq{<caption>$lex{Select} $lex{Staff} to $lex{Withdraw}</caption>\n};

    # Get Position and homeroom if any
    my $sth1 = $dbh->prepare("select field_value from staff_multi where field_name = ? and userid = ?");
    
    # Get all staff members.
    my $sth = $dbh->prepare("select lastname, firstname, userid, id from staff order by lastname, firstname");
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    
    while ( my $ref = $sth->fetchrow_hashref ) {
	my %r = %$ref;

	# Get Position
	$sth1->execute('position', $r{userid} );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $position = $sth1->fetchrow;
		
	print qq{<tr><td class="ra"><input type="radio" name="userid" value="$r{userid}"></td>\n};
	print qq{<td><b>$r{lastname}</b>, $r{firstname}</td><td>$position</td></tr>\n};
    }

    print qq{<tr><td class="la" colspan="3"><input type="submit" value="$lex{Withdraw}"></td></tr>\n};
    print qq{</form>\n};
    print qq{</body></html>\n};

    exit;

} # end of showStartPage


#------------------
sub confirmWithdraw {
#------------------

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

    my $userid = $arr{userid};

    # Set current time
    my @tim = localtime(time);
    my $year = @tim[5] + 1900;
    my $month = @tim[4] + 1;
    my $day = @tim[3];
    my $currdate = qq{$year-$month-$day};


    # Read the staff data.
    $sth = $dbh->prepare("select * from staff where userid = ?"); 
    $sth->execute( $userid );
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    my $ref = $sth->fetchrow_hashref;
    my %r = %$ref;

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

    
    print qq{<table cellspacing="0" cellpadding="3" border="0">\n};
    print qq{<tr><td class="bra">$lex{Name}</td><td class="la">$r{firstname} $r{lastname}</td></tr>\n};
    print qq{<tr><td class="bra">$lex{Userid}</td><td class="la">$userid</td></tr>\n};

    # Blank row
    # print qq{<tr><td class="ra">&nbsp;</td><td class="la"></td></tr>\n};


    
    # Withdraw Date
    print qq{<tr><td class="ra">$lex{Withdraw} $lex{Date}</td>\n};
    print qq{<td class="la"><input type="text" name="date" id="date" size="10" value="$currdate">\n};
    print qq{<button type="reset" id="start_trigger">...</button>\n};
    print qq{</td></tr>\n};

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

    # Submit
    print qq{<tr><td colspan="2" class="cn"><input type="submit" };
    print qq{value = "$lex{Yes}, $lex{Withdraw} $firstname $lastname"></td></tr>\n};
    
    print qq{</table></form>\n};

    print qq{<script type="text/javascript">
     Calendar.setup({
        inputField     :    "date", 
        ifFormat       :    "%Y-%m-%d",
        button         :    "start_trigger",
        singleClick    :    false,
        step           :    1
    });
    </script>\n};

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

    exit;
}



#------------------
sub withdrawStaff {
#------------------

    # foreach my $key (keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }
    # Date, Userid, Description passed.

    my $sth = $dbh->prepare("select * from staff where userid = ?"); 
    $sth->execute( $arr{userid} );
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    my $ref = $sth->fetchrow_hashref;
    my %r = %$ref;

    if ( not $ref ) { #Error!
	print qq{<h1>$lex{Error}: $lex{'Not Found'}!</h1>\n};
	print qq{</body></html>\n};
	exit;
    }

    delete $r{id};

    # Insert Staff Record into WD staff table
    my (@fields, @qst, @values);
    foreach my $fld (keys %r ) {
	if ( defined $r{$fld} ) {
	    push @fields, $fld;
	    push @qst, '?';
	    push @values, $r{$fld};
	}
    }
    my $fields = join(',', @fields);
    my $qst = join(',', @qst);

    $sth = $dbh->prepare("insert into staffwd ( $fields ) values ( $qst )");
    $sth->execute( @values );

    if ( $DBI::errstr) {
	print qq{<h3>$lex{Insert} $lex{Staff} $lex{Error}:};
	print qq{$lex{Error}:$DBI::errstr</h3>\n};
	die qq{$lex{Error}:$self: $DBI::errstr\n};
    }
    
    print qq{<h3>$lex{Staff} -> $lex{Withdrawn} $lex{Staff}</h3>\n};


    # Delete Original Staff Record from staff table
    $sth = $dbh->prepare("delete from staff where userid = ?"); 
    $sth->execute( $arr{userid} );

    if ( $DBI::errstr) {
	print qq{<h3>$lex{Delete} $lex{Staff} $lex{Error}:};
	print qq{$lex{Error}:$DBI::errstr</h3>\n};
	die qq{$lex{Delete} $lex{Staff} $lex{Error}:$self: $DBI::errstr\n};
    }


    # Get Any values from the multi table and append to the description value, if any.
    my $multivals;
    $sth = $dbh->prepare("select * from staff_multi where userid = ?"); 
    $sth->execute( $arr{userid} );
    while ( my $ref = $sth->fetchrow_hashref ) {
	my %r = %$ref;
#	print qq{R:$r{field_name} - $r{field_value}<br>\n};
	$multivals .= "$r{field_name}:$r{field_value}, ";
#	print qq{Multivals:$multivals<br>\n};
    }

    if ( $multivals ) {
	$arr{description} .= "\n$multivals";
    }

    # Delete the multi record values, if any
    $sth = $dbh->prepare("delete from staff_multi where userid = ?"); 
    $sth->execute( $arr{userid} );
    

    # Insert a enrol/withdraw record.
    $sth = $dbh->prepare("insert into staff_transfer 
      ( userid, date, type, description, lastname, firstname, certificatenumber ) 
      values ( ?, ?, ?, ?, ?, ?, ? )");

    $sth->execute( $arr{userid}, $arr{date}, 'withdraw', $arr{description},
		   $r{lastname}, $r{firstname}, $r{certification1} ); 

    if ($DBI::errstr) {
	print qq{<h3>$lex{Insert} $lex{Error}:};
	print qq{$lex{Error}:$DBI::errstr</h3>\n};
	die qq{$lex{Insert} $lex{Error}:$self: $DBI::errstr\n};
    }


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

    exit;
    
} # end of withdrawStaff
