#!/usr/bin/perl

use strict;
use CGI;

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

use Opals::Equipment qw(

    eq_defItem_getLists
    eq_defItem_getList
    eq_defRecord_getList
    
    eq_record_add

    eq_record_findByRId
    eq_record_addUpdate
    eq_record_update_rname
   
    eq_item_add
 
    eq_item_findByRId
    eq_item_addUpdateBarCodeItemType
    eq_item_addUpdate

    eq_item_delete
    eq_item_deleteSubFields
    eq_item_deleteBarcode
    eq_isBarcodeExist
    eq_itemType_getList

    eq_record_idGen

);

use Opals::Eq_Circulation qw(

    circ_getLoanListByRid

);

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        => 'eqmnt/ajax/save.tmpl',
        reqPermission   => 'eq_record_edit',
    }
);

my $rid     = $input->{'rid'};
my $op      = $input->{'op'};

my ($rFieldList,$iFieldList);
my $iDefList = eq_defItem_getList($dbh);
my $rDefList = eq_defRecord_getList($dbh);

if ($permission && $permission->{'eq_record_edit'} ) {

        #record-field values inputs
        my @fId         = ($cgi->param('fId')) ;
        my @fData       = ($cgi->param('fData')) ;
        my $rname       = $input->{'rname'};
        my @cats        = ($cgi->param('cat'));
        my $cat         = join(',',@cats);
        my $container   = $input->{'container'} || 0;   

        #item-field values inputs
        my @bc          = ($cgi->param('barcode')) ;
        my @copyNo      = ($cgi->param('copyNo')) ;
        my @itemType    = ($cgi->param('itemType')) ;
        my $subfieldData;
        my $n =0;

        foreach my $sf (@$iDefList){
            my $subfield = "sfData_" . $sf->{'id'};
            my @tmpArr =($cgi->param($subfield));
            $subfieldData->{$sf->{'id'}} = \@tmpArr;
        }
        my @iid         = ($cgi->param('iid')) ;
        my @delItem     = ($cgi->param('delItem'));
        my @deleted     = ($cgi->param('delete'));
        my @eqItemList;
        my $n = scalar(@bc);
        for (my $i=0;$i<$n;$i++){
            my $item;
            $item->{'deleted'}  = $deleted[$i];
            $item->{'new'}      = ($iid[$i] == 0)? "1":"0";
            $item->{'barcode'}  = $bc[$i];
            $item->{'typeId'}   = $itemType[$i];
            $item->{'iid'}      = $iid[$i];
            $item->{'copyNo'}   = $copyNo[$i];
            my @sfs =();
            foreach my $fname (keys %$subfieldData){
                $item->{$fname}=$subfieldData->{$fname}->[$i];
            }
            push @eqItemList,$item;
        }
        my $i = 0;


        my $i = 0;
        if (!$rid){
            $rid = eq_record_idGen($dbh);
            my $params = {rid=>$rid, fValue=>$rname,category=>$cat,container=>$container,reqField=>1};
            eq_record_add($dbh, $params );
            foreach my $id (@fId){
                my $params = {rid=>$rid, fId=>$id, fValue=>$fData[$i]};
                eq_record_add($dbh, $params);
                $i++;
            }
            my ($i, $iid) =(0, 0 );
            foreach my $item(@eqItemList){
                $iid++;
                my $params =  { 
                    rid     =>$rid,
                    iid     =>$item->{'iid'},
                    barcode =>$item->{'barcode'},
                    typeId  =>$item->{'typeId'}, 
                    copyNo  =>$item->{'copyNo'},
                    reqField=>1
                };
                eq_item_add($dbh,$params);
                foreach my $fn(sort keys %$item){
                    my $params = {iid=>$iid, rid=>$rid, sfId=>$fn,sfValue=>$item->{$fn}};
                    if ($fn && $fn =~ /^\d+?$/ ){
                        eq_item_add($dbh,$params);
                    }
                }
                $i++;
            }
        }
        elsif ($rid && $rid > 0 ) {
            
#Record Info       
            my $rname   =  $input->{'rname'};
            if ($rname && $rname ne ""){
                 eq_record_update_rname($dbh,$rid,$rname,$cat,$container);
            }
            foreach my $id (@fId){
                my $params = {rid=>$rid, fId=>$id, fValue=>$fData[$i]};
                eq_record_addUpdate($dbh, $params);
                $i++;
            }
#Holding Info            
            #my @iid         = ($cgi->param('iid')) ;
            #my @delItem     = ($cgi->param('delItem'));
            #my @deleted     = ($cgi->param('delete'));
=item
            my @eqItemList;
            my $n = scalar(@iid);
            for (my $i=0; $i < $n; $i++ ){
                my $item;
                $item->{'deleted'}  = $deleted[$i];
                $item->{'new'} = ($iid[$i] == 0)? "1":"0";
                $item->{'barcode'}  = $bc[$i];
                $item->{'typeId'}   = $itemType[$i];
                $item->{'iid'}      = $iid[$i];
                $item->{'copyNo'}   = $copyNo[$i];
                my @sfs =();
                foreach my $fname (keys %$subfieldData){
                    $item->{$fname}=$subfieldData->{$fname}->[$i];
                }
                push @eqItemList,$item;
            }
=cut
            foreach my $item (@eqItemList){
                my $params =  { rid=>$rid,
                                iid=>$item->{'iid'},
                                barcode=>$item->{'barcode'},
                                typeId=>$item->{'typeId'}, 
                                copyNo=>$item->{'copyNo'}
                };
                if ($item->{'deleted'} eq '1'){
                    eq_item_deleteBarcode($dbh,$params);
                }
                else{
                    eq_item_addUpdateBarCodeItemType($dbh, $params);
                    foreach my $fn(keys %$item){
                        if ($fn && $fn =~ /^\d+?$/ ){
                        #if ( $fn != 'iid') {
                            my $params = {iid=>$item->{'iid'}, rid=>$rid, sfId=>$fn,sfValue=>$item->{$fn}};
                            eq_item_addUpdate($dbh,$params);
                        }
                    }
                }
            }
        }
    my $itemList = eq_item_findByRId($dbh, $rid);
    my $max_iid=0;
    my $iCount = 0;
    
    my $onLoanList =  circ_getLoanListByRid($dbh,$rid);
    foreach my $i(@$itemList){
        $iCount++;
        $i->{'onLoan'} = "";
        $max_iid=$i->{'iid'} if($i->{'iid'}>$max_iid);
        foreach my $ol (@$onLoanList){
            if ($ol->{'barcode'} eq $i->{'barcode'}){
                $i->{'onLoan'} = 'onLoan';
            }
        }
    }
    foreach my $f (@$rDefList){
        push @$rFieldList , {
           fId      => $f->{'id'},
           fVal     => "",
           fName    => $f->{'name'},
           fDisplay => $f->{'display'},
           fType    => $f->{'fieldType'},
        }
    }
    foreach my $f(@$iDefList){
        push @$iFieldList, {
             sfId       => ($f->{'sfId'})? $f->{sfId}:$f->{'id'},
             sfVal      => "",
             sfName     => $f->{'name'},
             sfReqD     => $f->{'reqD'},
             sfDisplay  => $f->{'display'},
             url_link   => ($f->{'fieldType'} eq '2')?1:0,
             sfType     => $f->{'fieldType'},
             dateType   => ($f->{'dataType'} eq "Date")?"1":"0",
             selectType => ($f->{'dataType'} eq "Select")?"1":"0",
             numberList => ($f->{'dataType'} eq "NumberList")?"1":"0",
        }
    }
    my @sorted = sort { $a->{'iid'} cmp $b->{'iid'} || $a->{'copyNo'} cmp $b->{'copyNo'}} @$itemList;
    $template->param(
        rid             => $rid,
        itemList        => $itemList,
   );
}
    
tmpl_write($dbh, $cgi, $cookieList, $template);


