#!/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_time_text
);

use Opals::Equipment qw(

    eq_item_findByBarcode

);

use Opals::Eq_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        => 'eqmnt/loan_itemStatus.tmpl',
        reqPermission   => 'eq_circ_loan',
    }
);

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

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

    getItemCircStatus($dbh,$template,$barcode, $itemInfo);
}

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

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

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

#get Loan Info
    my @borrowerList = ();
    my $sql = " select id, dateLoan, dateDue, dateReturn, u.uid as uid, firstname, lastname, userbarcode, username 
                from eq_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->{'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');
            }
        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'},
            loan_dateLoanFormat_text    => $borrowerList[0]->{'dateLoanFormat_text'},
            loan_dateDue_text    => $borrowerList[0]->{'dateDueFormat_text'},
        );
        $template->param(loaning =>1);
    }
 
#get Holding Info
    $sql    = "select  h.*, u.uid, u.firstname, u.lastname, userbarcode, username
            from    eq_reserve as r inner join eq_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($recItem->{'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 eq_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($recItem->{'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 eq_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 eq_reserve where rid = ?";
    $sth    = $dbh->prepare($sql);
    $sth->execute($recItem->{'rid'});
    $rec    = $sth->fetchrow_hashref;
    $template->param(totalReserve => $rec->{'total'});
    $sth->finish;

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

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

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

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);
    }
}

