#!/usr/bin/perl

#use utf8;
use strict;
use CGI;
use Encode;
use PDF::API2;
use POSIX qw(
    ceil
    floor
);
use Time::localtime;


use Opals::Context;
use Opals::Constant;
use Opals::User qw(
    user_balance
    user_getInformation
    user_LoadCategory
);
use Opals::Circulation qw(
    circ_userListLoan
);
use Opals::Date qw(
    date_parse
    date_today
    date_text
    date_f005
);
use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_preference
);

my $rootDir = Opals::Context->config('rootDir');
my @allFontDirs = PDF::API2::addFontDirs "$rootDir/font/barcode/";
use constant    X_BOT_LEFT  =>  18;
use constant    Y_BOT_LEFT  =>  36;
use constant    X_TOP_RIGHT =>  594;
use constant    Y_TOP_RIGHT =>  756;

use constant    ROW_HEIGHT  =>  72;
use constant    COL_WIDTH  =>   198;
use constant    COL1_WIDTH  =>  184;
use constant    COL2_WIDTH  =>  198;
use constant    COL3_WIDTH  =>  193;
#use constant    SPC_WIDTH   =>  9;

my $dbh = Opals::Context->dbh();
END { $dbh->disconnect(); }

my $cgi = CGI->new;
my $input = $cgi->Vars();
my $pref = tmpl_preference($dbh);
my $libname=$pref->{'libname'};

my $mypdf = `/bin/mktemp`;

my $pdf  = PDF::API2->new(-file => $mypdf);
$pdf->mediabox(612,792);
my $normalFont = $pdf->corefont('Helvetica');  
my $barcodeFont = $pdf->ttfont('FREE3OF9.TTF');  
#my $barcodeFont = $pdf->ttfont('C39HDW2.TTF');  
#my $barcodeFont = $pdf->ttfont('C39HDW3.TTF');  
#my $barcodeFont = $pdf->ttfont('C39W2.TTF');  
#my $barcodeFont = $pdf->ttfont('C39W3.TTF');  


my ($permission, $cookie, $template) = tmpl_read(
        {
            dbh             => $dbh,
            cgi             => $cgi,
            tmplFile        => 'user/grpedit.tmpl',
            reqPermission   => 'user_edit',
        }
);
my $szOldWhere = MakeFilter(
    $input->{'oldfiltertype'},
    $input->{'oldfiltervalue'},
    $input->{'oldstatus'},
    $input->{'oldbrwrtype'}
);

my $startPos = int($input->{'startPos'});
if ($startPos > 0) {
    $startPos -= 1;
}
my @brwrtype = user_LoadCategory($dbh);
my %idxType;
foreach my $rec (@brwrtype) {
    $idxType{$rec->{'catid'}} = $rec->{'catname'};
}

if (!$input->{'uidlist'}) {
    GetAllBorrowers(
        $dbh, $input, $template, \%idxType, $szOldWhere,
        $input->{'oldordervalue'}
    );
}
else {
    GetListBorrowers(
        $dbh, $input, $template, \%idxType, $szOldWhere,
        $input->{'oldordervalue'}
    );
}

#================= OPEN PDF File ========================
open PDF, "<$mypdf";
print $cgi->header(
    -type           => 'application/pdf',
    -attachement    => 'OverdueNotice.pdf'
);
while (<PDF>) {
    print $_;
}
close PDF;


