#!/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 = ('Main' => 'Main',
	   'Eoy' => 'Eoy',
	   'Select' => 'Select',
	   'Student(s) Not Found' => 'Student(s) Not Found',
	   'Withdraw' => 'Withdraw',
	   'Transfer' => 'Transfer',
	   'Error' => 'Error',
	   'Insert' => 'Insert',
	   'Mass' => 'Mass',
	   'Grade' => 'Grade',
	   'Password' => 'Password',
	   'Description' => 'Description',
	   'Continue' => 'Continue',
	   'Students' => 'Students',
	   'Blank=All' => 'Blank=All',
	   'Date' => 'Date',
	   'Cannot open' => 'Cannot open',
	   'Reason' => 'Reason',

	   );

my $self = 'masswithdraw.pl';
my $pwd = 'tansi'; # later, pull from security system.

use DBI;
use CGI;


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

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



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


my $title = "$lex{Mass} $lex{Withdraw} $lex{Students}";

print qq{$doctype\n<html><head><title>$title</title>
<link rel="stylesheet" href="$css" type="text/css">\n};

if ( not $arr{page} ) { # 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><body>\n};
if ( not $arr{page} ) {
    print qq{<body onload="document.forms[0].elements[1].focus()" style="padding:1em 3em;">\n};
} else {
    print qq{<body style="padding:1em 3em;">\n};
}


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

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


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

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

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



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

    
    # Load Global Reasons (Exit)
    if ( not -e "$globdir/global.conf" ) {
	print qq{$lex{'Cannot open'} global.conf file!};
	print qq{</body></html>\n};
	exit;
    }

    # Read database names and also the global enrol/withdraw reasons.
    eval { require "$globdir/global.conf"; };
    if ( $@ ) {
	print qq{<h3>$lex{'Cannot open'} global.conf:\n $@</h3>\n};
	print qq{</body></html>\n};
	exit;
    }


    # Get current date
    my @tim = localtime(time);
    my $year = @tim[5] + 1900;
    my $month = @tim[4] + 1;
    my $day = @tim[3];
    my $currdate = "$year-$month-$day";


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


    # Password
    print qq{<tr><td class="bra">$lex{Password}</td>\n};
    print qq{<td class="la"><input type="password" name="password" size="12"></td></tr>\n};


    # Student Grade
    print qq{<tr><td class="bra">$lex{Grade}</td>\n};
    print qq{<td class="la"><input type="text" name="grade" size="4"> $lex{'Blank=All'}</td></tr>\n};


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

    # Withdraw Reason
    print qq{<tr><td class="bra">$lex{Withdraw} $lex{Reason}</td>\n};
    print qq{<td class="la"><select name="exittype"><option></option>\n};
    foreach my $type ( sort keys %g_wdraw ){
        print qq{<option value="$type">$g_wdraw{$type}</option>\n};
    }
    print qq{</select></td></tr>\n};

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


    print qq{<tr><td></td><td class="la"><input type="submit" value="$lex{Continue}"></td></tr>\n};
    print qq{</table></form>};

    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;

} # end of showStartPage



#-----------------
sub selectStudents { 
#-----------------

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

    # Check Password
    if ( not $arr{password} or $arr{password} ne $pwd ) {
	print qq{<div style="font-size:150%;font-weight:bold;padding:1em;">$lex{Password} $lex{Error}</div>\n};
	print qq{</body></html>\n};
	exit;
    }


    if ( $arr{grade} ) {
	$sth = $dbh->prepare("select * from student where grade = ? 
           order by grade, lastname, firstname");
	$sth->execute( $arr{grade} );
    } else {
	$sth = $dbh->prepare("select * from student 
           order by lastname, firstname"); 
	$sth->execute;
    }
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }

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

    print qq{<input type="hidden" name="description" value="$arr{description}">\n};
    print qq{<input type="hidden" name="exittype" value="$arr{exittype}">\n};
    print qq{<input type="hidden" name="date" value="$arr{date}">\n};

    print qq{<h2>$lex{Select} $lex{Students}</h2>\n};
    
    print qq{<table border="1" cellspacing="0" cellpadding="3">\n};
    print qq{<tr><th>$lex{Students}</th><th>$lex{Grade}</th></tr>\n};

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

    while ( my $ref = $sth->fetchrow_hashref ) {
	my %rec = ();
	%rec = %$ref;

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

    }

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

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

    exit;

} # end of selectStudents



#-------------------
sub withdrawStudents {
#-------------------

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

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

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

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

    # Put results into table format
    print qq{<table cellpadding="3" cellspacing="0" border="0">\n};

    foreach my $studnum ( keys %arr ) { # loop through passed student numbers

	# Get Student Info
	my $sth = $dbh->prepare("select * from student where studnum = ?"); 
	$sth->execute( $studnum );
	if ($DBI::errstr){ print $DBI::errstr; next; }
	my @student = $sth->fetchrow;
	my $lastname = $student[1];
	my $firstname = $student[2];


       # Load student record into hash
        $sth->execute( $studnum );
        if ($DBI::errstr){ print $DBI::errstr; next; }
        my $ref = $sth->fetchrow_hashref;
        my %rec = %$ref;
        # used to put values into transfer table.


	if ( not @student ){ 
	    print qq{<tr><td>$lex{'Student(s) Not Found'}: $studnum</td></tr>\n};
	    next;
	}

	# Insert Record in Student WD
	$student[0] = $sql{default};  # reset the studid/id.
	foreach my $studfld ( @student ){ 
	    if ( $studfld ne $sql{default} ) { $studfld = $dbh->quote( $studfld ); }
	}
	my $studentstr = join(', ', @student);

	$sth = $dbh->prepare("insert into studentwd values ( $studentstr )");
	$sth->execute;
	if ( $DBI::errstr ) { 
	    print qq{<tr><td>$lex{Insert} $lex{Error}: $firstname $lastname};
	    print qq{</td></tr>\n};
	    next;
	}

	# Remove from Student Table
	$sth = $dbh->prepare("delete from student where studnum = ?"); 
	$sth->execute( $studnum );
	if ( $DBI::errstr) {
	    print qq{<tr><td style="color:red;">$lex{Withdraw} $lex{Error}};
	    print qq{ $firstname $lastname: $DBI::errstr</font></td></tr>\n};
	} else {
	    print qq{<tr><td>$lex{Withdraw} - <b>$lastname</b>, $firstname</td></tr>\n};
	}


	# Add Transfer Record
	my $sth2 = $dbh->prepare("insert into transfer 
         ( studnum, date, type, description, exittype,  
          lastname, firstname, middlename, birthdate, provnum ) 
         values ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )");

	$sth2->execute( $rec{studnum}, $date, 'withdraw', $description, $exittype, 
		       $rec{lastname}, $rec{firstname}, $rec{initial}, 
		       $rec{birthdate}, $rec{provnum} );

	if ($DBI::errstr) { 
	    print qq{<tr><td><font color="red">$lex{Transfer} $lex{Error}};
	    print qq{ - $rec{lastname} $rec{firstname}: $DBI::errstr\n}; 
	}

    } # End of Student Withdrawal Loop

    print qq{</table>\n};

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

    exit;

}
