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

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

    my $recInfo = getRecordCircDetail($dbh,$rid,$dateFrom,$dateTo);
    
    
    
    $template->param (
        from          => substr($dateFrom,0,10),
        to            => substr($dateTo,0,10),
        rid         => $rid,
        rname       => $recInfo->{'rname'},
        model       => $recInfo->{'model'},
        bcList      => $recInfo->{'bcList'},
        bcCount     => scalar(@{$recInfo->{'bcList'}}),
        bcInSelCount=> $recInfo->{'bcInSelCount'},

    );

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

sub getRecordCircDetail {

    my ($dbh, $rid, $datFrom,$dateTo) = @_;
    my $sql = <<_STH_;
select l.dateLoan, l.dateReturn, u.firstname, u.lastname, u.userbarcode,
        i.rid, i.barcode, r.rname as rname, rf.fValue as model
from    eq_loan l inner join eq_items i using(barcode) inner join eq_records r using(rid)
left outer join opl_user u using(uid)
left outer join ( eq_def d inner join eq_recordFields rf on d.id = rf.fId && d.name regexp 'model\$' ) on rf.rid = i.rid
where i.rid = $rid
_STH_
    
    my $sth = $dbh->prepare($sql);
    $sth->execute();
    my @bcList = ();
    my $inSel = 0;
    my ($rname, $model) = ("","");
    my $bcInSelCount = 0;
    while ( my $r = $sth->fetchrow_hashref) {
        $inSel = 0;
        my $rec;
        $rec->{'rid'} = $r->{'rid'};
        if ($rname eq "") {
            $rname = $r->{'rname'} ;
        };
        if ($model eq "") {
            $model = $r->{'model'} ;
        };
        $rec->{'barcode'} = $r->{'barcode'};
        if($r->{'dateLoan'} ge $dateFrom && $r->{'dateLoan'} le $dateTo){
            $inSel=1;
            $bcInSelCount++;
        }
        $rec->{'inSel'} = $inSel;
        $rec->{'dateLoan'}     = $r->{'dateLoan'};
        $rec->{'dateReturn'}   = $r->{'dateReturn'};
        $rec->{'firstname'}    = $r->{'firstname'};
        $rec->{'lastname'}     = $r->{'lastname'};
        $rec->{'userbarcode'}  = $r->{'userbarcode'};
        push @bcList, $rec;
    }
    my $recCircInfo = {
        rname => $rname,
        model => $model,
        bcList => \@bcList,
        bcInSelCount=> $bcInSelCount
    };
    return $recCircInfo;
}


