#! /usr/bin/perl
#  Copyright 2001-2009 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',
	   'Unassign Locker' => 'Unassign Locker',
	   'Fees' => 'Fees',
	   'Checked' => 'Checked',
	   'Unassign' => 'Unassign',
	   'Unassigned' => 'Unassigned',
	   'Locks' => 'Locks',
	   'Lockers' => 'Lockers',
	   'Delete' => 'Delete',
	   'Student' => 'Student',
	   'Name' => 'Name',
           'Lockers' => 'Lockers',
           'Name' => 'Name',
	   'Homeroom' => 'Homeroom',
	   'Grade' => 'Grade',
	   'Error' => 'Error',
	   'Continue' => 'Continue',
	   'Blank=All' => 'Blank=All',
	   'Select by' => 'Select by',
	   'Separate with Spaces' => 'Separate with Spaces',
	   'Blank=All' => 'Blank=All',
	   'Location' => 'Location',
	   'Sort by' => 'Sort by',
	   'Locker' => 'Locker',
	   'Lock' => 'Lock',
	   'No Record(s) Found' => 'No Record(s) Found',
	   'Partner' => 'Partner',
	   'No Lock' => 'No Lock',
	   'Hover=View' => 'Hover=View',

	    );

my $self = 'lockerunassg.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";
}

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


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

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

# Get current dir so know what CSS to display;
my $runmode = 'main';
if (getcwd() =~ /tcgi/){ # we are in tcgi
    $css = $tchcss;
    $homepage = $tchpage;
    $runmode = 'teacher';
}

print "$doctype\n<html><head><title>". $lex{'Unassign Locker'}. "</title>
<link rel=\"stylesheet\" href=\"$css\" type=\"text/css\">
$chartype\n</head><body>\n";

print "[ <a href=\"$homepage\">". $lex{Main}. "</a> ";
if ( $runmode eq 'main' ) { print " <a href=\"$feespage\">". $lex{Fees}. "</a> "; }
print "]\n";

print "<center><h1>". $lex{'Unassign Locker'}. "</h1></center>\n";


if ( not $arr{page} ) {
    showStartPage();
} elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    selectRecords();
} elsif ( $arr{page} == 2 ) {
    delete $arr{page};
    deleteRecords();
}


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

    # Find all the grades
    my @grades = ();
    my $sth = $dbh->prepare("select distinct grade from student");
    $sth->execute;
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
    while ( my $grade = $sth->fetchrow ) {
	push @grades, $grade;
    }
    my $gradestring;
    foreach my $grade ( sort { $a <=> $b} @grades ) {
	$gradestring .= $grade. q{ };
    }

    # Find all the homerooms
    my @homerooms = ();
    $sth = $dbh->prepare("select distinct homeroom from student");
    $sth->execute;
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
    while ( my $homeroom = $sth->fetchrow ) {
	push @homerooms, $homeroom;
    }
    my $hrstring;
    foreach my $hr ( sort { $a <=> $b} @homerooms ) {
	$hrstring .= $hr. q{ };
    }

    # Find all the locker locations
    my $locationstring;
    $sth = $dbh->prepare("select distinct location from lok_locker order by location");
    $sth->execute;
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
    while ( my $loc = $sth->fetchrow ) {
	$locationstring .= $loc. q{ / };
    }


    # Main Form
    print "<center><form action=\"$self\" method=\"post\">\n";
    print "<input type=\"hidden\" name=\"page\" value=\"1\">\n";
    print "<table cellspacing=\"0\" cellpadding=\"4\" border=\"0\">\n";


    # Select by
    print "<tr><td align=\"right\"><b>". $lex{'Select by'}. "</b></td>\n<td align=\"left\">";
    print "<select name=\"group\">\n";
    print "<option title=\"$gradestring\">". $lex{Grade}. "</option>\n";
    print "<option title=\"$hrstring\">". $lex{Homeroom}. "</option>\n";
    print "<option title=\"$locationstring\">". $lex{Location}. "</option>\n";
    print "</select> ". $lex{'Hover=View'}. "<br>\n";
    print "<input type=\"input\" name=\"groupid\" size=\"12\">\n";
    print $lex{'Separate with Spaces'}. q{, }. $lex{'Blank=All'}. "</td></tr>\n";

    # ~~ Sort Example    foreach my $grade ( sort { $a <=> $b} @grades ) {

    # Sort by
    print "<tr><td align=\"right\"><b>". $lex{'Sort by'}. "</b></td>\n<td align=\"left\">";
    print "<select name=\"sort\" ><option>". $lex{Name}. "</option>\n";
    print "<option title=\"$gradestring\">". $lex{Grade}. "</option>\n";
    print "<option title=\"$hrstring\">". $lex{Homeroom}. "</option>\n";
    print "<option title=\"$locationstring\">". $lex{Location}. "</option>\n";
    print "<option>". $lex{Locker}. "</option><option>\n";
    print $lex{Lock}. "</option></select></td></tr>\n";

    # Delete Student Assignment
    print "<tr><td align=\"right\"><b>". $lex{Checked}. "</b></td><td>";
    print "<input type=\"checkbox\" name=\"checked\" value=\"CHECKED\">\n";
    print "</td></tr>\n";

    # End of Form / Submit
    print "<tr><td align=\"center\" colspan=\"2\">";
    print "<input type=\"submit\" value=\"". $lex{Continue}. "\"></td></tr>\n";
    print "</table></form>\n\n";


    print "</center></body></html>\n";

    exit;
}



