<?php
/**
* @author:  Bunzia Alexander <nifus@mail.ru> <http://www.weblancer.net/users/nifus/>
* @copyright: Copyright (c) 2010, Bunzia Alexander
* @version: 1.0
* @license: http://www.gnu.org/copyleft/gpl.html GNU/GPL
* @package: HiLo CMS
*/


class admin_tmpl{
	private $error = false;
	private $act = 'index';
	private $JsHttpRequest = false;
	
	public function __construct(){
	global $MAIN_PAGE;
		define('M_PATH',MAIN_SOURCE_PATH.'/modules/'.$MAIN_PAGE -> dirname() );
		define('M_URL',MAIN_SOURCE_URL.'/modules/'.$MAIN_PAGE -> dirname() );
		define('A_CHARSET', $MAIN_PAGE -> charset() );
		include_once(M_PATH.'/inc/url.php');
		include_once(M_PATH.'/inc/class.tmpl.php');
		//include_once(M_PATH.'/inc/class.modules.php');
		include_once(MAIN_SOURCE_PATH.'/modules/admin/lang/'.MAIN_LANG.'/lang.php');
		include_once(MAIN_SOURCE_PATH.'/inc/class.html.php');
		include(MAIN_SOURCE_PATH.'/ext/ajax/JsHttpRequest.php');
		$this -> JsHttpRequest = new JsHttpRequest( A_CHARSET );
		$this -> act = !empty($_REQUEST['act']) ? $_REQUEST['act'] : $this -> act;
		$GLOBALS['_RESULT']['id_request'] = $_REQUEST['id_request'];
	}
	
	public function get(){
		//sleep(2);
		$func = $this -> act;
		if ( !method_exists($this ,$func) ){
			sys_error(ERROR_404);
		}
		return $this -> $func();
	}
	
	
	
		//	главная, формирует список шаблонов
	private function index(){
		$t = new PHPTAL( M_PATH.'/tmpl/control_tmpl/main.html' );
		$p = new tmpl_q('f');
		$p -> orderby_tid('DESC');
		$p -> get('
			f.t_id, f.t_name, f.t_desc, 
			f.t_id as count_blocks, f.t_id AS blocks_url
			'
		,false);
		$rows= array();
		while( $row = $p -> row() ){
			$rows[] = arr_to_obj($row);
		}		
		$t -> rows = $rows;
		
		$e = html_control::editor('codemirror');
		$e -> set_name('desc');
		$e -> set_attr('cols',10);
		$t -> editor = $e -> show();
		return $t -> execute();
	}
	
	

	/**
  * Выводим список блоков привязанных к шаблону $_REQUEST['id']
  * 
  * @return: str 
  */
	private function blocks(){
	global $MAIN_DB;
		$id = intval($_REQUEST['id']);
		$sql = "
			SELECT 
			  *,`var` 
			FROM 
				".MAIN_PLB_TBL." gfl 
			LEFT JOIN
				".MAIN_BLK_TBL." b
			ON
				b.b_id = gfl.b_id
			WHERE 
				gfl.t_id = '".$id."' ORDER BY  gfl.sort ASC";
		$res = $MAIN_DB -> query($sql);
		$blocks= array();
		while( $row = $MAIN_DB -> fetch_array($res) ){
			$blocks[]=($row);	
		}		
		$t = new PHPTAL( M_PATH.'/tmpl/control_tmpl/blocks.html' );
		$t -> fid = $id;
		$t -> blocks = $blocks;
		return $t -> execute();
	}
	
	
		/*		AJAX	*/
		
	
	
		//	перезагружаем таблицу со списком шаблонов
	private function ajax_reload(){
		sys_block_disable();
			//	макрос таблицы
		$t = new PHPTAL( M_PATH.'/tmpl/control_tmpl/inc/tmpl_row.html' );
			//	выполнять макрос
		$t -> execute = true;
			//	выбираем страницы
		$p = new tmpl_q('f');
			//	сортировка указанная пользователем
		if ( !empty($_REQUEST['orderby_key']) ){
			$p -> $_REQUEST['orderby_key']( $_REQUEST['orderby_value']);
		}else{
			$p -> orderby_tid('DESC');
		}
		//$p -> set_debug(1);
		$p -> get('
			f.t_id, f.t_name, f.t_desc, 
			f.t_id as count_blocks, f.t_id AS blocks_url'
		,false);
		$rows= array();
		while( $row = $p -> row() ){
			
			$rows[]=arr_to_obj($row);
		}		
		$t -> rows = $rows;
		$GLOBALS['_RESULT']['content'] = $t -> execute();
		exit();
	}
	
		
	private function ajax_block_reload(){
		sys_block_disable();
			//	выбираем блоки
		include_once(M_PATH.'/inc/class.blocks.php');
		$b = blocks::query('b');
		$b -> include_pages_block_link('p',false);
		if ( !$b -> where_pid($_REQUEST['id']) ){
			sys_error(ERROR_500,'EMPTY id');
		}
		if ( !empty($_REQUEST['orderby_key']) ){
			$b -> $_REQUEST['orderby_key']( $_REQUEST['orderby_value']);
		}else{
			$b -> orderby_sort('ASC');
		}
		$b -> get('*,`var`');
		$blocks= array();
		while( $row = $b -> row() ){
			$blocks[]=arr_to_obj($row);	
		}		
					//	макрос таблицы
		$t = new PHPTAL( M_PATH.'/tmpl/control_tmpl/inc/block_row.html' );
			//	выполнять макрос
		$t -> execute = true;
		$t -> blocks = $blocks;
		$GLOBALS['_RESULT']['content'] = $t -> execute();
		exit();
	}
		
