#!/usr/bin/perl

#use utf8;
use strict;
use CGI;

use Opals::Context;
use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_redirect
);
use Opals::Locale qw(
    loc_getMsgFile
    loc_write
);
use Digest::SHA qw(
    sha1_base64
    sha1_hex
);



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        => 'user/createAccount.tmpl',
        }
);



  my $username  = $input->{'username'};
  my $password  = $input->{'pwd'};
  my $email     = $input->{'uEmail'};
  my $uid       = $input->{'uid'};

  my $retVal =-1;
  if($uid && $uid >0 
      && $username && $username ne ''
      && $password && $password ne ''){   
    $retVal=updateUserAccount($dbh, $username,$password,$email,$uid);
  }


my $msgValMap ={};
my $stdMsgMap  =loc_getMsgFile('user/createAccount.msg');
loc_write($template,$stdMsgMap);

if($retVal ==0){
    $template->param(creationError=>1);
}

elsif($retVal>0){
    $template->param(creationSuccess=>1);
}


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

#==============================================
#
sub updateUserAccount{
     my ($dbh, $username,$password,$email,$uid) = @_;
     $password = sha1_base64($password);
     my $permissions=getUserDefaultPermission($dbh,$uid);
     my $sth = $dbh->prepare(<<_STH_);
update opl_user 
set permissions =?,
    username = ?, password = ?, email = ?
where  uid= ?
_STH_
        $sth->execute($permissions,$username,$password,$email,$uid)|| return 0;
        $sth->finish;
        return  $uid;
}
#==============================================
#
sub getUserDefaultPermission{
     my ($dbh,$uid) = @_;
     my $permissions="";
     my $sth = $dbh->prepare(<<_STH_);
     select if(u.permissions is null,c.defaultPerm,concat(u.permissions,',',c.defaultPerm)) 
     from opl_user u inner join opl_category c on u.categorycode=c.catid 
     where uid=?
_STH_
        $sth->execute($uid)|| return 0;
        if(my ($p)=$sth->fetchrow_array){
            $permissions=$p;
        }
        $sth->finish;
     
     return  $permissions;
}

#==============================================