#----------------
sub selectRecords {
#----------------

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

    if ( $arr{group} eq $lex{Grade} or $arr{group} eq $lex{Homeroom} ) {

	if ( $arr{group} eq $lex{Grade} ) { 
	    $group = 'grade'; 
	} else {
	    $group = 'homeroom';
	}

	# Do the selects first; first find students from grouping
	my @groups = split /\s/, $arr{groupid};

	if ( not @groups ) { # select all students 
	    my $sth = $dbh->prepare("select lastname, firstname, studnum, $group from student
              order by lastname, firstname");
	    $sth->execute;
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	    while ( my ( $lastname, $firstname, $studnum, $grp ) = $sth->fetchrow ) {
		push @students, $studnum;
		$students{$studnum} = "$lastname, $firstname ($grp)";
	    }

	} else { # we have groups of students

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

	    foreach my $grp ( @groups ) {
		$sth->execute( $grp );
		if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
		while ( my ( $lastname, $firstname, $studnum, $grp ) = $sth->fetchrow ) {
		    push @students, $studnum;
		    $students{$studnum} = "$lastname, $firstname ($grp)";
		}
	    } # done loop through @groups
	}
	# We now have student @students and %students, now get their lockers.

	# Find the student's lockers (may be more than 1 student per locker)
	$sth = $dbh->prepare("select locker_num from lok_rlink where studnum = ?");
	foreach my $studnum ( @students ) {
	    $sth->execute( $studnum );
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	    $locker_num = $sth->fetchrow;
	    if ( $locker_num ) {
		push @lockers, $locker_num;
	    }
	}

    } else { # find lockers by location.

	my @locations = split /\s/, $arr{groupid};
	if ( not @locations ) { # select all lockers 
	    my $sth = $dbh->prepare("select locker_num from lok_rlink order by locker_num");
	    $sth->execute;
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    while ( my $locker_num = $sth->fetchrow ) {
		push @lockers, $locker_num;
	    }

	} else { # we have groups of lockers by location
	    my $sth = $dbh->prepare("select link.locker_num from lok_rlink as link, 
              lok_locker as l
              where link.locker_num = l.locker_num and l.location = ?");

	    foreach my $location ( @locations ) {
		$sth->execute( $location );
		if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
		while ( my $locker_num = $sth->fetchrow ) {
		    push @lockers, $locker_num;
		}
	    } # done loop through @locations
	} # done location 

    } # we now have locker_num in @lockers

    if ( not @lockers ) { # no lockers found
	print "<h1>". $lex{'No Record(s) Found'}. "</h1>\n";
	print "</body></html>\n";
	exit;
    }

#     print "Lockers", @lockers, "<br>\n";



    my $grouping; # whether to do a grouping process; separate tables.
    my $sth;

    if ( $arr{sort} eq $lex{Name} ) {

	$grouping = 0;
	$sth = $dbh->prepare("select s.lastname, s.firstname, s.studnum from 
          student as s, lok_rlink as l 
          where s.studnum = l.studnum and l.locker_num = ?");
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	foreach my $locker_num ( @lockers ) {
	    $sth->execute( $locker_num );
	    while ( my ( $lastname, $firstname, $studnum ) = $sth->fetchrow ) {
		if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
		$lockers{"$lastname$firstname:$studnum"} = $locker_num;
	    }
	}

    } elsif ( $arr{sort} eq $lex{Grade} ) {

	$grouping = $lex{Grade};
	$sth = $dbh->prepare("select s.lastname, s.firstname, s.grade, s.studnum 
          from student as s, lok_rlink as l 
          where s.studnum = l.studnum and l.locker_num = ?");
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	foreach my $locker_num ( @lockers ) {
	    $sth->execute( $locker_num );
	    while ( my ( $lastname, $firstname, $grade, $studnum ) = $sth->fetchrow ) {
		if ( length( $grade ) == 1 ){ $grade = '0'. $grade; }
		if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
		$lockers{"$grade$lastname$firstname:$studnum"} = $locker_num;
	    }
	}

    } elsif ( $arr{sort} eq $lex{Homeroom} ) {
	$grouping = $lex{Homeroom};
	$sth = $dbh->prepare("select s.lastname, s.firstname, s.homeroom, s.studnum
          from student as s, lok_rlink as l 
          where s.studnum = l.studnum and l.locker_num = ?");
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	foreach my $locker_num ( @lockers ) {
	    $sth->execute( $locker_num );
	    while ( my ( $lastname, $firstname, $homeroom, $studnum ) = $sth->fetchrow ) {
		if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
		$lockers{"$homeroom$lastname$firstname:$studnum"} = $locker_num;
	    }
	}

    } elsif ( $arr{sort} eq $lex{Location} ) {
	$grouping = $lex{Location};

	$sth = $dbh->prepare("select s.lastname, s.firstname, s.studnum
          from student as s, lok_rlink as l 
          where s.studnum = l.studnum and l.locker_num = ?");

	my $sth1 = $dbh->prepare("select location from lok_locker where locker_num = ?");
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }

	foreach my $locker_num ( @lockers ) {
	    # Get Location
	    $sth1->execute( $locker_num );
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	    my $location = $sth1->fetchrow;

	    $sth->execute( $locker_num );
	    while ( my ( $lastname, $firstname, $studnum ) = $sth->fetchrow ) {
		if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
		$lockers{"$location$lastname$firstname:$studnum"} = $locker_num;
	    }
	}


    } elsif ( $arr{sort} eq $lex{Lock} ) {

	$grouping = 0; # just as a reminder.

	$sth = $dbh->prepare("select s.lastname, s.firstname, s.studnum
          from student as s, lok_rlink as l 
          where s.studnum = l.studnum and l.locker_num = ?");

	my $sth1 = $dbh->prepare("select lock_num from lok_link where locker_num = ?");
	
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }

	foreach my $locker_num ( @lockers ) {

	    # Get Lock Number
	    $sth1->execute( $locker_num );
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	    my $lock_num = $sth1->fetchrow;
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }

	    $sth->execute( $locker_num );
	    my ( $lastname, $firstname, $studnum ) = $sth->fetchrow; # ignore others
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	    $lockers{"$lock_num:$studnum"} = $locker_num;

	}


    } elsif ( $arr{sort} eq $lex{Locker} ) {

	$grouping = 0; # just as a reminder.

	$sth = $dbh->prepare("select s.lastname, s.firstname, s.studnum
          from student as s, lok_rlink as l 
          where s.studnum = l.studnum and l.locker_num = ?");
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }

	foreach my $locker_num ( @lockers ) {
	    $sth->execute( $locker_num );
	    my ( $lastname, $firstname, $studnum ) = $sth->fetchrow; # ignore others
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	    $lockers{"$locker_num:$studnum"} = $locker_num;
	}


    }

    # we should now have a %lockers hash with correct sorting value and locker numbers
    # print "Locker:", %lockers, "<br>\n";

    # get locker info and print it...
    my $sth1 = $dbh->prepare("select cleaned, location, comment from lok_locker 
      where locker_num = ?");
    my $sth2 = $dbh->prepare("select lock_num from lok_link where locker_num = ?");
    my $sth3 = $dbh->prepare("select combination, pool, comment from lok_lock 
      where lock_num = ?");
    my $sth4 = $dbh->prepare("select studnum from lok_rlink where locker_num = ?");
    my $sth5 = $dbh->prepare("select lastname, firstname, grade, homeroom from studentall
      where studnum = ?");
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }

    print "<center><form action=\"$self\" method=\"post\">\n";
    print "<input type=\"hidden\" name=\"page\" value=\"2\">\n";
    print "<input type=\"submit\" value=\"". $lex{Unassign}. "\"><br>\n";

    print q{ }. $lex{Unassign}. q{ }. $lex{Locker}. q{=}. $lex{Unassign}. q{ }. $lex{Lock};

    print "<table cellspacing=\"0\" cellpadding=\"3\" border=\"1\">\n";
    print "<tr><th>". $lex{Locker}. "</th><th>". $lex{Student}. "</th><th>";
    print $lex{Lock}. "</th><th>". $lex{Partner}. "</th></tr>\n";

    
    my $currgroup = -1;
    my $oldgroup;

    foreach my $key ( sort keys %lockers ) {

	my $locker_num = $lockers{$key};

	# Get Locker Info.
	$sth1->execute( $locker_num );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	my ( $cleaned, $location, $comment ) = $sth1->fetchrow;

	# Get Lock Info
	my $lockinfo;
	$sth2->execute( $locker_num );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	my $lock_num = $sth2->fetchrow;

	if ( $lock_num ) {
	    $sth3->execute( $lock_num );
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	    my ( $combination, $pool, $comment ) = $sth3->fetchrow;
	    $lockinfo = "$lock_num ($combination)";
	} else {
	    $lockinfo = $lex{'No Lock'};
	}

	# Get Student Info
	my ( $dud, $mainstudnum ) = split /:/, $key;

	$sth4->execute( $locker_num );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	
	my %students = ();
	my ( $curr_lastname, $curr_firstname, $curr_grade ); # current main info for locker 
	while ( my $studnum = $sth4->fetchrow ) {

	    $sth5->execute( $studnum );
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	    my ( $lastname, $firstname, $grade, $homeroom ) = $sth5->fetchrow;

	    if ( $studnum == $mainstudnum ) {
		$curr_lastname = $lastname;
		$curr_firstname = $firstname;
		$curr_grade = $grade;
		$curr_homeroom = $homeroom;
	    } else {
		$students{$studnum} = "$lastname, $firstname ($grade)";
	    }
	
	} # end of student loop

	$prevgroup = $currgroup;
	if ( $grouping eq $lex{Grade} ) {
	    $currgroup = $curr_grade;
	} elsif ( $grouping eq $lex{Homeroom} ) {
	    $currgroup = $curr_homeroom;
	} elsif ( $grouping  eq $lex{Location} ) {
	    $currgroup = $location;
	}

	if ( $currgroup ne $prevgroup ) {

	    print "<tr><td colspan=\"4\" style=\"font-size:150%;text-align:center;\">";
	    print "$grouping $currgroup</td></tr>\n";

	}


	print "<tr><td><input type=\"checkbox\" name=\"$locker_num\" ";
	print "value=\"R\" $arr{checked}> $locker_num</td>\n";
	print "<td><b>$curr_lastname</b>, $curr_firstname ($curr_grade)</td>\n<td>";
	if ( $lock_num ) {
	    print "<input type=\"checkbox\" name=\"$lock_num\" value=\"L\">\n";
	}
	print " $lockinfo</td>\n<td>";
	foreach my $studnum ( keys %students ) {
	    print "$students{$studnum} $studnum<br>";
	}
	print "</td></tr>\n";

    } # end of locker loop.

    print "</table>";
    print "<input type=\"submit\" value=\"". $lex{Unassign}. "\">\n";

    print "</form></center>\n";
    print "</body></html>\n";

    exit;

} # end of selectRecords



#-----------------
sub deleteRecords {
#-----------------

    # delete Selected Locks / Lockers
    #foreach my $key ( sort keys %arr ) { print "K:$key V:$arr{$key}<br>\n"; }
    

    my $sth = $dbh->prepare("delete from lok_rlink where locker_num = ?");
    my $sth1 = $dbh->prepare("delete from lok_link where lock_num = ?");
    my $sth2 = $dbh->prepare("delete from lok_link where locker_num = ?");

    my $sth3 = $dbh->prepare("select locker_num from lok_link where lock_num = ?");

    print "<center><table cellspacing=\"0\" cellpadding=\"3\" border=\"1\">\n";
    print "<tr><th>". $lex{Unassigned}. q{ }. $lex{Lockers}. q{ / }. $lex{Locks};
    print "</th></tr>\n";

    foreach my $key ( sort keys %arr ) { 
	print "<tr><td>";
	if ( $arr{$key} eq 'R' ) {
	    my $locker_num = $key;
	    print $lex{Delete}. q{ }. $lex{Locker}. " $locker_num<br>\n";
	    $sth->execute( $locker_num );
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }

	    print $lex{Delete}. q{ }. $lex{Lock}. q{ - }. $lex{Locker}. " $locker_num<br>\n";
	    $sth2->execute( $locker_num );
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }

	} elsif ( $arr{$key} eq 'L' ) {
	    my $lock_num = $key;

	    # Get the locker number
	    $sth3->execute( $lock_num );
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	    my $locker_num = $sth3->fetchrow;

	    print $lex{Delete}. q{ }. $lex{Lock}. " $lock_num - ". $lex{Locker};
	    print " $locker_num\n";
	    $sth1->execute( $lock_num );
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	}

	print "</td></tr>\n";
    }

    print "</table>\n";
    print "</body></html>\n";

    exit;

}