	private function ajax_edit(){
		sys_block_disable();
		$p = new tmpl_q('f');
		if ( false===$p -> where_id($_REQUEST['id']) ){
			$row = array('tmpl_ul'=>tmpl_q::tmpl_ul('') );
		}else{
		  $p -> get('*,t_url as tmpl_ul') ;
		  $row = $p ->  row();
		}
			//	список папок
		
			//	формируем страницу
		$t = new PHPTAL( M_PATH.'/tmpl/control_tmpl/form.html' );
		$t -> row = ($row );
		$GLOBALS['_RESULT']['content'] =  $t -> execute();
		$GLOBALS['_RESULT']['title'] = 'Редактировать страницу';
		exit();
	}

	private function ajax_update(){
		sys_block_disable();
		$m = tmpl::load_id($_REQUEST['id']);
		$insert = false;
		if ( false===$m ){
			$m = tmpl::create();
			$insert = true; 
			//die(A_EMPTY_ID);
		}
		
			//	обновляем имя
		$m -> set('t_name',$_POST['t_name']);
		$m -> set('t_desc',$_POST['t_desc']);
		$m -> set('t_content',$_POST['t_content']);
		$m -> set('t_page_content_var',$_POST['t_page_content_var']);
		$m -> set('t_url',$_POST['t_url']);
		if ( 	$insert ){
		  $id = $m -> insert(); 
		}else{
		   $id = $m -> update(); 
		}
		if ( false===$id ){
			die( $m -> error() );
		}
		$GLOBALS['_RESULT']['msg'] = M_ADMIN_TMPL_SAVE;
		exit();
	}
	

	private function ajax_delete(){
		sys_block_disable();
		$m = tmpl::load_id($_REQUEST['id']);
		if ( false===$m ){
			die( A_EMPTY_ID );
		}
		$m -> delete();
		exit();
	}
	
		

	
			//	форма редактирования блока на странице
	private function ajax_blocks_edit(){
	global $MAIN_DB ;
		sys_block_disable();
		include_once(M_PATH.'/inc/class.blocks.php');
		$t = new PHPTAL( M_PATH.'/tmpl/control_tmpl/blocks_edit.html' );
	  
	  $t -> id = $_GET['id'];
		$sql = "SELECT * FROM ".$MAIN_DB -> prefix("system_tmpl_block_link")." WHERE id='".$_REQUEST['id']."'";
		$row = $MAIN_DB -> fetch_array( $MAIN_DB -> query($sql));
		$t -> row = $row;
			//	выводим список блоков
		$s = new select_box();
		$s -> empty_record(false);
		$s -> selected_id($row['b_id']);
		$b = blocks::query('b');
		$b -> orderby_path('ASC');
		$b -> orderby_name('ASC');
		$b -> get('b.b_id,b.b_name');

		while( list($bid,$bname) = $b -> row() ){
			$s -> set($bid,$bname );
		}
		$t -> block_list = $s -> get();


			//	выводим
		$GLOBALS['_RESULT']['content'] =  $t -> execute();
		$GLOBALS['_RESULT']['title'] = 'mod block';	
		exit();
	}
	
	
	private function ajax_blocks_save(){
	global $MAIN_DB ;
		sys_block_disable();
		include_once(M_PATH.'/inc/class.blocks.php');
		$sql = "
		  UPDATE  ".$MAIN_DB -> prefix("system_tmpl_block_link")." 
		  SET 
		  	`b_id`='".intval($_REQUEST['b_id'])."', 	
		  	`var`='".sys_in_sql($_REQUEST['var'])."', 	
		  	options='".sys_in_sql($_REQUEST['options'])."', 
		  	title='".sys_in_sql($_REQUEST['title'])."'
		WHERE id='".$_REQUEST['id']."'";
		$MAIN_DB -> query($sql);
		
		exit();
	}	
	
	
	
