<?php

class object_admin extends module {
	
	var $_loc_vars = array( 'templ', 'obj_name', 'del', 'add','onPage'  );
	var $_get_vars = array( 'act', 'id'  );
	var $obj;
	var $templ = 'object_admin.htm';
	var $del = true;
	var $add = true;
    var $onPage=10;

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

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

		$tpl = $R->getTpl( $this->templ, 'body' );
		$tplr = $R->getTpl( $this->templ, 'row' );
		$tpltd = $R->getTpl( $this->templ, 'td' );
		$tplth = $R->getTpl( $this->templ, 'th' );
		
		$tpl_del_td = $R->getTpl( $this->templ, 'del_td' );
		$tpl_del_th = $R->getTpl( $this->templ, 'del_th' );

		foreach( $this->obj->attrs as $attr_name => $attrs ) {
			if ( $attrs['hide'] ) continue;
			$tt = $R->set('attr_name', $attrs['desc'], $tplth );
			$tpl = $R->parse( 'head_cols', $tt, $tpl );
			
			$tt = $R->set('attr_name', $attr_name, $tpltd );
			$tplr = $R->parse( 'row_cols', $tt, $tplr);
		}
		
		if ( $this->del ) {
			$tpl = $R->parse( 'head_cols', $tpl_del_th, $tpl );
			$tplr = $R->parse( 'row_cols', $tpl_del_td, $tplr);
		}
		
		$filter = new filter( $this->obj_name );
		$filter->parse();

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

		$tpl = $R->set( 'filter', $filter->getHTML() , $tpl);
		$db2 = $db->q( $this->obj->getSelect( $filter->getSQL() .  ' ORDER BY `ID` DESC ' . $pw->getSQL() ) );
		while( $db2->r() ) {
			$this->obj->lRow($db2);
			$tt = $this->obj->assign( $tplr, true );
			$tpl = $R->parse( 'rows', $tt, $tpl );
		}
		
		$this->obj->byId($this->id);
		if ( !$this->id && !$this->add ) {
			$tpl = $R->set( 'form', '' , $tpl);
		} else {
			$tpl = $R->set( 'form', $this->r_form() , $tpl);
		}
		$tpl = $R->set( 'walker', $pw->getHTML() , $tpl);
		$tpl = $R->set( 'cur_page', $pw->page, $tpl );
		$tpl = $R->set( 'filter_url', $this->_get_filter_url(), $tpl );
		return $R->clear( $tpl );
	}
	
	
	function r_form() {
		$form = new form( $this->obj );
		return $form->render();
	}
	
	function _on_save_edit() {
		global $cat;
		if ( !$this->id && !$this->add )  _redirect('?cat=' . $cat->cat );

		$this->obj->lPost();
		if ( $this->obj->validate() ) { 
			$this->obj->save();
		} else {
			return $this->r_form();		
		}
		_redirect('?cat=' . $cat->cat . '&' . $this->_get_filter_url() .'&curpage='.$_GET['curpage'] );
	}
	
	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']);
	}
	
	function _get_filter_url() {
		foreach( $_GET as $k => $v ) {
			if ( strpos($k, $this->obj_name.'_') === 0 ) {
				$ret = '&'.$k.'='.$v;	
			}
		}
		return $ret;
	}
	

}	

?>