#!/usr/bin/perl

#use utf8;
use strict;
use CGI;

use Time::localtime;
use Opals::Context;
use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_preference
);


use Opals::Constant;

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        => 'txtbk/ajax/record/checkDuplicateBarcode.tmpl',
        reqPermission   => 'tb_record_edit',
    }
);

my $syspref = tmpl_preference($dbh);
my $tm = localtime;
my $dateToday = sprintf("%04d-%02d-%02d %02d:%02d:%02d", 
                $tm->year+1900, ($tm->mon)+1, $tm->mday, $tm->hour, $tm->min, $tm->sec);

if ($permission && $permission->{'tb_record_edit'}) {
    my $rid        = $input->{'rid'};
    my @barcodes   = ($cgi->param('bc'));
    my @duplicates;
    foreach my $bc (@barcodes){
        my $ret =  _tb_existBarcode($dbh,$bc,$rid);
        if ($ret && $ret != ''){
            push @duplicates, {barcode => $bc};
        }
    }
    $template->param (
        rid =>$rid,
        duplicate => scalar(@duplicates)>0?1:0,
        dupBCList => \@duplicates
    );
}
tmpl_write($dbh, $cgi, $cookie, $template);


#-------------------------------------------------------------------------------------------
sub _tb_existBarcode {

    my($dbh,$bc, $rid)=@_;
    my $sth = $dbh->prepare(<<_STH_);
select barcode from tb_items where barcode='$bc' && rid <> $rid
_STH_
    $sth->execute();
    my ($ret) = $sth->fetchrow_array;
    $sth->finish;
    if(!$ret){
        return '';
    }
    return $ret; 
}


