<?php

class object_admin extends module {

    public $_loc_vars = [ 'templ', 'obj_name', 'del', 'add','onPage'  ];
    public $_get_vars = [ 'act', 'id'  ];
    public $obj;
    public $templBlade = 'core_object_admin';

    public $del    = true;
    public $add    = true;
    public $onPage = 10;

    public function _init() {
        $this->obj = new cobject($this->obj_name);
        return parent::_init();
    }

    public function _on_() {
        global $blade;
        $db = $this->obj->getDB();

        $data = [];

        $cols = [];
        foreach ($this->obj->attrs as $attr_name => $attrs) {
            if ($attrs['hide']) {
                continue;
            }

            $cols[$attr_name] = $attrs['desc'];
        }

        $data['cols'] = $cols;

        $filter = new filter($this->obj_name);
        $filter->parse();
        $data['filter'] = $filter->getHTML();
        ;

        $db2 = $db->q($this->obj->getSelectEx('COUNT(*) as `cnt`', $filter->getSQL()));
        $db2->r();
        $size = $db2->f('cnt');

        $pw             = new Walker($size, $this->onPage);
        $data['walker'] = $pw->getHTML();
        $data['page']   = $pw->page;

        $data['row']       = $this->obj->getCollection($filter->getSQL() .  ' ORDER BY `ID` DESC ' . $pw->getSQL(), false, true);
        $data['filterUrl'] = $this->_get_filter_url();

        return $blade->run($this->getBladeTempl('body'), $data);
    }

    public function _on_edit() {
        global $blade;

        $id = intval($this->id);
        if ($id) {
            $this->obj->byId($id);
        }

        $data         = [];
        $data['form'] = $this->r_form();



        return $blade->run($this->getBladeTempl('form'), $data);
    }

    public function r_form() {
        $form = new form($this->obj);
        return $form->render();
    }

    public function _on_save_edit() {
        global $cat;

        $this->obj->lPost();

        if (!$this->obj->id && !$this->add) {
            _redirect('?cat=' . $cat->cat);
        }
        if ($this->obj->validate()) {
            $this->obj->save();
        } else {
            return $this->r_form();
        }
        _redirect('?cat=' . $cat->cat . '&' . $this->_get_filter_url() .'&curpage='.$_GET['curpage'], 'Данные сохранены');
    }

    public function _on_del() {
        global $cat;
        if ($this->del) {
            $this->obj->byId($this->id);
            $this->obj->del();
        }
        _redirect('?cat=' . $cat->cat . '&' . $this->_get_filter_url() .'&curpage='.$_GET['curpage'], 'Успешно удалено');
    }

    public function _get_filter_url() {
        foreach ($_GET as $k => $v) {
            if (strpos($k, $this->obj_name.'_') === 0) {
                $ret = '&'.$k.'='.$v;
            }
        }
        return $ret;
    }


}

?>