#!/usr/bin/perl

#use utf8;
use strict;
use CGI;

use Opals::Context;use POSIX qw(
    floor
);

use Time::localtime;
use Opals::Constant;

use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_preference
);
use Opals::User qw(
    user_list
    user_getInformationById
    user_balance
);
use Opals::Circulation qw(
    circ_getItemInfo
    circ_getRecID
);
use Opals::Date qw(
    date_parse
    date_today
    date_text
    date_validateWorkday
    date_deltaWorkDay
    date_addDeltaWorkday
);
use Opals::Locale qw(
    loc_getMsgFile
    loc_write
);


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

my $cgi = CGI->new;
my $input = $cgi->Vars();
my ($permission, $cookie, $template) = tmpl_read(
        {
            dbh             => $dbh,
            cgi             => $cgi,
            tmplFile        => 'report/printLabelsByRange.tmpl',
            reqPermission   => 'report',
        }
);
my $syspref = tmpl_preference($dbh);
my @cookieList = ($cookie);

my $tm = localtime;
my $todayStr = sprintf("%04d-%02d-%02d", $tm->year+1900, ($tm->mon)+1, $tm->mday);
  

if ($permission && $permission->{'report'}) {
        my $bigBc = getBiggestBcFromDB($dbh);
        my $nextBc= createNextBiggestBc($dbh,$bigBc);
          
           $template->param(
             nextBc =>$nextBc,
         ); 
   }

#Tue, Jan 12, 2010 @ 10:31:41 EST
my $msgValMap ={};
my $msgMap            =loc_getMsgFile('report/reports.msg',$msgValMap);
loc_write($template,$msgMap);

tmpl_write($dbh, $cgi, \@cookieList, $template);


################################################################################

sub getBiggestBcFromDB{
    my ($dbh) = @_;
    
#    my $sql = <<_STH_;
#select  max(barcode) as max
#from    opl_item  
#where barcode not regexp '^\_\_\_|^tmp_'
#_STH_
    my $sql = <<_STH_;
select   max(cast(barcode as UNSIGNED)) as max
from    opl_item  
where barcode not regexp '^\_\_\_|^tmp|temp'
_STH_
    
    my $sth = $dbh->prepare($sql);
    $sth->execute();
    while (my $rec = $sth->fetchrow_hashref) {
        return $rec->{'max'}
    }
    
    return ;
}
################################################################################

sub createNextBiggestBc{
     my ($dbh,$bc) = @_;
     my $prefix = "";
     my $bigBc = $bc;
        $bigBc =~ m/(^.*[\D]|^)([\d]+)$/;
        $prefix= $1;           
        
     my $tmp = $2;

     if($tmp=~ m/(^0+)(\d+)/){
        $tmp = $2;
        $prefix .=$1;
     }
     $bc = $prefix . ($tmp +1);

     return $bc;
}

################################################################################








