#!/usr/bin/perl

use strict;
use CGI;

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

use Opals::Constant;

use Opals::Date qw(
    date_time_text
);

use Opals::Equipment qw(

    eq_item_findByBarcode

);

use Opals::Eq_Circulation qw(
    
    circ_getItemStatus
    circ_updateItemStatus

);

use Opals::Eq_BarcodeMgmt qw(
    eq_bcm_validateBc

);

use JSON;

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

my $MAX_brwrList = 100;
my $syspref     = tmpl_preference($dbh);
my $validateBc  = $syspref->{'validateBarcode'};
my $barcodeType = $syspref->{'barcodeType'};
my $patronItemPrivacy=$syspref->{'patronItemPrivacy'};

my $cgi = CGI->new;
my $input = $cgi->Vars();
my ($permission, $cookieList, $template) = tmpl_read(
    {
        dbh             => $dbh,
        cgi             => $cgi,
        tmplFile        => '/eqmnt/circ_itemCircStatus.tmpl',
    }
);

my $barcode = $input->{'bc'};
$barcode =~  s/^\s+|\s+$//g;
$barcode = eq_bcm_validateBc($dbh,$barcode,$barcodeType) if($validateBc eq '1');

open debug, ">/tmp/debugK";
print debug "barcode:$barcode\n";

if ($barcode ){
    my $itemInfo    = eq_item_findByBarcode($dbh, $barcode, 0) ;
    if (defined $itemInfo) {
        my ($status, $circ, $firstname, $lastname) = getStatus($dbh, $barcode);
        $itemInfo->{'status'} = $status;
        my $itemInfoJSON = (defined $itemInfo)?to_json($itemInfo, {pretty=>1} ): '' ;
        my $itemTypeList = getItemTypeList($dbh);
        my $loanStats = getCircStats($dbh,$barcode);
        my $loanList = $loanStats->{'loanList'};
        print debug " itemInfoJSON : $itemInfoJSON \n";
        print debug " loanList" , to_json($loanStats->{'loanList'});
        my $circStats = {
            curBorrower => getCurBorrower($dbh,$barcode),
        };

        my $itemTypeListJSON = to_json($itemTypeList,{pretty=>1});
        my $loanListJSON = to_json($loanList,{pretty=>1});
        my $circStatsJSON = to_json($circStats,{pretty=>1});

        $template->param(
            itemInfo    => $itemInfoJSON,
            itemTypeList=> $itemTypeListJSON,
            loanList    => $loanListJSON,
            circStats => $circStatsJSON,
        );
    }
    else{
        $template->param(invalid => 1);
    }
}
$template->param(   barcode => $barcode,
                    patronItemPrivacy=>$patronItemPrivacy
);
close debug;
tmpl_write($dbh, $cgi, $cookieList, $template);

#---------------------------------------

sub getCircStats{
    my ($dbh,$barcode) = @_;

#get Loan Info
    my @borrowerList = ();
    my $sql = " select id,dateLoan,dateDue,dateReturn,u.uid as uid,firstname,lastname,userbarcode,username, o.type
                from eq_loan as l left outer join opl_user as u using (uid) left outer join eq_odl o on o.idloan = l.id
                where l.uid = u.uid && barcode = ? 
                order by dateLoan desc" ;
    my $sql_status = "select ondate,status from eq_itemStatus where barcode=? && ondate >? order by ondate limit 1";                
    my $sth = $dbh->prepare($sql);
    $sth->execute($barcode);
    my $rec;
    for (my $i = 0; $i <$MAX_brwrList; $i++) {
        $rec = $sth->fetchrow_hashref;
        last if (!$rec);  
        #$rec->{'dateLoanFormat_text'} = date_time_text($rec->{'dateLoan'},0, 'en');
        #$rec->{'dateDueFormat_text'} = date_time_text($rec->{'dateDue'}, 0, 'en');
        #if ( $rec->{'dateReturn'} )             { 
        #    $rec->{'dateReturnFormat_text'} = date_time_text($rec->{'dateReturn'}, 0, 'en');
        #}
        if(!$rec->{'uid'} ){
            $rec->{'uid'}         =-1;
            $rec->{'userbarcode'} ='No data';
            $rec->{'firstname'}   ='No data';
        }
        if ($rec->{'type'} eq 'lost'){
            my ($ondate,$status)=$dbh->selectrow_array($sql_status,undef,$barcode,$rec->{'dateReturn'});
            if(defined $status && $status ==1){
                $rec->{'returnLost'}=$ondate;
            }
        }
        push @borrowerList, $rec;  
    }
    $sth->finish;
  
    return {loanList=>\@borrowerList};
}

sub  getCurBorrower{
    my($dbh,$bc)=@_; 

    my $sth = $dbh->prepare(<<_SQL_);
    select u.firstname,u.lastname ,u.userbarcode,l.dateLoan,l.dateDue
    from eq_loan l inner join opl_user u using(uid)
    where barcode=? && dateReturn is null
_SQL_

    $sth->execute($bc);
    my $user = $sth->fetchrow_hashref;
    $sth->finish;
    return $user;
}


sub getStatus{
    my ($dbh, $barcode) = @_;
    my $sql     = "select ondate, status from eq_itemStatus where barcode =? order by ondate desc limit 1";
    my $sth     = $dbh->prepare($sql);
    $sth->execute($barcode);
    my ($dateStatus, $status ) = $sth->fetchrow_array;
    $sth->finish;

    if ( (!$dateStatus && !$status) || $status  == ITEM_ACTIVE ){
        $status = ITEM_ACTIVE;
        return ($status, 1, undef, undef);
    }
    else{
        return ($status, 1, undef, undef);
    }
}

sub saveNewStatus{
    my ($dbh, $input, $template) = @_;

    my $barcode = $input->{'bc'};
    my $newStatus = 0;
    $newStatus = ITEM_INACTIVE if ($input->{'itemStatus'} eq 'inactive');
    $newStatus = ITEM_ACTIVE if ($input->{'itemStatus'} eq 'active');
    $newStatus = ITEM_DAMAGED if ($input->{'itemStatus'} eq 'damaged');
    $newStatus = ITEM_LOST if ($input->{'itemStatus'} eq 'lost');

    my $itemCircStatus = circ_getItemStatus($dbh, {barcode=>$barcode});
    
    my $sql = "update eq_items set typeId=?, available=? where barcode = ?";
    my $sth = $dbh->prepare($sql);
    my $avail   = ($newStatus == ITEM_ACTIVE)? 1:0;
    my $typeId  = $input->{'typeId'};
    $sth->execute($typeId, $avail, $barcode);
    $sth->finish;


    if ($itemCircStatus->{'status'} == IT_STAT_ONLOAN ){
        #$template->param(deactivateLoanItem => 1);
        return;
    }
    else{
        circ_updateItemStatus($dbh,$barcode,$newStatus);
    }
}

sub getItemTypeList{
    my ($dbh) = @_;
    my $ret=[];
    my $sth= $dbh->prepare(<<_SQL_);
select  id,description
from    opl_itemType
where   itemCategory=3
_SQL_

   $sth->execute();
   while( my $t= $sth->fetchrow_hashref){
       push @$ret,$t;
   }
   $sth->finish;
   return $ret;

}

