<?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
*/

include_once(MAIN_SOURCE_PATH.'/modules/admin/inc/class.blocks.php');
include_once(MAIN_SOURCE_PATH.'/inc/class.html.php');
include_once(MAIN_SOURCE_PATH.'/modules/admin/inc/class.modules.php');
include_once(MAIN_SOURCE_PATH.'/modules/admin/inc/class.tmpl.php');
class admin_control_blocks{
	static $error = false;
	static $act = 'index';
	static $path_tmpl = false;
	static $path_m = false;
	static $url_m = false;
	static $path = false;

	function __construct(){}
	
	static function get(){
	global $MAIN_PAGE;
		self::$path_m = MAIN_SOURCE_PATH.'/modules/'.$MAIN_PAGE -> dirname();
		self::$url_m = MAIN_SOURCE_URL.'/modules/'.$MAIN_PAGE -> dirname();
		self::$act = !empty($_REQUEST['act']) ? $_REQUEST['act'] : self::$act;
		
		if ( false===is_callable('self::'.self::$act, false)){
			sys_error(ERROR_404);
		}
		$func = self::$act;

		preg_match('#^'.$MAIN_PAGE -> dirname().'_(.*)$#iUs',$_REQUEST['p_name'],$res);
		self::$path =$res[1];
		self::$path_tmpl = self::$path_m.'/tmpl/'.self::$path;
		return self::$func();
	}
	
	
	static function index(){
		$b = blocks::query('b');
		$b -> include_modules('m','m.m_name');
		$b -> set_orderby('b.m_path','ASC');
		$b -> set_orderby('b.b_name','ASC');
		//$p -> set_debug(1);
		$b -> get('
			b.*,
			b.b_type_content AS type,
			b.b_access as access_checked,
			b.b_id as countLinkTmpl
			'
		,false);
		$t = new PHPTAL( self::$path_tmpl.'/main.html' );
		$t ->rows = $b -> rows();

			  //  список модулей
		$t -> module_list =  modules::listSelect('');
		return $t -> execute();
	}


	static function reload(){
		sys_block_disable();
		$t = new PHPTAL( self::$path_tmpl.'/inc/row.html' );
		$t -> execute = true;

		$b = blocks::query('b');
		$b -> include_modules('m','m.m_name');
		$b -> set_orderby('b.m_path','ASC');
		$b -> set_orderby('b.b_name','ASC');
		$b -> where_path($_POST['filter_module']);
		//$b -> set_debug(1);
		$b -> get('
			b.*,
			b.b_type_content AS type,
			b.b_access as access_checked,
			b.b_id as countLinkTmpl'
		,false);
		$t -> rows = $b -> rows();
		HL::ajaxContent( $t -> execute() );
		exit();
	}
	

	/**
	*	Доступ к блоку свободный/по группам
	*
	*/
	static function freeAccess(){
	
		sys_block_disable();
		try{
			$m = blocks::searchById($_POST['id']);
			//$m -> set_debug(1);
			if ( false===$m ){
				throw new Exception('Ошибка: блок не выбран!');
			}
			$m -> set('b_access',$_POST['access']);
			$m -> update();
			//HL::ajaxMessage( '' );
		}catch( Exception $e ){
			HL::ajaxError( $e -> getMessage() );
		}
		
		self::reload();
		exit();
	}


	
	static function delete(){
		sys_block_disable();
		try{
			$m = blocks::searchById($_POST['id']);
			if ( false===$m ){
				throw new Exception('Ошибка: блок не выбран!');
			}
			$m -> delete();
		}catch( Exception $e ){
			HL::ajaxError( $e -> getMessage() );
		}
	
		self::reload();
		exit();
	}

	

