<?php

class admin_tree extends module {
	
	var $templ = "admin_tree.htm";
	var $_get_vars = array( 'act', 'parentId', 'id' );
	var $_loc_vars = array('templ', 'obj_name');
	var $obj_name = '';

	function _on_() {
		global $R, $db;
		$tpl = $R->getTpl( $this->templ, 'body' );
		$tmp = $this->r_subtree( 0 );
		$tpl = $R->parse( 'rows', $tmp, $tpl );
		$tpl = $R->set( 'form', '', $tpl );
		return $R->clear( $tpl );
	}
	
	function _on_edit() {
		global $R, $cat;
		$tpl = $R->getTpl( $this->templ, 'body' );

		$obj = new cobject ($this->obj_name);
		if (!$this->id && $this->parentId ) {
			$obj->set('parent_id', $this->parentId );				
		} else {
			$obj->byId( $this->id );
		}
		$form = new form( $obj );
		$tpl = $R->set( 'form', $form->render(), $tpl );
		$tmp = $this->r_subtree( '' );
		$tpl = $R->parse( 'rows', $tmp, $tpl );
	
		return $R->clear( $tpl );
	}
	
	function _on_save_edit() {
		global $cat;
		$obj = new cobject($this->obj_name);
		$obj->lPost();
		$obj->save();
		$this->reindex(0);
		_redirect("?cat=" . $cat->cat . '&act=edit&id='.$obj->id);
	}
	
	function r_subtree( $id, $level = 1 ) {
		global $R, $core_db;
		$tpl = $R->getTpl( $this->templ, 'row' );
		$tplu = $R->getTpl( $this->templ, 'row_unvisible' );
		$tpls = $R->getTpl( $this->templ, 'sep' );
		$obj = new cobject( $this->obj_name );
		$db2 = $core_db->q( $obj->getSelect( ' AND `parent_id` = "'.$id.'" ORDER BY `title` ') );
		while ( $db2->r() ) {
			$obj->lRow( $db2 );
			if ($obj->get('_sys_unvisible')) {
				$tt = $obj->assign( $tplu );		
			} else {
				$tt = $obj->assign( $tpl );		
			}
			for( $i=0; $i<$level; $i++ ) {
				$tt = $R->parse( 'seps', $tpls, $tt );
			}
			$tmp = $this->r_subtree($db2->f('id'), ($level+1));
			$out .= $R->parse( 'subrows', $tmp, $tt );
		}

		return $out;
	}

 	function reindex($id, $level = 1) {
        global $core_db;
   		$obj = new cobject( $this->obj_name );
   		$pobj = new cobject( $this->obj_name );

    
        $parr_ids = array(); 
        if ( $id ) {
		    $pobj->byId($id);
            $parr_ids = explode(',', $pobj->get('path_ids'));
            $parr_titles = explode('>', $pobj->get('path_titles'));
        }

		$db2 = $core_db->q( $obj->getSelect( ' AND `parent_id` = "'.$id.'" ') );
		while ( $db2->r() ) {
			$obj->lRow( $db2 );
            $parr_ids_tmp = $parr_ids;
            $parr_ids_tmp[] = $db2->f('id');

            $parr_titles_tmp = $parr_titles;
            $parr_titles_tmp[] = $db2->f('title');

            $obj->set('path_ids', implode(',', $parr_ids_tmp));
            $obj->set('path_titles', implode(' > ', $parr_titles_tmp));
            $obj->set('level', $level);
            $obj->save();
			$this->reindex($db2->f('id'), ($level+1));
		}
    }
	
}	

?>