#!/usr/bin/perl

use strict;
use CGI;

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

use Opals::Constant;

use Opals::Date qw(
    date_text
);

use Opals::Tb_Record qw(

    tb_item_findByBarcode

);

use Opals::Tb_Circulation qw(
    
    circ_getItemStatus
    circ_updateItemStatus

);

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

my $MAX_brwrList = 4;

my $cgi = CGI->new;
my $input = $cgi->Vars();
my ($permission, $cookieList, $template) = tmpl_read(
    {
        dbh             => $dbh,
        cgi             => $cgi,
        tmplFile        => 'txtbk/itemStatus.tmpl',
        reqPermission   => 'tb_record_edit',

    }
);

my $loginuid = $ENV{'curUserId'};
my $barcode = $input->{'bc'};
$barcode =~  s/^\s+|\s+$//g;

if ($barcode ){
    $template->param(bc => $barcode);
    my $itemInfo    = tb_item_findByBarcode($dbh, $barcode);
    if ($itemInfo) {
        $template->param($itemInfo);
    }
    else{
        $template->param(error => 1);
    }
    if($input->{'op'} && $input->{'op'} eq 'save') {
        saveNewStatus($dbh, $input, $template);
        $itemInfo    = tb_item_findByBarcode($dbh, $barcode);
    }
    getItemCircStatus($dbh,$template,$barcode, $itemInfo);
}

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

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

sub getItemCircStatus{
    my ($dbh,$template, $barcode, $itemInfo) = @_;

#get Loan Info
    my @borrowerList = ();
    my $sql = " select id, dateLoan, dateDue, dateReturn, u.uid as uid, firstname, lastname, userbarcode, username 
                from    tb_loan as l, opl_user as u 
                where   l.uid = u.uid && barcode = ? 
                order by dateLoan desc" ;
    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->{'dateLoan_text'}  = date_text($rec->{'dateLoan'},0);
        $rec->{'dateDue_text'}  = date_text($rec->{'dateDue'},0);
        if ($rec->{'dateReturn'}){
            $rec->{'dateReturn_text'}  = date_text($rec->{'dateReturn'},0) ;
        }
        push @borrowerList, $rec;  
    }
    $sth->finish;
    $template->param(brwrList => \@borrowerList);

    if (scalar(@borrowerList)> 0 && !$borrowerList[0]->{'dateReturn'}){
        $template->param(
            loan_userbarcode    => $borrowerList[0]->{'userbarcode'},
            loan_username       => $borrowerList[0]->{'username'},
            loan_firstname      => $borrowerList[0]->{'firstname'},
            loan_lastname       => $borrowerList[0]->{'lastname'},
            loan_uid            => $borrowerList[0]->{'uid'},
            loan_dateloan       => $borrowerList[0]->{'dateLoan'},
            loan_dateDue        => $borrowerList[0]->{'dateDue'},
            loan_dateReturn     => $borrowerList[0]->{'dateReturn'},
        );
        $template->param(loaning =>1);
    }
 
#get Holding Info
    $sql    = "select  h.*, u.uid, u.firstname, u.lastname, userbarcode, username
            from    tb_reserve as r inner join tb_hold as h on r.id = h.idReserve
                    inner join opl_user as u on r.uid = u.uid
            where   r.rid = ? && h.dateLoan is null && h.dateCancel is null && h.dateExpiry > now()
            order by h.dateHold ";
    
    $sth    = $dbh->prepare($sql);
    $sth->execute($itemInfo->{'rid'});
    $rec    = $sth->fetchrow_hashref;
    $sth->finish;

    if ($rec){
        $template->param(
            hold_userbarcode    => $rec->{'userbarcode'},
            hold_username       => $rec->{'username'},
            hold_firstname      => $rec->{'firstname'},
            hold_lastname       => $rec->{'lastname'},
            hold_uid            => $rec->{'uid'},
            hold_dateHold       => $rec->{'dateHold'},
            hold_dateExpiry     => $rec->{'dateExpiry'},
        );
        $template->param(holding => 1);
    }

#get Reserve Info
    $sql = " select r.*, u.*
            from tb_reserve as r inner join opl_user as u on r.uid = u.uid
            where rid = ? && numCopyReserve > 0 && r.dateCancel is null && r.dateExpiry > now()
            order by r.dateReserve limit 1 ";

    $sth    = $dbh->prepare($sql);
    $sth->execute($itemInfo->{'rid'});
    $rec    = $sth->fetchrow_hashref;
    $sth->finish;
    
    if ($rec){
        $template->param(
            rsvr_userbarcode    => $rec->{'userbarcode'},
            rsvr_username       => $rec->{'username'},
            rsvr_firstname      => $rec->{'firstname'},
            rsvr_lastname       => $rec->{'lastname'},
            rsvr_uid            => $rec->{'uid'},
            rsvr_dateReserve    => $rec->{'dateReserve'},
            rsvr_dateExpiry     => $rec->{'dateExpiry'},
        );
        $template->param(reserving => 1);
    }
    
#get total Loans/Reserves
    $sql    = "select count(*) as total from tb_loan where barcode='$barcode'";
    $sth    = $dbh->prepare($sql);
    $sth->execute();
    $rec = $sth->fetchrow_hashref;
    $template->param(totalLoan =>$rec->{'total'});
    $sth->finish;

    $sql    = "select count(*) as total from tb_reserve where rid = ?";
    $sth    = $dbh->prepare($sql);
    $sth->execute($itemInfo->{'rid'});
    $rec    = $sth->fetchrow_hashref;
    $template->param(totalReserve => $rec->{'total'});
    $sth->finish;

    my ($status, $circ, $firstname, $lastname) = getStatus($dbh, $barcode);
    #if ($status == ITEM_ACTIVE){
    #if ($itemInfo->{'available'} == 1){
    if ($itemInfo->{'available'} == 1 && $status == ITEM_ACTIVE){
        $template->param(itemActive => 1);
    }
    else{
        my ($status, $circ, $firstname, $lastname) = getStatus($dbh, $barcode);
        if ($status == ITEM_LOST){
            $template->param(itemLost => 1);    }
        elsif($status == ITEM_DAMAGED) {
            $template->param(itemDamage => 1);  }
        elsif($status == ITEM_INACTIVE ){
            $template->param(itemInactive => 1);   }
    }

    #itemCategory = 2 => textbook
    $sth = $dbh->prepare ("select it.* from opl_itemType as it inner join opl_itemCategory as itc on it.itemCategory = itc.id where it.itemCategory = 2");
    $sth->execute();

    my @tbItemTypes = ();
    while ($rec = $sth->fetchrow_hashref){
        if (uc($rec->{'id'}) eq uc($itemInfo->{'typeId'})){
                $rec->{'sel'} = 1;
        }
        push @tbItemTypes, $rec;
    }
    $sth->finish;
    $template->param(tbItemTypes => \@tbItemTypes);

}

sub getStatus{
    my ($dbh, $barcode) = @_;
    my $sql     = "select ondate, status from tb_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});

    if ( $itemCircStatus && $itemCircStatus->{'status'} == IT_STAT_ONLOAN && $newStatus == ITEM_INACTIVE){
        $template->param(deactivateLoanItem => 1);
        return;
    }
    my $note="";
    if ( $itemCircStatus->{'status'} == IT_STAT_ONLOAN){
        $note = $itemCircStatus->{'l_uid'};
    }
    else{
        $note = $loginuid ;
    }
    my $sql = "update tb_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;

    circ_updateItemStatus($dbh,$barcode,$newStatus,$note);

}