	static function edit(){
		sys_block_disable();
		$b = blocks::query('b');
		//$b -> set_debug(1);
		if ( false===$b -> where_id($_POST['id']) ){
			$row = array(
				'b_func' 						=> false,
				'type_content_html' => 1,
				'b_id' 							=> false, 
				'tmplSelect'				=> filedsGetBlocks::tmplSelect(),
				'groupsSelect' 			=> filedsGetBlocks::groupsSelect(),
				'tmplBlockSelect'		=> filedsGetBlocks::tmplBlockSelect(),
				
				 );
		}else{
			$b -> get('*, 
			  b_type_content 	AS type_content_tmpl,
			  b_type_content 	AS type_content_php,
			  b_type_content 	AS type_content_html,
			  b.b_id 					AS countLinkTmpl,
			  b_id 						AS groupsSelect,
			  b_tmpl 					AS tmplBlockSelect
			  ',false);
			$row = $b -> row();
		}
	

		$t = new PHPTAL( self::$path_tmpl.'/edit.html' );
		$t -> row = $row;
		HL::ajaxWindow( '' ,$t -> execute() );
	}


	private function save(){
		sys_block_disable();
		try{
			$p = blocks::searchById($_POST['id']);
			  //  если загрузить блок не удалось, значит его нужно создать
			if ( false===$p ){
				$p = blocks::create();
				$create = true;
			}
			//$p -> set_debug(1);
			foreach( $_POST['form'] as $k=>$v){
				$p -> set($k,$v);
			}
			$id = ( $create ) ? $p -> insert() :  $p -> update();
				//	обновляем права доступа к блоку
			blocks::set_groups($id,$_POST['groups']);
					  //  удалим все упоминания о блоке в шаблонах системы
			if ( !$_POST['id'] ){ 
			    //  только для новых блоков
			  include_once(MAIN_SOURCE_PATH.'/modules/admin/inc/class.tmpl.php');
			  tmpl::clear_tmpl($id);
			    //  добавляем блок в выбранные шаблоны оформления страниц
			  $set_tmpl = is_array($_POST['set_tmpl']) ? $_POST['set_tmpl'] : array();
			  foreach( $set_tmpl as $t_id ){
			    $tmpl = tmpl::load_id($t_id);
			    $tmpl -> add_block($id);
			    unset($tmpl);
			  }

			}
			
		}catch( Exception $e ){
			HL::ajaxError( $e -> getMessage() );
		}
	
		self::reload();
		exit();
	}
	
	
	static function block2tmpl(){
	global $MAIN_DB;
		$b = blocks::searchById($_GET['id']);
		$t = new PHPTAL( self::$path_tmpl.'/block2tmpl.html' );
		$t -> b_name = $b -> get('b_name');
			//
		$sql = "
			SELECT stbl.* ,st.t_name
			FROM ".$MAIN_DB -> prefix("system_tmpl_block_link")." stbl 
			LEFT JOIN ".$MAIN_DB -> prefix("system_tmpl")." st USING(t_id)
			WHERE stbl.b_id='".$_GET['id']."'" ;
		$res = $MAIN_DB -> query($sql);
		$rows = array();
		while( $row = $MAIN_DB -> fetch_array($res) ){
			$rows[]=$row;
		}
		$t -> rows = $rows;
		$t -> b_id = $_GET['id'];
		return $t -> execute();
	}

	/**
	*	быстрое обновление
	*
	*/
	static function updateKey(){
	global $MAIN_DB;
		sys_block_disable();
		try{
			$sql = "UPDATE ".$MAIN_DB -> prefix("system_tmpl_block_link")." SET `".$_POST['key']."`='".$_POST['value']."' WHERE id='".$_POST['id']."'";
			$MAIN_DB -> query($sql);
			HL::ajaxMsg( 'Измнения сохранены' );
		}catch( Exception $e ){
			HL::ajaxError( $e -> getMessage() );
		}
	}

	static function add_link(){
		sys_block_disable();

			$row = array(
				'tmplSelect' 		=> tmpl_q::tmplSelect(),
				'b_id'					=>	$_GET['id']
				 );
		$t = new PHPTAL( self::$path_tmpl.'/add_link.html' );
		$t -> row = $row;
		HL::ajaxWindow( '' ,$t -> execute() );
	}

	static function save_link(){
	global $MAIN_DB;
		sys_block_disable();
		$sql = "
		INSERT INTO ".$MAIN_DB -> prefix("system_tmpl_block_link")." 
		SET 
			b_id='".$_POST['b_id']."',
			t_id='".$_POST['t_id']."',
			`var`='".$_POST['var']."',
			`options`='".$_POST['options']."'";
		$MAIN_DB -> query($sql);
		self::block2tmplReload();
		exit();
	}

	static function del_link(){
	global $MAIN_DB;
		sys_block_disable();
		$sql = "DELETE FROM  ".$MAIN_DB -> prefix("system_tmpl_block_link")." WHERE id='".$_POST['id']."'";
		$MAIN_DB -> query($sql);
		self::block2tmplReload();
		exit();
	}


	static function block2tmplReload(){
	global $MAIN_DB;
		$t = new PHPTAL( self::$path_tmpl.'/inc/row_block2tmpl.html' );
		$t -> execute = true;
			//
		$sql = "
			SELECT stbl.* ,st.t_name
			FROM ".$MAIN_DB -> prefix("system_tmpl_block_link")." stbl 
			LEFT JOIN ".$MAIN_DB -> prefix("system_tmpl")." st USING(t_id)
			WHERE stbl.b_id='".$_POST['b_id']."'" ;
		$res = $MAIN_DB -> query($sql);
		$rows = array();
		while( $row = $MAIN_DB -> fetch_array($res) ){
			$rows[]=$row;
		}
		$t -> rows = $rows;
		HL::ajaxContent( $t -> execute() );
		exit();
	}

	
	
		
	/*private function ajax_edit_short(){
		sys_block_disable();
		$p = new b_query('p');
		$p -> where_id($_REQUEST['block_id']);
		$p -> get('*');
		$row = $p ->  row();
		
		$t = new PHPTAL(  M_PATH.'/tmpl/control_blocks/edit_short.html' );
		$t -> row = $row ;
		$GLOBALS['_RESULT']['content'] =  $t -> execute();
		$GLOBALS['_RESULT']['title'] = 'редактировать';
		exit();
	}
	
	
	private function ajax_save_short_form(){
		sys_block_disable();
		$p = blocks::load_id($_POST['id']);
		//$p -> set_debug(1);
		$p -> set('b_content',$_POST['form']['b_content']);
		$id = $p -> update();

		$GLOBALS['_RESULT']['msg'] = M_ADMIN_TMPL_SAVE;
		exit();
	}*/
	
	
}