#!/usr/bin/perl

#use utf8;
use strict;
use CGI;
use JSON;
use Opals::Context;
my $dbh = Opals::Context->dbh();
END { $dbh->disconnect(); }

my $input=getInput();
my $prefList=undef;
if (defined $input->{'prefList'}){
    $prefList=$input->{'prefList'} ;
    if(defined $prefList){
        $prefList = savePrefList($dbh,$prefList);
    }

}


my $custPermList=$input->{'custPermList'};


if(defined $custPermList){
    $custPermList=saveCustPermList($dbh,$custPermList);
}
elsif($input->{'custRptFields'}){
    saveCustRptFields($dbh,$input->{'custRptFields'});
}
print "Content-type: text/plain\n\n";
print  to_json({prefList=>$prefList,status=>1,custPermList=>$custPermList});
#-------------------------------------------------------------------------------

sub savePrefList{
    my($dbh,$prefList)=@_;
    my $sth=$dbh->prepare("update opl_preference set val=? where var=?");
    foreach my $pref(@$prefList){
        $sth->execute($pref->{'val'}, $pref->{'var'});
    }

}
#-------------------------------------------------------------------------------

sub saveCustPermList{
    my($dbh,$custPermList)=@_;
    updateDelCustPerm($dbh,$custPermList);
    fillCustPermCode($custPermList);
    $dbh->do("delete from opl_permission where grpId=0");
    foreach my $p(@$custPermList){
        $dbh->do("insert into opl_permission set grpId=0,name=? ,code=?",undef,$p->{'pName'},$p->{'pCode'});
    }
    return $custPermList;
}
#-------------------------------------------------------------------------------

sub saveCustRptFields{
    my($dbh,$params)=@_;
    my $rpName =$params->{'rptName'};
    my $rptFieldList=$params->{'rptFieldList'};
    my $custRptFields={};
    my ($v)=$dbh->selectrow_array("select val from opl_preference where var='custRptFields'");
    if(defined $v){
        $custRptFields=decode_json($v);
    }
    $custRptFields->{$rpName}=$rptFieldList;
    open debug,">/tmp/vv"; print debug to_json($custRptFields);close debug;
    $dbh->do("replace into opl_preference set val=? , var='custRptFields'",undef,to_json($custRptFields));
}
#-------------------------------------------------------------------------------

sub fillCustPermCode{
    my($custPermList)=@_;
    my $codeList={};
    foreach my $p(@$custPermList){
        if($p->{'pCode'} ne '' && !defined $codeList->{$p->{'pCode'}}){
            $codeList->{$p->{'pCode'}}=1;
        }
        else{
            my @nameArr=split(" ",$p->{'pName'});
            my $code=@nameArr[0];
            if(scalar(@nameArr)>1){
                $code .= "_" . @nameArr[1];
            }
            $code =~ s/\W//g;
            my $tmpCode=$code;
            my $i=0;
            while($codeList->{$tmpCode}){
                $tmpCode= $code . "_$i++";
            }
            $codeList->{$tmpCode}=1;
            $p->{'pCode'}=$tmpCode;
        }
    }
    
}
#-------------------------------------------------------------------------------
sub updateDelCustPerm{
    my($dbh,$custPermList)=@_;
    my $sth=$dbh->prepare("select code from opl_permission where grpId=0");
    $sth->execute();
    my $delPermList=[];
    my $del=1;

    while( my ($code)= $sth->fetchrow_array){
       foreach my $p(@$custPermList){
           if($p->{'pCode'} eq $code){
               $del=0;
               last;
           }
       }
       if($del){
            $dbh->do("update opl_category set defaultPerm=trim(both ',' from replace(concat(',',defaultPerm,','), ',$code,' ,','))");
            $dbh->do("update opl_user set permissions=trim(both ',' from replace(concat(',',permissions,','), ',$code,' ,',')) where permissions regexp '$code'");
       }
       $del=1;
    }

}
#-------------------------------------------------------------------------------
sub getInput{
  my $in={};
  if ($ENV{'REQUEST_METHOD'} eq "POST") {
        my $json ="";
        while (<STDIN>) {
            $json .= $_;
        }
        $in = decode_json($json);
   }
   return $in;
}