#----------------------------------------------------------------------------------------------------
sub printLabel {
    my ($input,$userData) = @_; 
    my $page;
    my $pIndex = 0;
    my ($x1, $y1) = (X_BOT_LEFT, Y_TOP_RIGHT - ROW_HEIGHT);
    my $fullname;
    my $homeroomGrade;
    #for(my $i=0; $i<scalar(@$userData); $i++){
    
    if ($startPos > 0) {
        $y1   = Y_TOP_RIGHT - ceil($startPos/3) * ROW_HEIGHT;
        $page = $pdf->page;
        $page = $pdf->openpage($pIndex++);
    }
    for (my $i = 0; $i < scalar(@{$userData}); $i++) {
        $fullname=''; $homeroomGrade='';

        foreach my $k (keys %{$userData->[$i]}) {
            $userData->[$i]->{$k} = decode('utf8', $userData->[$i]->{$k});
        }
        if (($i+$startPos) % 30 == 0) { 
            $pIndex++;
            $y1   = Y_TOP_RIGHT;
            $page = $pdf->page;
            $page = $pdf->openpage($pIndex);
        }

        if (($i+$startPos) % 3 == 0) {
            $x1  = X_BOT_LEFT;
            $y1 -= ROW_HEIGHT;
        }
        else{
            $x1 = X_BOT_LEFT + ($i+$startPos) % 3 * COL_WIDTH;
        }
        
        if($input->{'fNameStructure'}){
            if($input->{'fNameStructure'} != 1){
                #$fullname = $userData->[$i]->{'firstname'};
                if($input->{'fNameStructure'} == 3){
                    $fullname  = $userData->[$i]->{'lastname'} . ', ' . $userData->[$i]->{'firstname'};
                }
                elsif($input->{'fNameStructure'} == 4){
                    $fullname  = $userData->[$i]->{'lastname'} . ' ' .  $userData->[$i]->{'firstname'};
                }
                elsif($input->{'fNameStructure'} == 5){
                    $fullname  = $userData->[$i]->{'firstname'}. ' ' . $userData->[$i]->{'lastname'} ;
                }
            }
            elsif($input->{'fNameStructure'} == 2){
                $fullname = $userData->[$i]->{'lastname'};
            }
        }
                

        if($input->{'prtHomeroom'}){
            $homeroomGrade = 'HR:' .$userData->[$i]->{'homeroom'};
        }
        
        if($input->{'prtGrade'}){
            if($homeroomGrade ne ''){
                $homeroomGrade .= '    Grade:' . $userData->[$i]->{'grade'};
            }
            else{
                $homeroomGrade = $userData->[$i]->{'grade'};
            }
        }
                 
        writeLabel($page, $normalFont, 10,
                    $x1, $y1 + 3,
                    $fullname );

        writeLabel($page, $normalFont, 9,
                    $x1, $y1 -9,
                    $homeroomGrade);
       

        writeLabel($page, $barcodeFont, 26,
                    $x1, $y1 - 34,
                    '*' . $userData->[$i]->{'userbarcode'} . '*');
        writeLabel($page, $normalFont, 9,
                    $x1, $y1 - 46,
                    $userData->[$i]->{'userbarcode'});
    }

    $pdf->save;
    $pdf->end();
}
    
   
#----------------------------------------------------------------------------------------------------
sub writeLabel{
    my($page,$fnt,$fs,$x,$y,$text)=@_;
    my $txt = $page->text;
    $txt->textstart;
    $txt->font($fnt, $fs);
    $txt->translate($x +COL_WIDTH/2 - 9,$y+ROW_HEIGHT-20);
    $txt->text_center($text);
    $txt->textend;
}

#-------------------------------------------------------
sub GetAllBorrowers
{
    my ($dbh, $input, $template, $brwrtype, $szWhere, $szOrder) = @_;
    
    # Get the users in the current filter
    my $sql = "select * from opl_user "; 
    $sql .= $szWhere;
    if ( $szOrder )
    { $sql .= " order by " . $szOrder; }
    else
    { $sql .= " order by lastname"; }
 
    my $query = $dbh->prepare($sql);
    $query->execute();

    my @BrwrList = ();

    while ( my $rec = $query->fetchrow_hashref )
    {
        push @BrwrList, $rec;
    }
    $query->finish;
    printLabel($input,\@BrwrList);

}

