#!/usr/bin/perl

use strict;
use CGI;

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

);

use Opals::Equipment qw(

    eq_defRecord_getList
    eq_defRecord_getLists
    eq_defItem_getList
    eq_defItem_getLists
    
    eq_record_findByRId
    eq_item_findByRId
    srch_equipment
    srch_eq_record_byRIdList
    
);

use Opals::Eq_Circulation qw(
    
    circ_infoRecord
    circ_getItemStatus
);

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

my $cgi = CGI->new;
my $input = $cgi->Vars();
my $sessionID = $cgi->cookie('globalSessionID');

my ($permission, $cookieList, $template) = tmpl_read(
    {
        dbh             => $dbh,
        cgi             => $cgi,
        tmplFile        => 'eqmnt/report/searchWtBc_prt.tmpl',
    }
);

my $kw          = $input->{'kw'};
my $field       = $input->{'field'};
my $sField      = $input->{'sField'};
my $sortAttr    = $input->{'sortAttr'};
my $sortOrder = $input->{'sortOrder'};
   ($sortOrder && $sortOrder >=1) || ($sortOrder = 1);

if ($sField && $sField ne ""){
    $field = $sField;
}
my $resultOrder = $sortOrder;
my $prtType = $input->{'prtType'};
my $prtFields = $input->{'prtFields'};

my $defRecList      =  eq_defRecord_getList($dbh);
my $defItemList      = eq_defItem_getList($dbh);

my $defRecLists     =   eq_defRecord_getLists($dbh);
my $defItemLists    =   eq_defItem_getLists($dbh);

my ($type, $sF, $reqF) = split(/:/, $field);
my $prtOpt = $input->{'prtOpt'};
foreach my $defRec(@$defRecList){
    $defRec->{'sortField'} = 0;
    if ($defRec->{'id'} == $sortAttr){
        $defRec->{'sortField'} = 1;
    }
}

my ($resultSize, $recordList) = (0,[]);

$template->param(
    sKw     =>  $kw,
    sField  =>  $field,
    sfIndex =>  ($input->{'sfIndex'})?$input->{'sfIndex'}:0 ,
);

writeSortParam2Tmpl();

my ($resultSize, $recordList) = getResultList($dbh,$prtOpt,$field,$kw,$sortOrder,$sortAttr, $prtFields);

$recordList  = addHoldingInfo($dbh, $recordList,$prtFields ) ;
my $result  = ($resultSize > 0)? 1:0;
if ($prtType && $prtType eq 'csv'){
    saveResult2CSV($recordList,$defRecList,$defItemList,$prtFields);
}
else {
    $template->param(
        defRecList      =>  $defRecList, 
        defItemList     =>  $defItemList,   
        defRecLists     =>  $defRecLists,
        defItemLists    =>  $defItemLists,
        recordList      =>  $recordList, 
        result          =>  $result,
        resultSize      =>  $resultSize,
        printAllFields     =>  ($prtFields eq "all")? 1 : 0,
        searchType      =>  "searchWtBc",
        prtReportHeader =>  1,
    );

    if ($permission && $permission->{'equipment_mngt'}) {
        $template->param(    eqmntMgmt      => 1);
    }
}
tmpl_write($dbh, $cgi, $cookieList, $template);

sub getResultList {

    my ($dbh,$prtOpt,$field,$kw,$sortOrder,$sortAttr, $prtFields) = @_;
    my ($sql,$resultSize, $recordList) = ("",0,[]);
    my @ridList = ();
    my $ridStr = "";
    if ($prtOpt eq 'all'){
        ($resultSize, $recordList) = srch_equipment($dbh, $field, $kw,0,100000 ,$sortOrder, $sortAttr);
    }
    else{
        $sql = " select rid from opl_sessionVar s where s.var='eqBC' && s.ssid = '$sessionID' order by sOrder";
        my $sth = $dbh->prepare($sql);
        $sth->execute();

        while ( my $rid = $sth->fetchrow_array){
            push @ridList, $rid;
            $ridStr .= $rid . ",";
        }
        chop $ridStr;
        ($resultSize, $recordList) = srch_eq_record_byRIdList($dbh, $field, $kw,0,100000 ,$sortOrder, $sortAttr, $ridStr);
        $recordList =  addHoldingInfo($dbh, $recordList, $prtFields) ;
        $resultSize = scalar(@$recordList);
    }
    return ($resultSize, $recordList);
}

