#!/usr/bin/perl

#use utf8;
use strict;
use CGI;

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

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

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

my $cgi      = CGI->new;
my $input = $cgi->Vars();



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


my ($permission, $cookie, $template) = tmpl_read(
    {
        dbh             => $dbh,
        cgi             => $cgi,
        tmplFile        => 'ajax/marc21/getHoldingStatus.tmpl',
        reqPermission   => 'marc_edit',
    }
);

#my $bcList=[{bc=>"bc1",onloan=>1},{bc=>"bc2",onloan=>0}];    
my $bcList=getBcStatus($dbh,$rid);    


$template->param(bcList=>$bcList);
tmpl_write($dbh, $cgi, $cookie, $template);

sub getBcStatus{
    my($dbh,$rid)=@_;
    my $ret=[];
    my $sth=$dbh->prepare("select i.barcode,i.available,l.idloan from opl_item i left outer join opl_loan l using(barcode) 
                               where l.dateReturn is null && i.barcode not regexp '\_\_\_' && i.rid=?");
    my $sth_d=$dbh->prepare("select status from opl_itemstatus where barcode=? order by id desc limit 1");
    $sth->execute($rid);
    while(my ($bc,$avail,$idloan)=$sth->fetchrow_array){
        my $item={bc=>$bc,onloan=>$idloan, missing=>!$avail};
        $sth_d->execute($bc);
        if(my ($s) =$sth_d->fetchrow_array){
            $item->{"damaged"}=1 if($s==2);
        }
        push @$ret,$item;
    }
   
    return $ret;
}

#------------------------------------------------------------------------------