#-------------------------------------------------------
sub GetListBorrowers
{
    my ($dbh, $input, $template, $brwrtype, $szWhere, $szOrder) = @_;
    # Get the users in the current filter
    my $sql = "select * from opl_user "; 
    $szWhere="";
    $sql .= $szWhere;
    if ( $szWhere )
        { $sql .= " && uid=?"; }
    else
        { $sql .= " where uid=? "; }
    my $query = $dbh->prepare($sql);
    
    my @BrwrList = ();
    foreach my $uid (split /,/, $input->{'uidlist'})
    {
        $query->execute($uid);
        my $rec = $query->fetchrow_hashref;
        $query->finish;
        push @BrwrList, $rec;
    }
    printLabel($input,\@BrwrList);

}

#----------------------------------------------------------
sub MakeFilter
{
    my ($filtertype, $filtervalue, $status, $brwrtype) = @_;
    my $szWhere = '';
    my $condStr="";
    my $tmpCondStr="";
    if ( $filtervalue ne '' )
    {
        my $szCond = $filtervalue;
        $szCond =~ s/^\s+//;
        $szCond =~ s/\s+$//;
        $szCond =~ s/'/\\'/g;
        if ( $filtertype eq 'name' ){ 
            $szCond =~ s/ +/ /g;
            $szCond =~ s/,/ /g; 
            my @data = split(' ', $szCond);
            $condStr = "  (";
            foreach my $i (@data) {
                if($i =~ m/\w+/g){
                    $condStr  .= " ( lastname like '$i%' or lastname like '% $i%' or 
                                      firstname like '$i%' or firstname like '% $i%'
                                    )  and";                  
                }
             }
            $condStr =~ s/ and$/)/;
            #$condStr = " (firstname like '$szCond%' || lastname like '$szCond%')"; 
        }
        elsif ( $filtertype eq 'city' ) { $condStr= " city like '$szCond%'"; }
        elsif ( $filtertype eq 'zippostal' ) { $condStr = "zip = '$szCond'"; }
        elsif ( $filtertype eq 'phone' ) { $condStr = " phone = '$szCond'"; }
        elsif ( $filtertype eq 'grade' ) { $condStr = " grade = '$szCond'"; }
        elsif ( $filtertype eq 'teacher' ) { $condStr = " teacher like '$szCond%'"; }
        elsif ( $filtertype eq 'homeroom' ) { $condStr = " homeroom = '$szCond'"; }
        elsif ( $filtertype eq 'buildingcode' ) { $condStr = " buildingcode = '$szCond'"; }
        elsif ( $filtertype eq 'yeargraduation' ) { $condStr = " yeargraduation = $szCond"; }
    }
  # User type
    $brwrtype =~ s/^ +//g;
    $brwrtype =~ s/ +$//g;
    $brwrtype =~ s/^,+//g;
    $brwrtype =~ s/,+$//g;
    my @u_type = split(/,/, $brwrtype);
    
    foreach my $val (@u_type){
        $val =~ s/ +//g;
        if($val ne ''){
            $tmpCondStr .=' || categorycode=' . $val;
        }
    }
    $tmpCondStr =~ s/^ +//g;
    $tmpCondStr =~ s/^\|\| //g;
    if($tmpCondStr ne ''){
        if($condStr ne ''){
            $condStr .= " && (" . $tmpCondStr .")" ;
        }
        else{
            $condStr = " ($tmpCondStr )" ;

        }
    }

    $tmpCondStr="";
  # User status
    $status =~ s/,+$//g;
    my @u_status = split(/,/, $status); 
    
    foreach my $val (@u_status){
       if ( $val eq "active" ){
           $tmpCondStr .=' || status=' . USER_ACTIVE;
       }
        elsif ( $val eq "block" ){
            $tmpCondStr .=' || status=' . USER_BLOCK;
        }
        elsif ( $val eq "inactive" ){
            $tmpCondStr .=' || status=' . USER_INACTIVE;
        }
    }
    $tmpCondStr =~ s/^ +//g;
    $tmpCondStr =~ s/^\|\| //g;
    if($tmpCondStr ne ''){
        if($condStr ne ''){
            $condStr .= " && (" . $tmpCondStr .")";
        }
        else{
            $condStr =  $tmpCondStr ;

        }
    }
    
      if($condStr ne ''){
        return " where $condStr";
    }
    return "";
}



