#!/usr/bin/perl

#use utf8;
use strict;
use CGI;

use Opals::Context;

use Opals::Template qw(
    tmpl_read
    tmpl_write
);

use Opals::Equipment qw(
 
    eq_record_findByRId

);

use Opals::Eq_Circulation qw(
    
    circ_infoRecord
);

use Opals::Constant;

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

    my $rid = $input->{'rid'};
    my $recInfo =  eq_record_findByRId($dbh, {recordId=>$rid});
    my $rname = $recInfo->[0]->{'rname'};

    my ($bcList,$bcCount) = GetRecordCircDetail($dbh,$rid);
    $template->param (
        rid         => $rid,
        rname       => $rname,
        rInfo       => $recInfo,
        bcList      => $bcList,
        bcCount     => $bcCount
    );

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


sub GetRecordCircDetail {
    
    my ($dbh,$rid) = @_;
    my $sql = <<_STH_;
select r.rname,
        i.barcode,i.copyNo,
        l.uid,l.dateLoan,l.dateReturn,
        u.firstname,u.lastname, u.userbarcode 
from    eq_records r inner join eq_items i using(rid) 
        inner join eq_loan l on i.barcode = l.barcode 
        left outer join opl_user u on u.uid=l.uid 
        where i.rid= $rid
        order by i.barcode

_STH_
    my @itemList=();

    my $sth = $dbh->prepare($sql);
    $sth->execute();
    while (my $i = $sth->fetchrow_hashref) {
        push @itemList, $i;
    }
    $sth->finish;
    return (\@itemList,scalar(@itemList));

}
