#!/usr/bin/perl
#  Copyright 2001-2022 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 = ('View' => 'View',
	   'Staff' => 'Staff',
	   'Absences' => 'Absences',
	   'Main' => 'Main',
	   'Eoy' => 'Eoy',
	   'No Records Found' => 'No Records Found',
	   'Error' => 'Error',
	   'Edit' => 'Edit',
	   'Delete' => 'Delete',
	   'Records' => 'Records',
	   'Category' => 'Category',
	   'Hours' => 'Hours',
	   'Month' => 'Month',
	   
	   );


use DBI;
use CGI;
use CGI::Session;
use Cwd;

my $self = 'rptStaffPaySummary.pl';


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

# Set Date
my @tim = localtime(time);
my $cyear = @tim[5] + 1900;
my $cmonth = @tim[4] + 1;
my $cday = @tim[3];
my $currdate = "$cyear-$cmonth-$cday";
my $curryrmo = "$cyear-$cmonth";
my $currfdate = $s_month[$cmonth]. "$cday, $cyear";

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


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



# load staffpay vars: @pay_LeaveAreas
my $sth = $dbh->prepare("select id, datavalue from conf_system where sectionname = 'staffpay'");
$sth->execute;
if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
while (	my ($id, $datavalue) = $sth->fetchrow ) {
    eval $datavalue;
    if ( $@ ) {
	print "$lex{Error}: $@<br>\n";
	die "$lex{Error}: $@\n";
    }
}



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

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

print qq{<form action="$self" method="post" style="display:inline;">\n};
print qq{<input type="submit" value="Show Calculations">\n};
print qq{<select name="showcalc"><option value=""></option>\n};
print qq{<option value="all">All</option>\n};
print qq{<option value="neg">Negative Balance</option>};
print qq{</select></form>\n};

print qq{<h1>$title  <span style="font-size:70%;">$currfdate</span></h1>\n};

=head  # USEFUL!
my $sth = $dbh->prepare("show columns from staff_absent");
$sth->execute;
if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
while (my @cols = $sth->fetchrow ) {
    if ( $cols[0] eq 'id' or $cols[0] eq 'comment' ) { next; }
    push @fields, $cols[0];
}
=cut


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

#} elsif ( $arr{page} == 1 ) {
#    delete $arr{page};
    showReport();
#}
    
#if ( getcwd() =~ /tcgi/ ){ # we are in tcgi