#----------------------------------------------------------
sub MakeFilter_bk
{
    my ($filtertype, $filtervalue, $status, $brwrtype) = @_;
    my $szWhere = '';
    my $condStr="";
    my $tmpCondStr="";
    if ( $filtervalue ne '')
    {
        my $szCond = $filtervalue;
        $szCond =~ s/^\s+//;
        $szCond =~ s/\s+$//;
        if ( $filtertype eq 'name' ) 
            { $condStr = " (firstname like '$szCond%' || lastname like '$szCond%')"; }
        elsif ( $filtertype eq 'city' ) { $condStr= " city like '$szCond%'"; }
        elsif ( $filtertype eq 'zippostal' ) { $condStr = "zip = '$szCond'"; }
        elsif ( $filtertype eq 'phone' ) { $condStr = " phone = '$szCond'"; }
        elsif ( $filtertype eq 'grade' ) { $condStr = " grade = '$szCond'"; }
        elsif ( $filtertype eq 'teacher' ) { $condStr = " teacher like '$szCond%'"; }
        elsif ( $filtertype eq 'homeroom' ) { $condStr = " homeroom = '$szCond'"; }
        elsif ( $filtertype eq 'buildingcode' ) { $condStr = " buildingcode = '$szCond'"; }
        elsif ( $filtertype eq 'gradeyear' ) { $condStr = " yeargraduation = $szCond"; }
    }

    # User status 
    $status =~ s/,$//g;
    my @u_status = split(/,/, $status); 
    
    foreach my $val (@u_status){
       if ( $val eq "active" ){
           $tmpCondStr .=' || status=' . USER_ACTIVE;
       }
        elsif ( $val eq "block" ){
            $tmpCondStr .=' || status=' . USER_BLOCK;
        }
        elsif ( $val eq "inactive" ){
            $tmpCondStr .=' || status=' . USER_INACTIVE;
        }
    }
    $tmpCondStr =~ s/^ +//g;
    $tmpCondStr =~ s/^\|\| //g;
    if($tmpCondStr ne ''){
        if($condStr ne ''){
            $condStr .= " && (" . $tmpCondStr .")";
        }
        else{
            $condStr =  $tmpCondStr ;

        }
    }
    
    $tmpCondStr="";
    # User type
    $brwrtype =~ s/^ +//g;
    $brwrtype =~ s/ +$//g;
    $brwrtype =~ s/^,+//g;
    $brwrtype =~ s/,+$//g;
    my @u_type = split(/,/, $brwrtype);
    
    foreach my $val (@u_type){
        if($val ne ''){
            $tmpCondStr .=' || categorycode=' . $val;
        }
    }
    $tmpCondStr =~ s/^ +//g;
    $tmpCondStr =~ s/^\|\| //g;
    if($tmpCondStr ne ''){
        if($condStr ne ''){
            $condStr .= " && (" . $tmpCondStr .")" ;
        }
        else{
            $condStr =  $tmpCondStr ;

        }
    }
    if($condStr ne ''){
        return " where $condStr";
    }
    return "";
}
#-------------------------------------------------------
sub GetStatus
{
    my ($rec, $brwrtype) = @_;
    
    $rec->{'catname'} = $brwrtype->{$rec->{'categorycode'}};
    $rec->{'statusname'} = 'inactive' if ( $rec->{'status'} == USER_INACTIVE);
    $rec->{'statusname'} = 'active' if ( $rec->{'status'} == USER_ACTIVE);
    $rec->{'statusname'} = 'block' if ( $rec->{'status'} == USER_BLOCK);

    $rec->{'block'} = 1 if ( $rec->{'status'} == USER_BLOCK );

    #--- Get overdue/loans info
    my $loanList = circ_userListLoan($dbh, $rec->{'uid'});
    my $odCount = 0;
    foreach my $loan (@$loanList) 
    {
        if ( $loan->{'overdue'} ) { $odCount++; }
    }
    $rec->{'odloans'} = scalar(@$loanList) . "/" . $odCount;
    return $rec;
}