		//	форма добавления блока на страницу
	private function ajax_blocks_to_page_form(){
	global $ITEMS ;
		sys_block_disable();
		$id = intval($_REQUEST['id']);
		if ( empty($id) ){
			die( A_EMPTY_ID );
		}
		include_once(M_PATH.'/inc/class.blocks.php');
		$t = new PHPTAL( M_PATH.'/tmpl/control_tmpl/blocks_to_page_form.html' );
		$t -> f_id = $id;
		
			//	выводим список блоков
		$s = new select_box();
		$s -> empty_record(false);
		
		$b = blocks::query('b');
		$b -> orderby_path('ASC');
		$b -> orderby_name('ASC');
		$b -> get('b.b_id,b.b_name');
		while( list($bid,$bname) = $b -> row() ){
			$s -> set($bid,$bname );
		}
		$t -> block_list = $s -> get();
		
			//	выводим список областей
		$s = new select_box();
		$s -> empty_record(true);
	
		foreach( $ITEMS  as $k => $v ){
			$s -> set($k,$v );
		}
		$t -> items_list = $s -> get();

			//	выводим
		$GLOBALS['_RESULT']['content'] =  $t -> execute();
		$GLOBALS['_RESULT']['title'] = 'add block';	
		exit();
	}
	
	
	
		//	удалить связь
	private function ajax_blocks_to_page_del(){
		sys_block_disable();
		
		$p = tmpl::load_id($_REQUEST['id']);
		if ( false===$p ){
			die( A_EMPTY_ID );
		}
		
		$p -> del_block($_REQUEST['b_id']);
		exit();
	}
	
		//	добавить связь
	private function ajax_blocks_to_page_save(){
		sys_block_disable();
		$p = tmpl::load_id($_REQUEST['id']);
		if ( false===$p ){
			die(A_EMPTY_ID);
		}
		$p -> add_block($_REQUEST['b_id'],$_REQUEST['item'],false);
		exit();
	}
	
		//	сохранить сортировку блоков
	private function ajax_sort_blocks_to_page(){
	global $MAIN_DB;
		sys_block_disable();
		
		$p = tmpl::load_id($_REQUEST['id']);
		if ( false===$p ){
			die(A_EMPTY_ID);
		}
		foreach( $_REQUEST['order'] AS $b_id=>$sort){
			$b_id = intval($b_id);
			$sort = intval($sort);
			if ( empty($b_id) ){
				continue;
			}
			$sql = "UPDATE ".MAIN_PLB_TBL." SET `sort`='$sort' WHERE id='$b_id'";
			$MAIN_DB -> query($sql);
		}
		exit();
	}
	
	
	/**
	* Клонирование шаблона
	*
	*/
	private function ajax_clone_form(){
		sys_block_disable();
		$p = new tmpl_q('f');
		if ( false===$p -> where_id($_REQUEST['id']) ){
		  exit();
		}
	  $p -> get('t_id') ;
		$row = $p ->  row();
			//	список папок
		
			//	формируем страницу
		$t = new PHPTAL( M_PATH.'/tmpl/control_tmpl/clone_form.html' );
		$t -> row = ($row );
		$GLOBALS['_RESULT']['content'] =  $t -> execute();
		$GLOBALS['_RESULT']['title'] = 'Клонировать шаблон';
		exit();
	}
	
	/**
	* Клонирование шаблона
	*
	*/
	private function ajax_clone_save(){
	global $MAIN_DB;
		sys_block_disable();
		$p = new tmpl_q('f');
		if ( false===$p -> where_id($_POST['id']) ){
		  exit();
		}
	  $p -> get('t_id,t_content,t_url') ;
		$row = $p ->  row();
			//	список папок
		$p =  tmpl::create();
		//$p -> set_debug(1);
		$p -> set('t_name',$_POST['t_name']);
		$p -> set('t_desc',$_POST['t_desc']);
		$p -> set('t_content',$row['t_content'] );
		$p -> set('t_url',$row['t_url']);
		$id = $p -> insert();
		
		$sql = "SELECT 	b_id,`sort`,`var`,options,title FROM ".$MAIN_DB -> prefix("system_tmpl_block_link")." WHERE t_id='".$_POST['id']."'";
		$res = $MAIN_DB -> query($sql);
		while( $row = $MAIN_DB -> fetch_array($res) ){
		  $sql = "INSERT INTO ".$MAIN_DB -> prefix("system_tmpl_block_link")." SET 
		    t_id='".$id."',
		    b_id='".$row['b_id']."',
		    `sort`='".$row['sort']."',
		    `var`='".$row['var']."',
		    options='".$row['options']."',
		    title='".$row['title']."' ";
		 $MAIN_DB -> query($sql);   
		    
		}
	  
		exit();
	}

}

?>