sub saveResult2CSV {
    my ($recordList,$defRecList,$defItemList, $prtFields) = @_;
    print "Content-Type:application/x-download\n";
    print "Content-Disposition:attachment;filename=equipmentList.csv\n\n";  
    
    my $header = "\"" . "Name " . "\",";
    foreach my $rd (@$defRecList){
        if ($prtFields eq "all") {
                $header .= " \"$rd->{'name'}\"," ;
        }
        else {
            if ($rd->{'display'}){
                $header .= " \"$rd->{'name'}\"," ;
            }
        }
    }
    $header .= "\"" ." Barcode " . "\",";
    foreach my $id(@$defItemList){
        if ($prtFields eq "all") {
            $header .= " \"$id->{'name'}\"," ;
        }
        else{
             if ($id->{'display'}){
                $header .= " \"$id->{'name'}\"," ;
            }
        }
    }
    $header .= "\"Status\"";
    print "$header \n";
    my $strR = "";
    my $str = "";
    foreach my $r (@$recordList){
        $strR = $r->{'rname'} ."," ;
        foreach my $rf (@{$r->{'fields'}}){
            if ($prtFields eq "all") {
                $strR .= "\"".$rf->{'fval'} ."\",";
            }
            else {
                if ($rf->{'display'}){
                    $strR .= "\"".$rf->{'fval'} ."\",";
                }
            }
        }
        foreach my $if(@{$r->{'items'}}){
            $str = $if->{'barcode'} . ",";
            foreach my $sf(@{$if->{'sfields'}}) {
                if ($sf->{'val'} && $sf->{'val'} ne "") {
                    $str .= "\"" . $sf->{'val'} . "\",";
                }
                else {
                    $str .= ",";
                }
             }
            $str .= $if->{'status'} , "\n";
            print $strR . $str . "\n";
        }
    }
    exit;
}

sub writeSortParam2Tmpl{
    
    $template->param(
        sortOrder       => $sortOrder,
        sortAttr        => $sortAttr,
        sortRName       => ($sortAttr ne "" && $sortAttr < 0)? 1:0,
        sortOrderReverse    => ($sortOrder && $sortOrder == 1)  ? 2 : 1,
        sortDown        => ($sortOrder && $sortOrder == 1)  ? 0 : 1,
        sortField       =>  $sortAttr ,
    );
}

sub  addHoldingInfo{
    
    my ($dbh, $recordList , $prtFields) = @_;
    my $rCount = 0;

    my $sth_items = $dbh->prepare(<<_SQL_);
select * from eq_items where rid = ? && barcode not regexp '^\_\_\_'
_SQL_

   foreach my $rec (@$recordList){
        my @itemList = ();   
        $sth_items->execute($rec->{'rid'});
        if ($rec->{'iCount'} > 0){
            while (my $item = $sth_items->fetchrow_hashref){
                my $itemCircStatus =  circ_getItemStatus($dbh,{barcode=>$item->{'barcode'}});
                my ($itemStatus,$colorStyle,$fontStyle)  =  getStyleByStatus($itemCircStatus->{'status'});
                $item->{'status'} = $itemStatus; 
                $item->{'colorStyle'} = $colorStyle;
                $item->{'fontStyle'} = $fontStyle;
                my @sfields = getItemSubFieldInfo($dbh, $rec->{'rid'},$item->{'iid'}, $prtFields);
                $item->{'sfields'} = \@sfields;
                push @itemList, $item;
            }
        }
        else{
            my @sfields = getItemSubFieldInfo($dbh, $rec->{'rid'},0, $prtFields);
            my $item  = {
               barcode => "",
               sfields => \@sfields,
            };
            push @itemList,$item;
        }
        $rec->{'items'} = \@itemList;
        $rec->{'iCount'} = scalar(@itemList);
    }
    $sth_items->finish;
    return $recordList;
}

sub getStyleByStatus {
     
    my ($statusCode) = @_;
    my ($itemStatus,$colorStyle,$fontStyle) = ('available','green','normal');

    if($statusCode == 2){
        ($itemStatus,$colorStyle,$fontStyle) = ('reserved','brown','bold');
    }
    elsif($statusCode == 3){
        ($itemStatus,$colorStyle,$fontStyle) = ('on loan','brown','bold');
    }
    elsif($statusCode == 4){
        ($itemStatus,$colorStyle,$fontStyle) = ('overdue','brown','bold');
    }
    elsif($statusCode == 5){
        ($itemStatus,$colorStyle,$fontStyle) = ('on hold','brown','bold');
    }
    elsif($statusCode == 7){
        ($itemStatus,$colorStyle,$fontStyle) = ('lost','brown','bold');
    }
    elsif($statusCode == 8){
        ($itemStatus,$colorStyle,$fontStyle) = ('damage','brown','bold');
    }
    elsif($statusCode == 10){
        ($itemStatus,$colorStyle,$fontStyle) = ('restricted','brown','bold');
    }
    elsif($statusCode == 11){
        ($itemStatus,$colorStyle,$fontStyle) = ('missing','brown','bold');
    }
   
   return ($itemStatus,$colorStyle,$fontStyle) ;
}

sub getItemSubFieldInfo {

    my ($dbh,$rid,$iid, $prtFields) = @_;
    my $query = "select f.sfValue as val from eq_def d 
               left outer join eq_itemFields f on d.id = f.sfId
               && f.rid = ? && f.iid = ? 
               where d.defType = 'item' ";
    if ($prtFields ne "all"){
        $query .= " && d.display = 1 " ;
    }
       $query .=  "order by d.fOrder" ;
    my $sth = $dbh->prepare($query);
    $sth->execute($rid,$iid);
    my @retVal = ();
    while ( my $sf = $sth->fetchrow_hashref()){
        push @retVal, {
            val   => $sf->{'val'} ,
        };
    }
    $sth->finish;
    return @retVal;
}
