#!/usr/bin/perl

use strict;
use CGI;

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

use Opals::Eq_Search qw(
      
    eq_category_getList
    eq_category_getListById

);


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

my $cgi = CGI->new;
my $input = $cgi->Vars();
my ($permission, $cookieList, $template) = tmpl_read(
    {
        dbh             => $dbh,
        cgi             => $cgi,
        tmplFile        => 'eqmnt/ajax/category/save.tmpl',
        reqPermission   => 'eq_record_edit',
    }
);

my $categoryList = eq_category_getList($dbh);

my $op = $input->{'op'} || "";
my $id = $input->{'id'} || 0;
my $assign2Id = $input->{'assign2Id'} || 0;
my $name = $input->{'category'};
my $parentId = $input->{'catList'};



    my $catId = 0;
    if ($op && $op == "delete") {
        eq_record_category_update($dbh,$id,$assign2Id);
        $catId = eq_category_delete($dbh,$id);      
    }
    else{
        $catId = eq_category_add($dbh,$name,$parentId);
    }
    my $categoryList = eq_category_getList($dbh);

    $template->param (
        catId   => $catId,
        catList => $categoryList
    );

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

sub eq_category_add {
    my ($dbh,$name,$parentId) = @_;
    
    my $sth = $dbh->prepare("insert into eq_category set name='$name', parentId=$parentId");
    $sth->execute();
    my $ret = $dbh->{'mysql_insertid'};
    $sth->finish;
    return $ret;

}

sub eq_category_delete {
    my ($dbh,$id) = @_;
    
    my $sth = $dbh->prepare("delete from eq_category where id=$id limit 1");
    $sth->execute();
    $sth->finish;
    return $id;

}

sub eq_record_category_update {

    my ($dbh,$oldId,$newId) = @_;
    my $sql = "update eq_records set category= replace(category,$oldId,$newId) where find_in_set($oldId,category)";
    my $sth = $dbh->prepare($sql);
    $sth->execute();
    $sth->finish;

}
