#!/usr/bin/perl

#use utf8;
use strict;
use CGI;

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

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

my $cgi = CGI->new;
# $cgi->param('aaa') returns an array of aaa
my $input = $cgi->Vars();
#my $op = $input->{'op'};
#my @category = ($cgi->param('cat'));
use JSON;


my ($permission, $cookieList, $template) = tmpl_read(
    {
        dbh             => $dbh,
        cgi             => $cgi,
        tmplFile        => 'util/editItemType.tmpl',
        reqPermission   => 'pref_edit',
    }
);

my $selectedCategory = $input->{'selectedCat'};
   $selectedCategory = ($selectedCategory =~ m/^[123]$/)?$selectedCategory:1;

if ($permission && $permission->{'pref_edit'}) {
          
    my $itemTypeId = $input->{'itemTypeId'};
    my $itemCatList=getItemCategoryList($dbh);
    
    my $itemTypeInfo=undef;
    my $itemTypeParam=[];
    if(defined $itemTypeId){
         $itemTypeInfo=getItemTypeInfo($dbh, $itemTypeId);
         if(defined $itemTypeInfo){
             $itemTypeParam =getItemTypeParam($dbh, $itemTypeId);
             $selectedCategory =  $itemTypeInfo->{'itemCategory'};
         }
         else{
             $template->param(ERROR_NOT_FOUND_TYPE=>1);
         }
    }
    else{
        $itemTypeInfo={};
        $itemTypeInfo->{'itemCategory'}=$itemCatList->[0]->{"id"};
        my ($defaultItemTypeId) = $dbh->selectrow_array('select id from opl_itemType order by defaultType desc limit 1');
        $itemTypeParam =getItemTypeParam($dbh, $defaultItemTypeId);
        $template->param(isNew=>1);
    }
  
    my $itemTypeInfoJSON  = defined $itemTypeInfo?to_json($itemTypeInfo, {pretty => 1}) :"{}";
    my $itemTypeParamJSON = to_json($itemTypeParam, {pretty => 1})  ;
    my $itemCatListJSON   = to_json($itemCatList, {pretty => 1})  ;
    $template->param(itemCatListJSON   => $itemCatListJSON,
                     itemTypeInfoJSON  => $itemTypeInfoJSON ,
                     itemTypeParamJSON => $itemTypeParamJSON,
                     selectedCategory  => $selectedCategory || 1,
                     );
    
}




$template->param(hlpUrl     => Opals::Constant->getHlpUrl('itemtype') );

tmpl_write($dbh, $cgi, $cookieList, $template);
#$dbh->disconnect();


################################################################################
sub getItemTypeParam {
    my ($dbh, $itemTypeId) = @_;

    my $sth =$dbh->prepare(<<_SQL_);
select  catname,
        catid as userTypeId,
        if(loanPeriod div 24>0, loanPeriod div 24, loanPeriod) loan_len,if(loanPeriod div 24>0,'day','hour') loan_unit, 
        if(renewalPeriod div 24>0,renewalPeriod  div 24,renewalPeriod ) renewal_len,if(renewalPeriod div 24>0,'day','hour') renewal_unit, 
        if(reservePeriod div 24>0,reservePeriod  div 24, reservePeriod) reserve_len,if(reservePeriod div 24>0,'day','hour') reserve_unit, 
        if(holdPeriod div 24>0, holdPeriod div 24,holdPeriod ) hold_len,if(holdPeriod div 24>0,'day','hour') hold_unit, 
        if((gracePeriod div 24>0 && gracePeriod mod 24 =0),gracePeriod div 24,gracePeriod) grace_len, 
        if((gracePeriod div 24>0 && gracePeriod mod 24 =0),'day',gracePeriodUnit) grace_unit,
        maxRenewal,maxItemLoan
from    opl_category c left outer join opl_itemTypeParam p on p.userTypeId=c.catid and p.itemTypeId=?
  

_SQL_

    my @userTypeDataList;
    $sth->execute($itemTypeId);
    while(my $rec = $sth->fetchrow_hashref){
        my $userTypeData={};
        $userTypeData->{'maxRenewal'}       = $rec->{'maxRenewal'}||0;
        $userTypeData->{'maxItemLoan'}      = $rec->{'maxItemLoan'}||0;
        $userTypeData->{'catname'}          = $rec->{'catname'};
        $userTypeData->{'userTypeId'}       = $rec->{'userTypeId'};

        $userTypeData->{'loanPeriod'}       = {len=>$rec->{'loan_len'}||0,   unit=>$rec->{'loan_unit'}};
        $userTypeData->{'holdPeriod'}       = {len=>$rec->{'hold_len'}||0,   unit=>$rec->{'hold_unit'}};
        $userTypeData->{'renewalPeriod'}    = {len=>$rec->{'renewal_len'}||0,unit=>$rec->{'renewal_unit'}};
        $userTypeData->{'gracePeriod'}      = {len=>$rec->{'grace_len'}||0,  unit=>$rec->{'grace_unit'}};
        $userTypeData->{'reservePeriod'}    = {len=>$rec->{'reserve_len'}||0,unit=>$rec->{'reserve_unit'}};

        push @userTypeDataList, $userTypeData;


    }
    


    return (\@userTypeDataList);
}

################################################################################
sub getItemTypeInfo{
    my ($dbh, $itemTypeId) = @_;
    my $sql = <<_SQL_;
select  *
from    opl_itemType
where   id = ?
_SQL_
    my $itemType = $dbh->selectrow_hashref($sql, undef, $itemTypeId);

    return $itemType;

}



################################################################################
sub getItemCategoryList {
    my ($dbh) = @_;
    my @itemCatList = ();
    my $sth = $dbh->prepare("select *  from opl_itemCategory order by id");
    $sth->execute();
    while ( my $ic = $sth->fetchrow_hashref){
        push @itemCatList, {
            id          => $ic->{'id'},
            description => $ic->{'description'},
            typeIdList =>getItemTypeIdList($dbh,$ic->{'id'})
        };
   }
   $sth->finish;
   return \@itemCatList;
}
################################################################################
#Tue, May 10, 2016 @ 12:29:33 EDT
sub getItemTypeIdList{
    my($dbh,$catId)=@_;
    my $sth=$dbh->prepare("select id from opl_itemType where itemCategory=?");
    $sth->execute($catId);
    my $typeIdList=[];
    while( my ($typeId)=$sth->fetchrow_array) {
        push @$typeIdList,$typeId;
    }
    return $typeIdList;
}
