<?php

if (!check_auth() || $CURRENT_USER['level'] < 7) {
    die("Access denied!");
}
require_once dirname(__FILE__) . "/SMPHPToolkit/SMAjax.php";
CADBiSNew::instance()->script_src('js/ajax/buffer.js');
CADBiSNew::instance()->script_src('js/ajax/manager.js');
CADBiSNew::instance()->link_href('skins/smadbis/css/grid.css');
$BILL = new CBilling($GV["dbhost"], $GV["dbname"], $GV["dblogin"], $GV["dbpassword"]);
$cats = $BILL->GetUrlCategories();
global $cats_cid;
$cats_cid_title = array();
foreach ($cats as $cat) {
    $cats_cid[$cat['cid']] = $cat;
}
$ajaxbuf_url_cats = new ajax_buffer("update_buffer_cats");
$emanager = new ajax_entities_manager('entities_manager', $ajaxbuf_url_cats);
$ajaxbuf_url_matched_cats = new ajax_buffer("update_buffer_cats_matched");
//$emanager_matched = new ajax_entities_manager('entities_manager_matched', $ajaxbuf_url_matched_cats);
class cat_urls_formatter extends grid_formatter
{
    protected $_field = '';
    /**
     * Entities manager
     * @var ajax_entities_manager
     */
    protected $_cats_cid_title = null;
    protected $_manager = '{}';
    /**
     * @param string $field
            break;
        case $emanager->action->UPD:
            $item = json_decode($emanager->getItem());
            $item->keywords = explode(',', $item->keywords);
            for ($i = 0; $i < count($item->keywords); ++$i) {
                $item->keywords[$i] = rtrim(ltrim($item->keywords[$i]));
                if (strlen($item->keywords[$i]) < 4 || empty($item->keywords[$i])) {
                    array_splice($item->keywords, $i, 1);
                    $i = 0;
                }
            }
            $BILL->UpdateUrlCategoryKeywords($item->cid, $item->keywords);
            $BILL->UpdateUrlCategory($item->cid, array('title' => $item->title, 'title_ru' => $item->title_ru));
            break;
        case $emanager->action->DEL:
            $item = json_decode($emanager->getItem());
            if ($item->cid > 0) {
                $BILL->DeleteUrlCategory($item->cid);
            }
            break;
    }
    $emanager->eraseAction();
}
/**
 * Retrieve categories from the database
 */
$cats = $BILL->GetUrlCategories($cats_grid_pager->get_curpage(), $cats_grid_pager->get_pagesize(), $cats_grid->get_sorting(), $cats_grid->get_sort_direction(), $cats_grid->get_filterfield(), $cats_grid->get_filtering());
foreach ($cats as $cat) {
    $cat['keywords'] = implode(", ", $BILL->GetUrlCategoryKeywords($cat['cid']));
    $cats_ds->add_row(array($cat['cid'], $cat['title'], $cat['title_ru'], $cat));
}