#!/usr/bin/perl

use strict;
use CGI;

use Opals::Context;
use Opals::Template qw(
    tmpl_read
    tmpl_write
);

use Time::localtime;
use Opals::Search qw(
 
    srch_F852Default_marc21

);


use Opals::Tb_Record qw(
    
    tb_defRecordIndex_getList

    tb_barcode_getMaxValue
    tb_createNextBiggerBc

    tb_record_idGen
    tb_record_add
    tb_itemType_getList

    tb_item_add

    tb_barcode_getList
    tb_isBarcodeExist
    tb_barcode_getMaxDup

);

my $dbh = Opals::Context->dbh();
END { $dbh->disconnect(); }
my $cgi = CGI->new;
my $input = $cgi->Vars();
my ($permission, $cookieList, $template) = tmpl_read(
    {
        dbh             => $dbh,
        cgi             => $cgi,
        tmplFile        => '/txtbk/record/add.tmpl',
        reqPermission   => 'tb_record_edit',
    }
);

my $defRecordIndexList  = tb_defRecordIndex_getList($dbh, 1);
my $tbItemTypeList    = tb_itemType_getList($dbh);


my $test =  srch_F852Default_marc21($dbh,);

my @bCode       = ($cgi->param('bcode'));
my @itType      = ($cgi->param('ittype'));
my @lCode       = ($cgi->param('lcode'));
my @price       = ($cgi->param('price'));
my @classNo     = ($cgi->param('classno'));
my @acqDate     = ($cgi->param('acquisitiondate'));
my @distributor = ($cgi->param('distributor'));
my @PONo        = ($cgi->param('pono'));
my @regionCode  = ($cgi->param('rgncode'));
my @districtCode    = ($cgi->param('dstcode'));
my @buildingCode    = ($cgi->param('bldcode'));
my @importDate  = ($cgi->param('impdate'));
my @budgetCategory    = ($cgi->param('budgetCategory'));
my @vendorCatalogNo   = ($cgi->param('vendorCatalogNo'));
my @delItem         = ($cgi->param('delItem'));

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);

my $save = $input->{'save'};
if ($save eq 'save'){
    my $saveDone = 1;
    my $rid = tb_record_idGen($dbh);
    my $title = $input->{'245_a'};
    my $retRecAdd = tb_record_add($dbh, $rid, '005', $dateToday);
    foreach my $def (@$defRecordIndexList){
        my $fId     = $def->{'fieldId'} . '_' . $def->{'subfield'};
        my $fVal = "";
        if ($def->{'repeatable'}){
            my @fVal = ($cgi->param($fId));
            my $n = scalar (@fVal);
            foreach my $f(@fVal){
                $retRecAdd = tb_record_add($dbh, $rid, $fId, $f);
                if ($retRecAdd < 1 || $saveDone < 1){ $saveDone = 0;}
            }
        }
        elsif($def->{'checkbox'} ){
             $fVal    = $input->{$fId};
             if ($fVal){
                $fVal    = $input->{$fId . '_v'};
                $retRecAdd = tb_record_add($dbh, $rid, $fId, $fVal);
             }
        }
        elsif($fId eq '900_a'){
            my @fVal = ($cgi->param($fId));
            my $val = join(', ',@fVal);
            $retRecAdd = tb_record_add($dbh, $rid, $fId, $val);
        }
        else {
            $fVal    = $input->{$fId};
            my $retRecAdd = tb_record_add($dbh, $rid, $fId, $fVal);
            if ($retRecAdd < 1 || $saveDone < 1)
                { $saveDone = 0;}
        }
    }
    for my $i (0 .. $#bCode){
        if ($delItem[$i] eq "1") {
            next;
        }
        if (tb_isBarcodeExist($dbh, $bCode[$i])){
            my $maxDupBarcode = tb_barcode_getMaxDup($dbh, $bCode[$i]);
            $bCode[$i] = $maxDupBarcode;
            }
        my $params = {
            rid         => $rid,
            barcode     => $bCode[$i],
            typeId      => $itType[$i],
            lCode       => $lCode[$i],
            price       => $price[$i],
            classno     => $classNo[$i],
            acqDate     => $acqDate[$i],
            PONo        => $PONo[$i],
            distributor => $distributor[$i],
            regionCode  => $regionCode[$i],
            districtCode=> $districtCode[$i],
            buildingCode=> $buildingCode[$i],
            importDate  => $importDate[$i],
            budgetCategory=> $budgetCategory[$i],
            vendorCatalogNo=>$vendorCatalogNo[$i]
        };
        my $retItemAdd = tb_item_add($dbh, $params);
        if ($retItemAdd < 1 || $saveDone < 1){ $saveDone = 0;}
    }
    $template->param(
        recordSaved     => 1,
        saveDone        => $saveDone,
        title           => $title,
    );
}

#get default system-library codes
my $default852 = srch_F852Default_marc21($dbh);
my $sCode =  $default852->subfield('a');
my $lCode =  $default852->subfield('b');

$template->param(
    sCode   => $sCode,
    lCode   => $lCode,
);

#my $bcList = tb_barcode_getList($dbh);
#my $maxBarcode = 

my $maxBarcode  = tb_barcode_getMaxValue($dbh);
my $nextMaxBarcode =  tb_createNextBiggerBc($dbh,$maxBarcode);


foreach my $d (@$defRecordIndexList){
    foreach my $k (keys %$d){
        if ($k eq "fId" && $d->{$k} eq "900_a" ){
            $d->{'gradeLevel'} = 1;
        }
    }
}

$template->param(
    defRecordIndexList  => $defRecordIndexList,
    tbItemTypeList      => $tbItemTypeList, 
#   barcodeList         => $bcList,
    todayDateTime       => $dateToday,
    maxBarcode          => $maxBarcode,
    nextBiggerMaxBc     => $nextMaxBarcode,
);

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