#-------------
sub showReport {  # do all months for all staff
#-------------

    # foreach my $key (sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }
    
    
    # Start Form
    print qq{<form action="$self" method="post">\n};
    
    # Load all staff members
    my (@userids,%names);
    my $sth = $dbh->prepare("select distinct l.userid, s.lastname,s.firstname 
        from staff_leave l, staff s
        where l.userid = s.userid order by s.lastname, s.firstname");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    while ( my ($userid, $lastname, $firstname) = $sth->fetchrow ) {
	push @userids, $userid;
	$names{$userid} = qq{<b>$lastname</b>, $firstname};
    }

    # Configured Leave Values
    my $sth1 = $dbh->prepare("select category, hours from staff_leave where userid = ?");
    # Used Leaves
    my $sth2 = $dbh->prepare("select sum(hours) from staff_payjrl 
			     where userid = ? and category = ?");

    my $sth3 = $dbh->prepare("select * from staff_payjrl 
			     where userid = ? and category = 'other'");

    
    my $first = 1;
    my $count = 1;
    foreach my $userid ( @userids ) {

	if ( $first ) { # start table header.
	    print qq{<table border="1" cellpadding="3" cellspacing="0">\n};
	    print qq{<tr><th>Staff Name</th>\n};
	    foreach my $category ( @pay_LeaveAreas ) {
		print qq{<th>$category</th>};
	    }
	    print qq{<th>Earned</th><th title="Leave without Pay">LWOP</th>};
	    print qq{<th>Other</th></tr>\n};
	    $first = 0;
	}

	# Name
	if ( $count % 2 == 0 ) {
	    print qq{<tr>};
	} else {
	    print qq{<tr style="background-color:#DDD;">};
	}
	print qq{<td>$names{$userid}</td>};

	
	# Load starting hours for this staff member.
	$sth1->execute( $userid );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my %leavehours;
	while ( my ($category, $hours) = $sth1->fetchrow ) {
	    $leavehours{$category} = $hours;
	}

	foreach my $category ( @pay_LeaveAreas ) { # typically 4 categories predefined.
	
	    $sth2->execute( $userid, $category );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    my $sum = $sth2->fetchrow;
	    my $balance = $leavehours{$category} - $sum;
	    if ( $balance < 0 and $arr{showcalc} ) { # any value of showcalc works (neg/all)
		print qq{<td class="cn">$balance<br><span style="color:red;font-size:80%;">};
		print qq{$leavehours{$category} - $sum</span></td>};
	    } elsif ( $arr{showcalc} eq 'all' ) {
		print qq{<td class="cn"><b>$balance</b><br>};
		print qq{$leavehours{$category} - $sum</td>};
	    } else { # no calcs
		print qq{<td class="cn">$balance</td>};
	    }
	}

	
	# Now do earned / used;
	$sth2->execute( $userid, 'earned' );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my $earned = $sth2->fetchrow;

	$sth2->execute( $userid, 'used' );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my $used = $sth2->fetchrow;
	my $balance = $earned - $used;

	if ( $arr{showcalc} eq 'all' ) {
	    print qq{<td class="cn"><b>$balance</b><br>};
	    print qq{$earned - $used</td>};
	} else { # no calcs
	    print qq{<td class="cn">$balance</td>\n};
	}

	# Now do without pay
	$sth2->execute( $userid, 'wopay' );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my $wopaysum = $sth2->fetchrow;
	print qq{<td class="cn">$wopaysum</td>};

	# Other Category - load entire record
	$sth3->execute( $userid );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my ($ocount, $otext);
	while ( my $ref = $sth3->fetchrow_hashref ) {
	    my %r = %$ref;
	    $ocount++;
	    $otext = $otext. qq{$r{comment}\n};
	}
	if ( $ocount ) {
	    print qq{<td title="$otext">$ocount View</td>};
	} else {
	    print qq{<td></td>};
	}
	
	print qq{</tr>\n};

	$count++;

    } # next userid;

    
    if ( $first ) {
	print qq{<p>$lex{'No Records Found'}</p>\n};
	print qq{</body></html>\n};
	exit;
    } else {
	print qq{</table>\n};
    }

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

    exit;
    
} # end of showReport


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


    print qq{<form action="$self" method="post" style="margin-bottom:1.5em;">\n};
    print qq{<input type="hidden" name="checked" value="1">\n};
    print qq{<input type="submit" value="Check All Staff"></form>\n};


    my $checked;
    if ( $arr{checked} ) {
	$checked = qq{Checked="Checked"};
	delete $arr{checked};
    }

    
    # Setup Year-Months.
    my @months;
    my %months;

    my $sth = $dbh->prepare("select distinct year(date), month(date) from staff_payjrl 
      where date is not NULL and date != '0000-00-00' order by year(date), month(date) ");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    while ( my ($yr,$mo) = $sth->fetchrow ) {
#	print qq{Y:$yr M:$mo<br>\n};
	my $yrmo = "$yr-$mo";
	push @months, $yrmo;
	$months{$yrmo} = "$s_month[$mo]-$yr";
    }
    # rptmonth4 has a starting year / 10 month setup.

    
    # Load starting hours for this staff member.
    my $sth = $dbh->prepare("select distinct l.userid, s.lastname,s.firstname 
        from staff_leave l, staff s
        where l.userid = s.userid order by s.lastname, s.firstname");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

    # Start Form
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<div><input type="submit" value="View Hours"> \n};
    print qq{ Blank Month = All Months</div>\n};
    
    my $first = 1;
    while ( my ($userid, $lastname, $firstname) = $sth->fetchrow ) {

	if ( $first ) {
	    print qq{<table border="1" cellpadding="3" cellspacing="0" };
	    print qq{style="float:left;margin:0.5em;">\n};
	    print qq{<tr><th>$lex{Staff}</th></tr>\n};
	    $first = 0;
	}

	print qq{<tr><td><input type="checkbox" name="$userid" value="1" $checked>};
	print qq{<b>$lastname</b>, $firstname ($userid)</td></tr>\n};

    }

    print qq{</table>\n};

    # Get Month    
    print qq{<table cellpadding="3" border="1" cellspacing="0" };
    print qq{style="float:left;margin:0.5em;">\n};
    print qq{<tr><th>$lex{Month}</th></tr>\n};
#    print qq{<tr><td class="la"><select name="month"><option></option>\n}; 

    foreach my $mo ( @months ) {
	print qq{<tr><td><input type="radio" name="month" value="$mo">$months{$mo}</td></tr>\n};
    }
    print qq{</table>\n};

    print qq{<br clear="left">\n};
    print qq{<div><input type="submit" value="View Hours"></div>\n};
    
    print qq{</form>\n};

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

}
       


    
