#!/usr/bin/perl

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;
my $input = $cgi->Vars();
my ($permission, $cookie, $template) = tmpl_read(
    {
        dbh             => $dbh,
        cgi             => $cgi,
        tmplFile        => 'util/catTypeInfo.tmpl',
    }
);
my $op = $input->{'op'};
my $catId  = $input->{'catId'};
my $catTypeInfo;
if ($op && $op eq 'load'){
    if ($catId ne ""){
        $catTypeInfo = getCatTypeInfo($dbh, $catId);
        if ($catTypeInfo){
            $template->param(
                status      => 'loadOK',
                catid       =>  $catTypeInfo->{'catid'},
                cattype     =>  $catTypeInfo->{'cattype'},
                catname     =>  $catTypeInfo->{'catname'},
                maxloan     =>  $catTypeInfo->{'maxloans'},
                maxreserv   =>  $catTypeInfo->{'maxreserv'},
                required    =>  $catTypeInfo->{'required'},
                defaultPerm =>  $catTypeInfo->{'defaultPerm'},
            );
        }
        else{
            $template->param(
                status      => 'loadFail',
                errorCode   => 1,
                errorMsg    => 'Cannot get info ' . $catId . 'Please try again later.'
            );
        }
    }
    else{
         $template->param(
                status      => 'loadFail',
                errorCode   => 1,
                errorMsg    => 'Cannot get info ' . $catId . 'Please try again later.'
            );

    }
}
elsif($op eq 'save'){
    if ($catId > 0){
        my $ret = update_category($dbh,  
                        $input->{'typeName'},      
                        ($input->{'maxLoan'})   ? $input->{'maxLoan'} : 0,
                        ($input->{'maxReserve'})? $input->{'maxReserve'} : 0,
                        ($input->{'permissions'})?$input->{'permissions'} : "",
                        $input->{'catId'} );
        if ($ret){
            $template->param(
                status      => 'updateOK',
            );
        }
        else{
            $template->param(
                status=> 'updateError', 
                errorCode   => 2,
                errorMsg    => 'Error: cannot update. this user type [' . $input->{'typeName'}  . '] exists.'
            );

        }
    }
    else{
        my $ret = insert_category($dbh,  
                       $input->{'cType'},  
                       $input->{'typeName'},      
                       ($input->{'maxLoan'})   ? $input->{'maxLoan'} : 0,
                       ($input->{'maxReserve'})? $input->{'maxReserve'} : 0  , 
                       ($input->{'permissions'})?$input->{'permissions'} : "" );
        if ($ret){
            $template->param(
                status  => 'saveOK',
            );
        }
        else{
            $template->param(
                status=> 'saveError', 
                errorCode   => 2,
                errorMsg    => 'Error: cannot add. New adding user type [' . $input->{'typeName'}  . '] exists.'
            );
        }
    }
}
elsif($op eq 'delete'){
    if ($catId && $catId > 0){
        my $ret = delete_category($dbh, $input->{'catId'} ); 
        if ($ret){
            $template->param(status=> 'deleteOK');
        }
        else{
            $template->param(
                status      => 'deleteError',
                errorCode   => 3,
                errorMsg    => 'Error: cannot delete this user. Please try again!'
            );
        }
    }
}

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

########################################################################################

sub getCatTypeInfo {
    my ($dbh, $catId) = @_;
    return if (! $catId || $catId eq "");
    #my $sql = "select * from opl_category where catid = ? ";
    my $sql = "select * from opl_category_tmp where catid = ? ";
    my $ret = $dbh->selectrow_hashref($sql,undef,$catId);
    if (! $ret){
        return;
    }
    return $ret;
}

sub update_category{

    my ($dbh, $typeName, $maxLoan, $maxReserve, $permissions, $catId) = @_;
    my $query = $dbh->prepare("select catid from opl_category_tmp where LCASE(catname) = ?");
    $query->execute(lc($typeName));
    my $ret =   $query->fetchrow_array();
    if ($ret && $ret != $catId ) {
        $query->finish;
        return 0;
    }

    my $sql = "update  opl_category_tmp 
            set catname = ?,
                maxloans= ?,
                maxreserv= ?,
                defaultPerm=?
            where   catid           = ?";

    my @bindVal = ($typeName, $maxLoan,$maxReserve,$permissions,$catId );
    $dbh->do($sql, undef, @bindVal);
    return 1;
}

sub insert_category{

    my ($dbh, $catType ,$typeName, $maxLoan, $maxReserve, $permissions) = @_;
    $catType =~ s/^\s+|\s+$//g;

    my $query = $dbh->prepare("select catid from opl_category_tmp where LCASE(catname) = ?");
    $query->execute(lc($typeName));
    my $ret =   $query->fetchrow_array();
    if ($ret) {
        $query->finish;
        return 0;
    }
    else{
        my $sql = "insert into opl_category_tmp
                    set     cattype   = ?,  
                            catname   = ?,
                            maxloans  = ?,
                            maxreserv = ?,
                            defaultPerm=?";

        my @bindVal = ($catType, $typeName, $maxLoan,$maxReserve,$permissions);
        $dbh->do($sql, undef, @bindVal);
        addItemTypeParam($dbh, $catType);
    }
    $query->finish;
    return 1;
}


sub delete_category{
    
    my ($dbh,$catid) = @_;
    my $ret_1 = $dbh->do("delete from opl_category_tmp where catid=$catid");
    my $ret_2 = $dbh->do("delete from opl_itemTypeParam_tmp where userTypeId = $catid ");
    my $ret = ($ret_1)?$ret_1:0;
    return $ret;

}

sub addItemTypeParam {
    my ($dbh, $userType) = @_;
    my @bindVal = ($userType);
    my ($userTypeId) = $dbh->selectrow_array("select catid from opl_category_tmp where cattype = ?", undef, @bindVal);
    if (!$userTypeId) {
        return;
    }
    my $sth = $dbh->prepare(<<_SQL_);
select  itemTypeId
from    opl_itemTypeParam_tmp
group by itemTypeId
_SQL_
    
    my $sth_addItemTypeParam = $dbh->prepare(<<_SQL_);
insert into opl_itemTypeParam_tmp
set     itemTypeId    = ?,
        userTypeId    = ?,
        loanPeriod    = 0,
        renewalPeriod = 0,
        reservePeriod = 0,
        holdPeriod    = 0,
        gracePeriod   = 0,
        maxRenewal    = 0,
        fine          = 0
_SQL_

    my $rv = $sth->execute() || return;
    while (my ($itemTypeId) = $sth->fetchrow_array) {
        $rv = $sth_addItemTypeParam->execute($itemTypeId, $userTypeId) || return;
    }
    $sth_addItemTypeParam->finish;
    $sth->finish;
    return $rv;
}

