#!/usr/bin/perl

use strict;
use CGI;
use JSON;

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

use Opals::Eq_Search qw(
    eq_srch_getFieldList
);
use Opals::Eq_Circulation qw(
    circ_infoRecord
    eq_circ_getItemStatus
);

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/report/equipmentList.tmpl',
    }
);

my $defRecList = [];
my $defItemList = []; 
my $fieldList     = eq_srch_getFieldList();
my $totalEquipment = getTotalNumberOfEquipment();

#Remove Equipment & barcode from the list
foreach my $f(@$fieldList){
  if ($f->{'defType'} eq 'record' && ($f->{'id'} ne 'name' && $f->{'id'} ne 'eq_name' )){
    push @$defRecList,$f;
  }
  elsif ($f->{'defType'} eq 'item' && ($f->{'id'} ne 'barcode' && $f->{'id'} ne 'eq_barcode' )){
    push @$defItemList,$f;
  }
  else{}
}

$template->param (
    srchFieldList => to_json($fieldList,{pretty=>1}),
    defList       => to_json({record=>$defRecList,item=>$defItemList},pretty=>1),
    totalEquipment=> $totalEquipment
);

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

1;

sub getTotalNumberOfEquipment {
  my $sql= "select count(*) from eq_items i inner join eq_records r using(rid) where i.deleted='0' && r.deleted='0'";
  my $ret = $dbh->selectrow_array($sql);
  return $ret || 1;
}
