<?php

class admin_cats extends module {
	
	var $templ = "admin_cats.htm";
	var $_get_vars = array( 'act', 'parentCat', 'id', 'mname' );
	var $_loc_vars = array('templ');

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

		$obj = new cobject ('_sys_cat');
		if (!$this->id && $this->parentCat ) {
			$obj->set('parent_cat', $this->parentCat );				
		} 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 ('_sys_cat');
		$obj->lPost();
		$obj->save();

		$savedSql = $obj->save_sql;
		$this->saveMigration($savedSql);

		_redirect("?cat=" . $cat->cat . '&act=edit&id='.$obj->id);
	}
	
	function r_subtree( $cat, $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( '_sys_cat' );
		$db2 = $core_db->q( $obj->getSelect( ' AND `parent_cat` = "'.$cat.'" ORDER BY `_sys_order` ') );
		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('cat_id'), ($level+1));
			$out .= $R->parse( 'subrows', $tmp, $tt );
		}

		return $out;
	}

	function _on_getVars() {
		$module = substr($this->mname,0,-4);
		
		if(!$module) die('');

		$obj = new cobject ('_sys_cat');
		$data = explode(';', $obj->attrs['module']['templ']);
		$path = $data[0];


		require_once( _ENGINE_DIR . $path .'/' . $module.'.php' );
		$tobj = new $module();
		$html = '';
		foreach($tobj->_loc_vars as $v) {
			$html .= "<b>$"."$v</b>=".$tobj->$v.";<br>";
		}
		
		die($html);
	}


    function saveMigration($query) {
    	global $core_db;

    	$filename =   date('Ymd-Hi') . "-user-cats.sql";

		$f = fopen( _ENGINE_DIR . 'migrations/' . $filename, "a" );
		fputs($f, $query . ";\n" );
		fclose($f);

   	    $core_db->q('SELECT apply_datetime FROM _sys_db_migrations WHERE `filename` = "'.db_escape_string($filename).'" ');
   	    if (!$core_db->nr()) {
		 	$core_db->q('INSERT INTO _sys_db_migrations (`filename`,`apply_datetime`) values ("'.db_escape_string($filename).'", "'.date('Y-m-d H:i:s').'" ) ');
		}
    }
}	

?>