#!/usr/bin/perl
use Opals::Context;
use Time::localtime;
use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_preference
);
use Opals::Date qw(
    date_parse
    date_text
    date_profileList
);

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

my $cgi = CGI->new;
my $input = $cgi->Vars();
my $op = $input->{'op'};
my @taxName     = ($cgi->param('taxName'));
my @rate        = ($cgi->param('rate'));
#my @unitType    = ($cgi->param('unitType'));
my @calFormat   = ($cgi->param('calFormat'));
 
my $debug;
my ($permission, $cookieList, $template) = tmpl_read(
        {
            dbh             => $dbh,
            cgi             => $cgi,
            tmplFile        => 'util/taxes.tmpl',
            reqPermission   => 'pref_edit',
        }
);

    my $tm = localtime;
    my $dateToday = sprintf("%04d-%02d-%02d", $tm->year+1900, ($tm->mon)+1, $tm->mday);


# See User.pm for the list of permissions
if ($permission && $permission->{'pref_edit'}) {

   if($op eq  'save'){
       saveTaxes($dbh);
   }
   my ($taxList) = listTaxes($dbh);
   $template->param(
         taxList  => $taxList,
         today      =>$dateToday,
   );

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

   tmpl_write($dbh, $cgi, $cookie, $template); 
#######################################
sub listTaxes{
        my ($dbh) = @_;
        
    my $sth = $dbh->prepare(<<_STH_);
    select * from  opl_taxes  
_STH_
    $sth->execute();
 
        my @taxList;
        while (my $rec = $sth->fetchrow_hashref) {
             push @taxList, $rec;
        }
        $sth->finish;
        return \@taxList;
}

#######################################
sub saveTaxes{
    my ($dbh) = @_;

  my $sth = $dbh->prepare(<<_STH_);
    delete from  opl_taxes
_STH_
    $sth->execute();
   
         $sth = $dbh->prepare(<<_STH_);
insert into opl_taxes
set     taxName   = ?,
        rate      = ?,
        calFormat =?
_STH_

        for(my $i =0; $i < scalar(@taxName);$i++) {
            $taxName[$i]      =~ s/[\r\n]//g;
              if($calFormat[$i] eq '') {
                 $calFormat[$i] = 'basic';
            }
                           
            $sth->execute($taxName[$i],$rate[$i],$calFormat[$i]);

        }

        $sth->finish;
}

    
    



