#!/usr/bin/perl

#use utf8;
use strict;
use CGI;

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



use Time::localtime;


use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_preference
);
use Opals::Locale qw(
    loc_getMsgFile
    loc_write
);

use Opals::Tb_Record qw(

    tb_item_findByBarcode
);

my @fields=qw(
    loan
    inlibrary
    reserve
    renewal
    return
);



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

my $pref = tmpl_preference($dbh);

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

my $incExcOpt = $input->{'incExcOpt'};
if(!$incExcOpt || $incExcOpt ne 'inclusion'){
    $incExcOpt='exclusion';
}
#$incExcOpt = "exclusion" if ( !$incExcOpt );
my ($permission, $cookie, $template) = tmpl_read(
        {
            dbh             => $dbh,
            cgi             => $cgi,
            tmplFile        => '/txtbk/report/dailyCircStats.tmpl',
            reqPermission   => 'tb_report',
        }
);

my $date   = $input->{'date'}; 
my $type   = $input->{'type'};
my $sortField=$input->{'sortField'}||"callNumber";

my $msgMap =loc_getMsgFile('report/reports.msg',{loanListHeaderTxt      =>{date=>$date},
                                                 returnListHeaderTxt    =>{date=>$date},
                                                 renewalListHeaderTxt   =>{date=>$date},
                                                 reserveListHeaderTxt   =>{date=>$date},
                                                 inlibraryUsedListHeaderTxt=>{date=>$date},
                                                 ebReadListHeaderTxt    =>{date=>$date},
                                                 ebPreviewListHeaderTxt =>{date=>$date}
                                                 });
loc_write($template,$msgMap);
my $sortFieldfMap={
    "barcode"   =>"i.barcode, callNumber, author,titleSort",
    "callNumber"=>"callNumber, author,titleSort",
    "title"     =>"titleSort,callNumber, author",
    "author"    =>"author,callNumber, titleSort",
    "pubName"   =>"pubName, callNumber, author,titleSort",
    "pubPlace"  =>"pubPlace, callNumber, author,titleSort",
    "pubDate"   =>"pubDateSort, callNumber, author,titleSort"
};
my $headerMap={
    "loan"      =>"loanListHeaderTxt",
    "return"    =>"returnListHeaderTxt",
    "renewal"   =>"renewalListHeaderTxt",
    "reserve"   =>"reserveListHeaderTxt",
    "inLib"     =>"inlibraryUsedListHeaderTxt",
    "ebRead"    =>"ebReadListHeaderTxt",
    "ebPreview" =>"ebPreviewListHeaderTxt"
};

if($date){
    my $circStatsTbl =[];
      #$circStatsTbl =$fnMap->{$type}($dbh,$date,$incExcOpt);
      my $allCircStatsTbl = [] ;
      my $pageTitle ;
   
      if (defined $type && $type =~ m/all/){
          $allCircStatsTbl = getStats_allTypes($dbh,$date,$sortField,$incExcOpt);
          $pageTitle = "List of transactions on " . $date;
      }
      else{
         $circStatsTbl =getStats($dbh,$date,$type,$sortField,$incExcOpt);
         $pageTitle =$msgMap->{$headerMap->{$type}};

      }
      $template->param(
                date             =>  $date,
                pageTitle        =>  $pageTitle || "List of " . ucfirst($type) . " on " . $date,
                circStatsTbl     =>  $circStatsTbl,
                allCircStatsTbl  =>  $allCircStatsTbl,
                allTypes         => ($type =~ m/all/)? 1 : 0
        );
}
tmpl_write($dbh, $cgi, $cookie, $template);

#########################################################################################
sub getStats{
    my($dbh,$date,$type,$sortField,$incExcOpt)=@_;
    $date=~ s/ \d\d:\d\d:\d\d$//g; 
    my $df="$date 00:00:00";
    my $dt="$date 23:59:59";
    my $ret=[];
  
    my $query ="";
    my @fields=qw(barcode  title author pubName pubPlace pubDate);
    if($type eq 'reserve'){
         $query ="select barcode from tb_reserve r inner join tb_items i using(rid)  
                where r.dateReserve  between ? and ?";
    }
    else{
        $query ="select barcode from tb_loan ";
        if($type eq 'loan'){
            $query .=" where dateLoan  between ? and ?";
        }
        if($type eq 'return'){
              $query .=" where dateReturn  between ? and ?";
        }
        if($type eq 'renewal'){
              $query .=" where dateRenewal  between ? and ?";
        }
    }
    my $sth=$dbh->prepare($query);
    $sth->execute($df,$dt)   ;
    while( my $loan=$sth->fetchrow_hashref){
        my $itemInfo = tb_item_findByBarcode($dbh,$loan->{'barcode'});
        $itemInfo->{'barcode'} = $loan->{'barcode'};
        push @$ret,$itemInfo;
    }
    $sth->finish;
    return $ret;
}

sub getStats_allTypes {

    my($dbh,$date,$sortField,$incExcOpt)=@_;

    my $types = ["loan","renewal","return"];
    my $circTbl = {};
    my @list = ();
    foreach my $type(@$types){
       my $ret = getStats($dbh,$date,$type,$sortField,$incExcOpt);
       if ($ret && scalar (@$ret > 0)) {
           
         $circTbl->{$type} =  $ret;
         push @list, {
            type  => ucfirst($type),
            list  => $ret
         }
       }
    }
    return \@list;
}

__END_OF_FILE:

