<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

/***************************************************************************
 *	PROJECT: ZokiSoft Smart Catalog
 *
 *	This program is a commercial software and any kind of using
 *	it must agree to ZokiSoft License Agreement.
 *
 *	This notice may not be removed from the code.
 *
 *	Copyright 2007-2008 ZokiSoft
 *	http://www.zokisoft.com/
 ***************************************************************************/

class Admin extends Catalog_Controller {


	var $aHeaderVar = array();
	var $aFooterVar = array();
	var $aSystemVar = array();
	var $aTemplateVar = array();

	var $aSubmenu = array();
	

/*
*
*	constructor
*
*/
	function Admin()
	{

		parent::Catalog_Controller();

		$this->load->model('Catalog_model');
		$this->load->model('Catalog_admin_model');

		if ( !$this->bAdmin )
			redirect('user/login/admin');

		$this->aHeaderVar['catalog_charset'] = $this->config->item('catalog_charset');

		$this->aSystemVar['template_viewer_root'] = $this->config->item('template_module_viewer');
		$this->aSystemVar['template_viewer_current'] = $this->config->item('template_viewer_admin');
		//$this->aSystemVar['current_location'] = $this->uri->uri_string();
		
		// define submenu
		$this->aSubmenu['post_list'] = array('url'=>'admin/post_list/','param'=>'','lang_key'=>'adm_post_list');
		$this->aSubmenu['post_translate'] = array('url'=>'admin/post_lang/','param'=>'','lang_key'=>'adm_translate');
//		$this->aSubmenu['post_custom_field'] = array('url'=>'admin/customfield_tree/','param'=>'','lang_key'=>'adm_customfield');
		$this->aSubmenu['post_custom_field'] = array('url'=>'admin/customfield/','param'=>'','lang_key'=>'adm_customfield');
		$this->aSubmenu['user_list'] = array('url'=>'admin/user_list/','param'=>'','lang_key'=>'adm_user_list');
		$this->aSubmenu['user_group'] = array('url'=>'admin/user_group/','param'=>'','lang_key'=>'adm_user_group');
		$this->aSubmenu['categ_list_mode'] = array('url'=>'admin/category_list/','param'=>'','lang_key'=>'adm_view_as_list');
		$this->aSubmenu['categ_tree_mode'] = array('url'=>'admin/category_list/tree','param'=>'','lang_key'=>'adm_view_as_tree');
		$this->aSubmenu['categ_translate'] = array('url'=>'admin/category_lang/','param'=>'','lang_key'=>'adm_translate');
		$this->aSubmenu['opt_catalog'] = array('url'=>'admin/option_list/','param'=>'','lang_key'=>'adm_opt_catalog');
		$this->aSubmenu['opt_post'] = array('url'=>'admin/option_list/post','param'=>'','lang_key'=>'adm_trash_post');
		$this->aSubmenu['opt_category'] = array('url'=>'admin/option_list/category','param'=>'','lang_key'=>'adm_trash_category');
		$this->aSubmenu['opt_user'] = array('url'=>'admin/option_list/user','param'=>'','lang_key'=>'adm_trash_user');
		$this->aSubmenu['opt_index'] = array('url'=>'admin/option_list/index_page','param'=>'','lang_key'=>'adm_opt_index');
		$this->aSubmenu['opt_ads'] = array('url'=>'admin/option_list/ads','param'=>'','lang_key'=>'adm_ads');
		$this->aSubmenu['opt_all'] = array('url'=>'admin/option_list/0','param'=>'','lang_key'=>'all');
		$this->aSubmenu['trash_post'] = array('url'=>'admin/trash/','param'=>'','lang_key'=>'adm_trash_post');
		$this->aSubmenu['trash_user'] = array('url'=>'admin/trash/user','param'=>'','lang_key'=>'adm_trash_user');
		$this->aSubmenu['trash_category'] = array('url'=>'admin/trash/category','param'=>'','lang_key'=>'adm_trash_category');
		$this->aSubmenu['trash_comment'] = array('url'=>'admin/trash/comment','param'=>'','lang_key'=>'adm_trash_comment');
		$this->aSubmenu['stat_list'] = array('url'=>'admin/stat_list/','param'=>'','lang_key'	=>'adm_view_as_list');
		$this->aSubmenu['stat_translate'] = array('url'=>'admin/stat_lang/','param'=>	'','lang_key'=>'adm_translate');


	}



/*
*
*	index
*
*/
	function index()
	{


		$aData = array();

		$aData['Admin'] = $this->_get_global_statistic();

		$aData['Admin']['FullStat'] = array();

// Collect Stat:

		$sNow = time();
// users ----------------------------
		$aData['Admin']['FullStat']['User'] = array();
		$this->db->select("`zok_user`.`Status`, COUNT(`zok_user`.`Id`) as UserNum");
		$this->db->where("`Status` != 'deleted'");
		$this->db->groupby('`zok_user`.`Status`');
		$rRes = $this->db->get('`zok_user`');
		$aData['Admin']['FullStat']['User']['Group'] = $rRes->result_array();
/*

		$this->db->select("COUNT(`zok_user`.`Id`) as UserNum");
		$rRes = $this->db->get('`zok_user`');
 		$aUser = $rRes->row_array();
		$aData['Admin']['FullStat']['User']['Total'] = $aUser['UserNum'];
*/

		$this->db->select("COUNT(`zok_sessions`.`session_id`) as UserNum");
		$this->db->where('last_activity > \'' . ($sNow - 5*60) . '\'' );
		$rRes = $this->db->get('`zok_sessions`');
		$aUser = $rRes->row_array();
		$aData['Admin']['FullStat']['User']['Online'] = $aUser['UserNum'];
//--------------------------------------------

// posts -------------------------------------
		$aData['Admin']['FullStat']['Post'] = array();
		$this->db->select("`zok_post`.`Status`, COUNT(`zok_post`.`Id`) as PostNum");
		$this->db->where("`Status` != 'deleted'");
		$this->db->groupby('`zok_post`.`Status`');
		$rRes = $this->db->get('`zok_post`');
		$aPostNum = $rRes->row_array();
		$aData['Admin']['FullStat']['Post']['Group'] = $rRes->result_array();
/*
		$this->db->select("COUNT(`zok_post`.`Id`) as PostNum");
		$rRes = $this->db->get('`zok_post`');
 		$aUser = $rRes->row_array();
		$aData['Admin']['FullStat']['Post']['Total'] = $aUser['PostNum'];
*/
		$this->db->select("`zok_post_stat`.*, `zok_post_lang`.`Title`");
		$this->db->join('`zok_post_lang`', '`zok_post_stat`.`PostId` = `zok_post_lang`.`PostId`');
		$this->db->orderby('`zok_post_stat`.`View`', 'desc');
		$this->db->limit('10');
		$rRes = $this->db->get('`zok_post_stat`');
		$aPostList = $rRes->row_array();
		$aData['Admin']['FullStat']['Post']['TopView'] = $rRes->result_array();

//--------------------------------------------

		$this->load->view( $this->aSystemVar['template_viewer_current'] . 'admin', $aData);

	}



/*
*
*	edit email templates
*
*/
	function email_template()
	{

		if ( ( $this->input->post('save') ) )
		{

			$this->db->select('`zok_email_template`.`Name`');
			$rRes = $this->db->get('`zok_email_template`');

			foreach ( $rRes->result_array() as $aName )
				if ( $this->input->post($aName['Name'] . '_subject') && $this->input->post($aName['Name'] . '_body') )
				{
					$this->db->where('`zok_email_template`.`Name`=\'' . $aName['Name'] . '\'');
					$this->db->update('`zok_email_template`', array('Subject' => $this->input->post($aName['Name'] . '_subject'), 'Body' => $this->input->post($aName['Name'] . '_body')));
				}

		}

		$aData['Email_template'] = array();
		$aData['Email_template'] = $this->_get_global_statistic();

		$this->db->select('*');
		$rRes = $this->db->get('`zok_email_template`');

		$aData['Email_template']['TemplateList'] = $rRes->result_array();

		$this->load->view( $this->aSystemVar['template_viewer_current'] . 'email_template', $aData);

	}


/*
*
*	mass mailer
*
*/
	function mass_mailer()
	{

		$aData['Mass_mailer'] = array();
		$aData['Mass_mailer'] = $this->_get_global_statistic();

		if ( $this->input->post('mm_subject') && $this->input->post('mm_body') )
		{

			$sStatus = '';
			$sStatus .= ( $this->input->post('active') ? '\'active\',' : '' );
			$sStatus .= ( $this->input->post('inactive') ? '\'inactive\',' : '' );
			$sStatus .= ( $this->input->post('unconfirmed') ? '\'unconfirmed\',' : '' );
			$sStatus .= '\'0\'';

			$this->db->select('`zok_user`.`Id`, `zok_user`.`Email`');
			$this->db->where('`zok_user`.`Status` IN (' . $sStatus . ')');
			$rRes = $this->db->get('`zok_user`');

			$aData['Mass_mailer']['LettersSend'] = $rRes->num_rows();

			$sNow = date("Y-m-d H:i:s");

			if ( $this->input->post('mailbox') && $this->input->post('email') )
			{
				foreach ( $rRes->result_array() as $aUser )
				{
					$this->db->insert('`zok_email_queue`', array('Sender' => $this->config->item('mail_reply'), 'Recipient' => $aUser['Email'], 'Subject' => $this->input->post('mm_subject'), 'Body' => $this->input->post('mm_body') ) );
					$this->db->insert('`zok_user_mailbox`', array('UserId' => $aUser['Id'], 'SenderId' => $this->aSystemVar['current_user']['Id'], 'RecipientId' => $aUser['Id'], 'Subject' => $this->input->post('mm_subject'), 'Body' => $this->input->post('mm_body'), 'DateSend' => $sNow ) );
				}
			}
			elseif ( $this->input->post('email') )
			{
				foreach ( $rRes->result_array() as $aUser )
					$this->db->insert('`zok_email_queue`', array('Sender' => $this->config->item('mail_reply'), 'Recipient' => $aUser['Email'], 'Subject' => $this->input->post('mm_subject'), 'Body' => $this->input->post('mm_body') ) );
			}
			elseif ( $this->input->post('mailbox') )
			{
				foreach ( $rRes->result_array() as $aUser )
					$this->db->insert('`zok_user_mailbox`', array('UserId' => $aUser['Id'], 'SenderId' => $this->aSystemVar['current_user']['Id'], 'RecipientId' => $aUser['Id'], 'Subject' => $this->input->post('mm_subject'), 'Body' => $this->input->post('mm_body'), 'DateSend' => $sNow ) );
			}
			else
			{
				$aData['Mass_mailer']['LettersSend'] = 0;
			}

		}

		$this->load->view( $this->aSystemVar['template_viewer_current'] . 'mass_mailer', $aData);

	}

/*
*
*	post list
*
*	@param - post status
*	@param - user id ( for personalized list )
*	@param - pagination page number
*
*/
	function post_list( $sStatus = '0', $sSubType = '0', $sUserId = '0', $iPage = '1' )
	{

		$sLang = $this->aSystemVar['cur_lang'];

		$sStat = @$this->input->post('Status');
		if( !empty( $sStat ) )
		{
			$sStatus = $sStat;
		}

		$sST = @$this->input->post('SubType');
		if( !empty($sST) )
		{
			$sSubType = $this->input->post('SubType');
		}

		$iUID = @$this->input->post('UserId');
		if( !empty( $iUID ) )
		{
			$sUserId = $this->input->post('UserId');
		}

		$iCat = @$this->input->post('Category');
		if( !empty($iCat) )
		{
			$iCategory = (int)$iCat;
		}
		else
		{
			$iCategory = '';
		}

		if ( ( $sAction = $this->input->post('action') ) )
		{

			$sId = '';
			foreach( $this->input->post('PostId') as $iId )
				$sId .= $iId . ',';

			$sId .= '0';

			$this->db->where( ' Id IN (' . $sId . ')');
			$this->db->update('zok_post', array( 'Status' => $sAction ) );

		}

		$aData['Post_list'] = array();
		$aData['Post_list'] = $this->_get_global_statistic();

// pagination
		$iPerPage = $this->config->item('pagination_item_per_page') * 2;
		$iStart = ($iPage-1)*$iPerPage;
// -----------

		$this->db->select('SQL_CALC_FOUND_ROWS `zok_post`.*, `zok_post_pic`.`Pic`, `zok_post_pic`.`Ext`, `zok_user`.`Name`', false);
		$this->db->from('`zok_post`');
		$this->db->join('zok_post_pic', '`zok_post`.`PrimaryPicId` = `zok_post_pic`.`Id`', 'left');
		$this->db->join('zok_user', '`zok_post`.`UserId` = `zok_user`.`Id`', 'left');
// if sStatus is 0 it is considered as empty !
		if ( !empty( $sStatus ) )
			$this->db->where('`zok_post`.`Status` = \'' . $sStatus . '\'');
		else
			$this->db->where('`zok_post`.`Status` != \'deleted\'');
		if ( !empty( $sSubType ) )
			$this->db->where('`zok_post`.`SubType` = \'' . $sSubType . '\'');
		if ( !empty( $sUserId ) )
			$this->db->where('`zok_post`.`UserId` = \'' . $sUserId . '\'');
		if ( !empty( $iCategory ) )
			$this->db->where('`zok_post`.`CategoryId` = \'' . $iCategory . '\'');
		$this->db->orderby('`zok_post`.`Id`', 'desc');
		$this->db->limit($iPerPage, $iStart);
		$rRes = $this->db->get();

// pagination: get num rows
		$this->db->select("FOUND_ROWS() as ItemNum");
		$rRes2 = $this->db->get();
		$iItemNum = $rRes2->row_array();
		$iItemNum = $iItemNum['ItemNum'];
		//build pagination string
		$this->load->library('pagination');
		$oPageNate = new Pagination();
		$oPageNate->SetParams($iPerPage, $iItemNum, $iPage, site_url('admin/post_list/' . $sStatus . '/' . $sSubType . '/' . $sUserId), $this->lang);
		$iStart = $oPageNate->GetStart();
		$aData['Post_list']['Pagination'] = $oPageNate->GeneratePageNateLine();
// end of pagination

		$aData['Post_list']['PostList'] = array();
		foreach( $rRes->result_array() as $aPost )
		{
			if ( isset($aPost['Pic']) )
				$aPost['PicUrl'] = base_url() . $this->config->item('post_pic_url') . $aPost['Id'] . '/' . $aPost['Pic'] . '_icon' . $aPost['Ext'];
			else
				$aPost['PicUrl'] = base_url() . $this->config->item('design_pic_url') . $this->config->item('thumb_no_post');

			$aPost['CountryFlag'] = $this->config->item('base_url') . $this->config->item('flag_url') . strtolower( $aPost['Country'] ) . '.gif';

			$this->db->select('`Id`');
			$this->db->where('`PostId` = \''.$aPost['Id'].'\'');
			$rRes = $this->db->get('`zok_post_pic`');
			$aPost['PicNum'] = $rRes->num_rows();

			// =================================================================================================
			// langs tricks
			// get translation
			$this->db->where('`zok_post_lang`.`PostId`=\''.$aPost['Id'].'\'');
			$rRes2 = $this->db->get('`zok_post_lang`');
			foreach ($rRes2->result_array() as $aItem)
			{
				if ($aItem['Lang'] == $this->aSystemVar['cur_lang'])
				{
					$aPost['Title'] = $aItem['Title'];
					$aPost['Body'] = nl2br($aItem['Body']);
					$aPost['Snipet'] = nl2br(substr($aItem['Body'],0,200)).' ...';
					$aPost['Keywords'] = $aItem['Keywords'];
					$aPost['Lang'] = true;
				}
				else
				{
					$aPost['TTitle'] = $aItem['Title'];
					$aPost['TBody'] = nl2br($aItem['Body']);
					$aPost['TSnipet'] = nl2br(substr($aItem['Body'],0,200)).' ...';
					$aPost['TKeywords'] = $aItem['Keywords'];
				}
			}

			// if there are no translation to default language use any other.
			if (empty($aPost['Title']))
			{
				$aPost['Title'] = $aPost['TTitle'];
				$aPost['Body'] = $aPost['TBody'];
				$aPost['Snipet'] = $aPost['TSnipet'];
				$aPost['Keywords'] = $aPost['TKeywords'];
				$aPost['Lang'] = false;
			}
			// =================================================================================================

			$aData['Post_list']['PostList'][] = $aPost;
		}

		$rRes = $this->db->query('DESCRIBE `zok_post` `SubType`');
		$aField = $rRes->row_array();
		preg_match_all( '/\'(.+?)\'/', $aField['Type'], $aOption );
		$aData['Post_list']['SubType']['SubTypeList'] = $aOption[1];

		$aData['Post_list']['Status'] = $sStatus;
		$aData['Post_list']['SubType'] = $sSubType;
		$aData['Post_list']['Category'] = $iCategory;

		$aData['Post_list']['category_list'] = $this->Catalog_model->GetCategoryTree($this->aSystemVar['cur_lang']);

		$this->aTemplateVar['submenu'][] = $this->aSubmenu['post_list'];
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['post_translate'];
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['post_custom_field'];

		$this->load->view($this->aSystemVar['template_viewer_current'] . 'post_list', $aData);

	}

/*
*	post lang
*/
	function post_lang( $sStatus = '0', $sSubType = '0', $sUserId = '0', $iPage = '1' )
	{

		$sLang = $this->aSystemVar['cur_lang'];

		$sStat = @$this->input->post('Status');
		if( !empty( $sStat ) )
		{
			$sStatus = $sStat;
		}

		$sST = @$this->input->post('SubType');
		if( !empty($sST) )
		{
			$sSubType = $this->input->post('SubType');
		}

		$iUID = @$this->input->post('UserId');
		if( !empty( $iUID ) )
		{
			$sUserId = $this->input->post('UserId');
		}

		$iCat = @$this->input->post('Category');
		if( !empty($iCat) )
		{
			$iCategory = (int)$iCat;
		}
		else
		{
			$iCategory = '';
		}

		if ( ( $sAction = $this->input->post('action') ) )
		{

			$sId = '';
			foreach( $this->input->post('PostId') as $iId )
				$sId .= $iId . ',';

			$sId .= '0';

			$this->db->where( ' Id IN (' . $sId . ')');
			$this->db->update('zok_post', array( 'Status' => $sAction ) );

		}

		$aData['Post_list'] = array();
		$aData['Post_list'] = $this->_get_global_statistic();

// pagination
		$iPerPage = $this->config->item('pagination_item_per_page') * 2;
		$iStart = ($iPage-1)*$iPerPage;
// -----------

		$this->db->select('SQL_CALC_FOUND_ROWS `zok_post`.*, `zok_user`.`Name`', false);
		$this->db->from('`zok_post`');
		$this->db->join('zok_user', '`zok_post`.`UserId` = `zok_user`.`Id`', 'left');
// if sStatus is 0 it is considered as empty !
		if ( !empty( $sStatus ) )
			$this->db->where('`zok_post`.`Status` = \'' . $sStatus . '\'');
		else
			$this->db->where('`zok_post`.`Status` != \'deleted\'');
		if ( !empty( $sSubType ) )
			$this->db->where('`zok_post`.`SubType` = \'' . $sSubType . '\'');
		if ( !empty( $sUserId ) )
			$this->db->where('`zok_post`.`UserId` = \'' . $sUserId . '\'');
		if ( !empty( $iCategory ) )
			$this->db->where('`zok_post`.`CategoryId` = \'' . $iCategory . '\'');
		$this->db->orderby('`zok_post`.`Id`', 'desc');
		$this->db->limit($iPerPage, $iStart);
		$rRes = $this->db->get();

// pagination: get num rows
		$this->db->select("FOUND_ROWS() as ItemNum");
		$rRes2 = $this->db->get();
		$iItemNum = $rRes2->row_array();
		$iItemNum = $iItemNum['ItemNum'];
		//build pagination string
		$this->load->library('pagination');
		$oPageNate = new Pagination();
		$oPageNate->SetParams($iPerPage, $iItemNum, $iPage, site_url('admin/post_lang/' . $sStatus . '/' . $sSubType . '/' . $sUserId), $this->lang);
		$iStart = $oPageNate->GetStart();
		$aData['Post_list']['Pagination'] = $oPageNate->GeneratePageNateLine();
// end of pagination

		$aData['Post_list']['PostList'] = $rRes->result_array();

		$iId = '0';
		foreach( $rRes->result_array() as $aPost )
			$iId .= ','.$aPost['Id'];

// select translations
		$aLangList = array();
		$this->db->where('`PostId` IN ('.$iId.')');
		$rRes = $this->db->get('`zok_post_lang`');
		foreach ( $rRes->result_array() as $aItem )
		{
			$aData['Post_lang']['LangList'][$aItem['PostId']][$aItem['Lang']] = $aItem;
		}


		$rRes = $this->db->query('DESCRIBE `zok_post` `SubType`');
		$aField = $rRes->row_array();
		preg_match_all( '/\'(.+?)\'/', $aField['Type'], $aOption );
		$aData['Post_list']['SubType']['SubTypeList'] = $aOption[1];

		$aData['Post_list']['Status'] = $sStatus;
		$aData['Post_list']['SubType'] = $sSubType;
		$aData['Post_list']['Category'] = $iCategory;

		$aData['Post_list']['category_list'] = $this->Catalog_model->GetCategoryTree($this->aSystemVar['cur_lang']);
		
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['post_list'];
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['post_translate'];
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['post_custom_field'];

		$this->load->view( $this->aSystemVar['template_viewer_current'] . 'post_lang', $aData);

	}



	function post_trans($iItemId='',$sLang='')
	{

		if ( $this->input->post('ItemId') && $this->input->post('ItemLang') && $this->input->post('ItemTitle') )
		{
// -----------------------------------------------------------------------
// update category lang table

			$iCategoryId = $this->input->post('ItemId');
			$iCatLang = $this->input->post('ItemLang');

			$this->db->select('`Id`');
			$this->db->where('`PostId`=\''.$iCategoryId.'\' AND `Lang`=\''.$iCatLang.'\'');
			$rRes = $this->db->get('`zok_post_lang`');

			$aData = array(
				'Title'		=>	htmlspecialchars(wordwrap($this->input->post('ItemTitle', true), 35, ' ', true)),
				'Body'		=>	htmlspecialchars(wordwrap( $this->input->post('ItemBody', true), 35, ' ', true)),
				'Keywords'	=>	htmlspecialchars(wordwrap( $this->input->post('ItemKey', true), 35, ' ', true))
				);

			if ( 0 == $rRes->num_rows() )
			{
			// insert
				$aData['PostId']=$iCategoryId;
				$aData['Lang']=$iCatLang;

				$this->db->insert('`zok_post_lang`',$aData);
			}
			else
			{
			// update
				$aId = $rRes->row_array();
				$this->db->where('`zok_post_lang`.`Id`=\''.$aId['Id'].'\'');
				$this->db->update('`zok_post_lang`', $aData);
			}

// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// go to act lang list
			$this->post_lang();
			return true;

		}

		if (empty($iItemId) || empty($sLang))
			$this->post_lang();

		$aData['data'] = array();

		$this->db->where('`PostId`=\''.$iItemId.'\'');
		$rRes = $this->db->get('`zok_post_lang`');
		$aLangList = $rRes->result_array();

		$aData['data']['Item']['Id'] = $iItemId;

		$aData['data']['LocItem'] = array();
		$aData['data']['CompItem'] = array();
		foreach ($aLangList as $aItem)
		{
			if ( $aItem['Lang'] == $sLang )
				$aData['data']['LocItem'] = $aItem;
			else
				$aData['data']['CompItem'] = $aItem;
		}

		$aData['data']['TransLang'] = array();
		foreach ($this->aSystemVar['lang_list'] as $aItem)
		{
			if ( $aItem['BaseName'] == $sLang )
			{
				$aData['data']['LocLang'] = $aItem;
				break;
			}
		}

		$this->load->view($this->aSystemVar['template_viewer_current'] . 'post_trans', $aData);


	}


/*
*
*	user list
*
*	@param - user status
*	@param - pagination page number
*
*/
	function user_list( $sStatus = '', $iPage = '1' )
	{


		if ( ( $sAction = $this->input->post('useraction') ) )
		{

			$sId = '';
			foreach( $this->input->post('UserId') as $iId )
				$sId .= $iId . ',';

			$sId .= '0';

			$this->db->where( ' Id IN (' . $sId . ')');

			if ( 'changegroup' == $sAction )
			{
				$iGroupId = (int)$this->input->post('uservalue');
				// 2 - 'member' group
				$iGroupId = 0 == $iGroupId ? 2 : $iGroupId;
				$this->db->update('zok_user', array('UserGroup'=>$iGroupId));
			}
			else
				$this->db->update('zok_user', array( 'Status' => $sAction ) );
		}

		
		$this->db->select('`Id`,`GroupName`');
		$rRes = $this->db->get('`zok_user_group`');
		$aData['User_group'] = $rRes->result_array();

		$aData['User_list'] = array();

// pagination
		$iPerPage = $this->config->item('pagination_item_per_page') * 2;
		$iStart = ($iPage-1)*$iPerPage;
// -----------

		$this->db->select('SQL_CALC_FOUND_ROWS `zok_user`.*, `zok_user_data`.`RealName`, `zok_user_data`.`Description`', false);
		$this->db->from('`zok_user`');
		$this->db->join('zok_user_data', '`zok_user`.`Id` = `zok_user_data`.`UserId`', 'left');

		// if sStatus is 0 it is considered as empty !
		$sStatus = $this->input->post('Status');
		if ( !empty($sStatus) )
			$this->db->where('`zok_user`.`Status` = \'' . $sStatus . '\'');
		else
			$this->db->where('`zok_user`.`Status` != \'deleted\'');

		$iUserGroup = (int)$this->input->post('FUserGroup');
		if( !empty($iUserGroup) )
			$this->db->where('`zok_user`.`UserGroup` = \'' . $iUserGroup . '\'');
		
		$sUser = $this->input->post('User');
		if( !empty($sUser) )
			$this->db->like('`zok_user`.`Name`', $sUser);

		$sEmail = $this->input->post('Email');
		if( !empty($sEmail) )
			$this->db->like('`zok_user`.`Email`', $sEmail);
		
		$this->db->orderby('`zok_user`.`Id`', 'desc');
		$this->db->limit($iPerPage, $iStart);
		$rRes = $this->db->get();

// pagination: get num rows
		$this->db->select("FOUND_ROWS() as ItemNum");
		$rRes2 = $this->db->get();
		$iItemNum = $rRes2->row_array();
		$iItemNum = $iItemNum['ItemNum'];
		//build pagination string
		$this->load->library('pagination');
		$oPageNate = new Pagination();
		$oPageNate->SetParams($iPerPage, $iItemNum, $iPage, site_url('admin/user_list/' . $sStatus), $this->lang);
		$iStart = $oPageNate->GetStart();
		$aData['User_list']['Pagination'] = $oPageNate->GeneratePageNateLine();
// end of pagination

		$aData['User_list']['UserList'] = array();
		foreach( $rRes->result_array() as $aUser )
		{
			if ( '' != $aUser['Pic'] )
				$aUser['PicUrl'] = base_url() . $this->config->item('user_data_url') . $aUser['UserFolder'] . $aUser['Pic'] . '_icon' . $aUser['Ext'];
			else
				$aUser['PicUrl'] = base_url() . $this->config->item('design_pic_url') . $this->config->item('user_no_icon');

			$this->db->select('`Id`');
			$this->db->where('`UserId` = \'' . $aUser['Id'] . '\' AND `Status` != \'deleted\'');
			$rRes = $this->db->get('`zok_post`');
			$aUser['PostNum'] = $rRes->num_rows();

			$this->db->select('`Id`');
			$this->db->where('`UserId` = \'' . $aUser['Id'] . '\' AND `zok_user_mailbox`.`UserId` = `zok_user_mailbox`.`RecipientId`');
			$rRes = $this->db->get('`zok_user_mailbox`');
			$aUser['MailInboxNum'] = $rRes->num_rows();

			$aData['User_list']['UserList'][] = $aUser;
		}

		$aData['User_list']['Status'] = $sStatus;
		$aData['User_list']['UserGroup'] = $iUserGroup;
		
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['user_list'];
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['user_group'];

		$this->load->view( $this->aSystemVar['template_viewer_current'] . 'user_list', $aData);

	}

	
	function user_group($sGroupName='member')
	{
	
		$aData = array();
				
		$aResGroups = array('admin','member','guest');

		if ( $this->input->post('GroupName') )
			$sGroupName = $this->input->post('GroupName');
		
		// delete group
		if ( $this->input->post('deletegroup') && $this->input->post('groupname') )
		{
			$sDelGroupName = $this->input->post('groupname');
			
			if ( !in_array($sDelGroupName,$aResGroups) )
			{
				// delete group and set group value of all users who has it to 2(member)
				$this->db->where('`GroupName`=\''.$sDelGroupName.'\'');
				$rRes = $this->db->get('`zok_user_group`');
				
				$aDelGroup = $rRes->row_array();
				
				$this->db->where('`UserGroup`',$aDelGroup['Id']);
				$this->db->update('`zok_user`',array('UserGroup'=>2));

				// delete group
				$this->db->delete('`zok_user_group`', array('Id'=>$aDelGroup['Id']) );
				
				$sGroupName = 'member';
			}		
		}
		
		// add new group
		if ( $this->input->post('newgroup') && $this->input->post('newgroupname') )
		{
			$sNewGroupName = $this->input->post('newgroupname');
			// allow only latin letters, digits and '-'
			$search = array('/[^A-Za-z0-9\-]+/');
			$replace = array('-');
			$sNewGroupName = preg_replace( $search, $replace, substr($sNewGroupName, 0, 19) );
			// check if goup name is unique
			$this->db->where('`GroupName`',$sNewGroupName);
			$rRes = $this->db->get('`zok_user_group`');
			
			// ok, add new group
			if ( 0 == $rRes->num_rows() )
			{

				$aNewGroup = array(
					'GroupName'	=> $sNewGroupName,
					'Data'		=> serialize(array('categ_to_hide'	=> Array (),
											'categ_to_categ'	=> Array (),
											'categ_to_post'		=> Array (),
											'new_categ_status'	=> 'inactive',
											'new_post_status'	=> 'inactive',
											'post_total_num'	=> '-',
											'post_pic_num'		=> '-',
											'pic_max_upload_size'	=> '-',
											'pic_max_upload_width'	=> '-',
											'pic_max_upload_height' => '-',
											'post_text_len'		=> '-',
											'post_lifetime'		=> '-'))
					);

				$this->db->insert('`zok_user_group`',$aNewGroup);
				
				$sGroupName = $sNewGroupName;
			}
		}
		
		$aData['CGroupName'] = $sGroupName;
		
		$rRes = $this->db->get('`zok_user_group`');
		
		foreach( $rRes->result_array() as $aItem )
		{
			$aData['GroupList'][] = $aItem['GroupName'];
			
			if ( $sGroupName == $aItem['GroupName'] )
				$aData['CGroupData'] = unserialize($aItem['Data']);
		}		

		// save changes in group data
		if ( $this->input->post('groupchanges') )
		{
			foreach ( $aData['CGroupData'] as $key => $value )
			{
				switch ($key)
				{
					// array of categories
					case 'categ_to_hide':
					case 'categ_to_categ':
					case 'categ_to_post':
						if ( ($aItem = $this->input->post($key)) && is_array($aItem) )
						{
							// rem redundant categories
							$aItem = $this->_prepCatList($aItem);
							$aData['CGroupData'][$key] = $aItem;
						}
						else
							$aData['CGroupData'][$key] = array();

					break;
					default:

						$aItem = $this->input->post($key);
						
						if ( isset($aItem) )
						{
							$aData['CGroupData'][$key] = $aItem;
						}
						else
							$aData['CGroupData'][$key] = '-';
					break;
				}
			}
			
			//update db record
			$this->db->where('GroupName', $sGroupName);
			$this->db->update('zok_user_group', array('Data' => serialize($aData['CGroupData'])) );
			
		}
		
		$aData['CategoryList'] = $this->Catalog_model->GetCategoryTree($this->aSystemVar['cur_lang']);
		
		$aData['bDelete'] = in_array($sGroupName,$aResGroups) ? false : true;

		$this->aTemplateVar['submenu'][] = $this->aSubmenu['user_list'];
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['user_group'];

		$this->load->view( $this->aSystemVar['template_viewer_current'] . 'user_group', $aData);
	
	}


/*
*
*	category list
*
*	@param - category status
*	@param - pagination page number
*
*/
	function category_list( $sStatus = 'list', $iParentId = '0' )
	{


		if ( ( $sAction = $this->input->post('action') ) )
		{
			if ( 'order' == $sAction )
			{

				$aOrderId = $this->input->post('OrderId');
				$aOrderValue = $this->input->post('OrderValue');

				if ( is_array($aOrderId) && is_array($aOrderValue) )
				{

					if ( function_exists('array_combine') )
					{
						$aUpdateOrder = array_combine( $aOrderId, $aOrderValue );
					}
					else
					{
						for( $i=0; $i<count($aOrderId); $i++)
							$aUpdateOrder[$aOrderId[$i]] = $aOrderValue[$i];
					}

					foreach( $aUpdateOrder as $key => $iOrder )
					{
						if ( (int)$iOrder == $iOrder )
						{
							$this->db->where('`zok_category`.`Id` = \'' . (int)$key . '\'');
							$this->db->update('`zok_category`', array( '`zok_category`.`CategoryOrder`' => $iOrder ));
						}
					}
				}
			}
			else
			{

				$sId = '';
				foreach( $this->input->post('CategoryId') as $iId )
					$sId .= $iId . ',';

				$sId .= '0';

				$this->db->where( ' Id IN (' . $sId . ')');
				$this->db->update('zok_category', array( 'Status' => $sAction ) );

			}
		}


		$aData['Category_list'] = array();
		$aData['Category_list'] = $this->_get_global_statistic();
		$aData['Category_list']['CategoryList'] = array();

		if ( 'list' == $sStatus )
		{

			$this->db->where('`zok_category`.`Id` = \'' . $iParentId . '\'');
			$rRes = $this->db->get('`zok_category`');
			$aData['Category_list']['CategoryParent'] = $rRes->row_array();

			$aCategoryList = $this->Catalog_model->getCategoriesList($iParentId,$this->aSystemVar['cur_lang'],"`zok_category`.`Status`!='deleted'");

			$aData['Category_list']['CategoryList'] = $aCategoryList;

//exit;
/*
// select categories
			$aCategoryList = $this->Catalog_model->GetSubCategoryList($iParentId,);

// select subcategories
			$sId = '';
			foreach ( $aCategoryList as $aCategory )
				$sId .= $aCategory['Id'] . ',';

			$sId = substr($sId,0,-1);

			$this->db->where('`zok_category`.`ParentId` IN (' . $sId . ') AND `zok_category`.`Status` != \'deleted\'');
			$this->db->orderby('`zok_category`.`ParentId`', 'asc');
			$rRes = $this->db->get('`zok_category`');
			$aSubCategoryList = array();
			foreach ( $rRes->result_array() as $aCategory )
				$aSubCategoryList[$aCategory['ParentId']][] = $aCategory;

// combine categories with subcategories
			foreach ( $aCategoryList as $aCategory )
			{
				if ( !empty($aSubCategoryList[$aCategory['Id']]) && is_array($aSubCategoryList[$aCategory['Id']]) )
					$aCategory['SubCategoryList'] = $aSubCategoryList[$aCategory['Id']];
				else
					$aCategory['SubCategoryList'] = array();

			}
*/
		}
		else
		{
			//$this->benchmark->mark('code_start');
			$aData['Category_list']['CategoryList'] = $this->Catalog_model->GetCategoryTree($this->aSystemVar['cur_lang'],'');
			//$this->benchmark->mark('code_end');
			//echo '<hr>' . $this->benchmark->elapsed_time('code_start', 'code_end') . '<hr>';
		}

		$aData['Category_list']['Mode'] = $sStatus;
		$aData['Category_list']['ParentId'] = $iParentId;
		$aData['Category_list']['BreadCrumb'] = @$this->Catalog_model->GetNamedBreadCramb($aData['Category_list']['CategoryParent']['BreadCramb']);

		
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['categ_list_mode'];
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['categ_tree_mode'];		
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['categ_translate'];

		
		$this->load->view( $this->aSystemVar['template_viewer_current'] . 'category_list', $aData);

	}



	function category_lang()
	{


		$aData['Category_lang'] = array();
		$aData['Category_lang'] = $this->_get_global_statistic();
		$aData['Category_lang']['CategoryList'] = array();

		$aData['Category_lang']['CategoryList'] = $this->Catalog_model->GetCategoryTree($this->aSystemVar['cur_lang'],'');

// select translations
		$aLangList = array();
		$rRes = $this->db->get('`zok_category_lang`');
		foreach ( $rRes->result_array() as $aItem )
		{
			$aData['Category_lang']['LangList'][$aItem['CategoryId']][$aItem['Lang']] = true;
		}

		$aData['Category_lang']['LangNum'] = count($this->aSystemVar['lang_list']);

		$this->aTemplateVar['submenu'][] = $this->aSubmenu['categ_list_mode'];
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['categ_tree_mode'];		
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['categ_translate'];
		

		$this->load->view( $this->aSystemVar['template_viewer_current'] . 'category_lang', $aData);

	}


	function category_trans($iCategoryId='',$sLang='')
	{

		if ( $this->input->post('CatId') && $this->input->post('CatLang') && $this->input->post('CatTitle') )
		{
// -----------------------------------------------------------------------
// update category lang table

			$iCategoryId = $this->input->post('CatId');
			$iCatLang = $this->input->post('CatLang');

			$this->db->select('`Id`');
			$this->db->where('`CategoryId`=\''.$iCategoryId.'\' AND `Lang`=\''.$iCatLang.'\'');
			$rRes = $this->db->get('`zok_category_lang`');

			$aData = array(
				'Title'			=>	htmlspecialchars(wordwrap( ucfirst($this->input->post('CatTitle', true)), 35, ' ', true)),
				'Description'	=>	htmlspecialchars(wordwrap( $this->input->post('CatDesc', true), 35, ' ', true)),
				'Keywords'		=>	htmlspecialchars(wordwrap( $this->input->post('CatKey', true), 35, ' ', true))
				);

			if ( 0 == $rRes->num_rows() )
			{
			// insert
				$aData['CategoryId']=$iCategoryId;
				$aData['Lang']=$iCatLang;

				$this->db->insert('`zok_category_lang`',$aData);
			}
			else
			{
			// update
				$aId = $rRes->row_array();
				$this->db->where('`zok_category_lang`.`Id`=\''.$aId['Id'].'\'');
				$this->db->update('`zok_category_lang`', $aData);
			}

// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// go to act lang list
			$this->category_lang();
			return true;

		}

		if (empty($iCategoryId) || empty($sLang))
			$this->category_lang();

		$aData['data'] = array();

		$this->db->where('`CategoryId`=\''.$iCategoryId.'\'');
		$rRes = $this->db->get('`zok_category_lang`');
		$aLangList = $rRes->result_array();

		$aData['data']['Category']['Id'] = $iCategoryId;

		$aData['data']['LocCategory'] = array();
		$aData['data']['CompCategory'] = array();
		foreach ($aLangList as $aItem)
		{
			if ( $aItem['Lang'] == $sLang )
				$aData['data']['LocCategory'] = $aItem;
			else
				$aData['data']['CompCategory'] = $aItem;
		}

		$aData['data']['TransLang'] = array();
		foreach ($this->aSystemVar['lang_list'] as $aItem)
		{
			if ( $aItem['BaseName'] == $sLang )
			{
				$aData['data']['LocLang'] = $aItem;
				break;
			}
		}

		$this->load->view($this->aSystemVar['template_viewer_current'] . 'category_trans', $aData);

	}

/*
*
*	comment list
*
*	@param - comment status
*	@param - pagination page number
*
*/

	function comment_list( $sStatus = '', $iPage = '1' )
	{

		$sLang = $this->aSystemVar['cur_lang'];

		if ( ( $sAction = $this->input->post('action') ) )
		{

			$sId = '';
			foreach( $this->input->post('CommentId') as $iId )
				$sId .= $iId . ',';

			$sId .= '0';

			$this->db->where( ' Id IN (' . $sId . ')');
			$this->db->update('zok_comment', array( 'Status' => $sAction ) );
		}


		$aData['Comment_list'] = array();
		//$aData['Comment_list'] = $this->_get_global_statistic();


		$this->db->select('`zok_comment`.*');
		$this->db->from('`zok_comment`');
		if ( !empty( $sStatus ) )
			$this->db->where('`zok_comment`.`Status` = \'' . $sStatus . '\'');
		else
			$this->db->where('`zok_comment`.`Status` != \'deleted\'');

		$rRes = $this->db->get();
		$iPostNum = $rRes->num_rows();

// pagination
		$iPerPage = $this->config->item('pagination_item_per_page') * 2;
		$iStart = ($iPage-1)*$iPerPage;
// -----------

		$this->db->select('SQL_CALC_FOUND_ROWS `zok_comment`.*, `zok_post_lang`.`Title`, `zok_user`.`Name`', false);
		$this->db->from('`zok_comment`');
		$this->db->join('`zok_post`', '`zok_comment`.`PostId` = `zok_post`.`Id`' );
		$this->db->join('`zok_post_lang`', '`zok_post`.`Id` = `zok_post_lang`.`PostId` AND `zok_post_lang`.`Lang`=\''.$sLang.'\'','left');
		$this->db->join('`zok_user`', '`zok_comment`.`UserId` = `zok_user`.`Id`' );
// if sStatus is 0 it is considered as empty !
		if ( !empty( $sStatus ) )
			$this->db->where('`zok_comment`.`Status` = \'' . $sStatus . '\'');
		else
			$this->db->where('`zok_comment`.`Status` != \'deleted\'');

		$this->db->orderby('`zok_comment`.`Id`', 'desc');
		$this->db->limit($iPerPage, $iStart);
		$rRes = $this->db->get();
		$aData['Comment_list']['CommentList'] = $rRes->result_array();
		$aData['Comment_list']['Status'] = $sStatus;

// pagination: get num rows
		$this->db->select("FOUND_ROWS() as ItemNum");
		$rRes2 = $this->db->get();
		$iItemNum = $rRes2->row_array();
		$iItemNum = $iItemNum['ItemNum'];
		//build pagination string
		$this->load->library('pagination');
		$oPageNate = new Pagination();
		$oPageNate->SetParams($iPerPage, $iItemNum, $iPage, site_url('admin/comment_list/' . $sStatus), $this->lang);
		$iStart = $oPageNate->GetStart();
		$aData['Comment_list']['Pagination'] = $oPageNate->GeneratePageNateLine();
// end of pagination

		$this->load->view( $this->aSystemVar['template_viewer_current'] . 'comment_list', $aData);

	}


/*
*
*	option list
*
*	@param - option group
*
*/
	function option_list( $sGroup = 'catalog' )
	{

// save options
		if ( $this->input->post('changeoption') )
		{

			$sCustomConfig = '<?php  if (!defined(\'BASEPATH\')) exit(\'No direct script access allowed\');' . "\n\n";
			$aNewOption = array();
			$rRes = $this->db->select('`zok_option`.`Name`, `zok_option`.`Value`, `zok_option`.`Type`, `zok_option`.`Group`');
			$rRes = $this->db->get('`zok_option`');

			foreach ( $rRes->result_array() as $aOption )
			{

				if ( empty($sGroup) || $aOption['Group'] == $sGroup )
				{
// rewrite 'Value' with new one
					if ( false != $this->input->post($aOption['Name']) || '0' === $this->input->post($aOption['Name']) )
						$aOption['Value'] = $this->input->post($aOption['Name']);
					elseif ( 'checkbox' == $aOption['Type'] )
						$aOption['Value'] = 0;
					else
						$aOption['Value'] = $this->config->item($aOption['Name']);

					$aNewOption[] = array( 'Name' => $aOption['Name'], 'Value' => $aOption['Value'] );
				}


//				if ( isset($aOption['Value']) )
//					$aNewOption[] = array( 'Name' => $aOption['Name'], 'Value' => $aOption['Value'] );

				$str_search=array("'","\\");
				$str_replace=array('','');
				$sCustomConfig .= '$config[\'' . $aOption['Name'] . '\'] = \'' . str_replace($str_search,$str_replace,$aOption['Value']) . '\';' . "\n";

			}

			$this->Catalog_admin_model->MakeCustomConfig( $aNewOption, true );

			$sCustomConfig .= "\n" . '?>';

			$this->load->helper('file');
			write_file( $this->config->item('config_custom_path') . $this->config->item('config_custom_name'), $sCustomConfig );

		}


		$aData['Option_list'] = array();
//		$aData['Option_list'] = $this->_get_global_statistic();

		$rRes = $this->db->query('DESCRIBE `zok_option` `Group`');
		$aField = $rRes->row_array();
		preg_match_all( '/\'(.+?)\'/', $aField['Type'], $aOption );
		$aData['Option_list']['GroupList'] = $aOption[1];

		$aData['Option_list']['OptionList'] = array();
		$this->db->select('`zok_option`.*');
		if ( !empty( $sGroup ) )
			$this->db->where('`zok_option`.`Group` = \'' . $sGroup . '\'');
		$rRes = $this->db->get('`zok_option`');
		foreach ( $rRes->result_array() as $aOption )
		{
			if ( 'callback_' == substr( $aOption['Range'], 0, 9 ) )
			{
				$sFunction = substr( $aOption['Range'], 8 );
				if ( method_exists( $this, $sFunction ) )
					$aOption['Range'] = $this->$sFunction();
			}

			$aData['Option_list']['OptionList'][] = $aOption;
		}

		$aData['Option_list']['Group'] = $sGroup;
//print_r($aData['Option_list']);
//exit;


		$this->aTemplateVar['submenu'][] = $this->aSubmenu['opt_catalog'];
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['opt_post'];
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['opt_category'];
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['opt_user'];
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['opt_index'];
        $this->aTemplateVar['submenu'][] = $this->aSubmenu['opt_ads'];
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['opt_all'];

		$this->load->view( $this->aSystemVar['template_viewer_current'] . 'option_list', $aData);

	}



	/**
	 *	get deleted items
	 *
	 *	@param	-	string
	 *	@return
	 *
	 */
	function trash( $sGroup = 'post' )
	{


		$aData['Trash'] = $this->_get_global_statistic();

		if ( 'post' == $sGroup )
		{

// delete || restore
			if ( ( $sAction = $this->input->post('action') ) )
			{
				if ( 'deleted' == $sAction )
				{
					foreach( $this->input->post('ItemId') as $iId )
						$this->Catalog_admin_model->DeletePostById( $iId );
				}
				else
				{
					$sId = '';
					foreach( $this->input->post('ItemId') as $iId )
						$sId .= $iId . ',';

					$sId .= '0';

					$this->db->where( ' Id IN (' . $sId . ')');
					$this->db->update('zok_post', array( 'Status' => $sAction ) );
				}
			}

// generate list
			$this->db->select('`zok_post`.`Id`, `zok_post_lang`.`Title`, CONCAT("post/review/", `zok_post`.`Id`) as ViewUrl');
			$this->db->join('`zok_post_lang`','`zok_post_lang`.`PostId`=`zok_post`.`Id`','left');
			$this->db->from('`zok_post`');
			$this->db->where('`zok_post`.`Status` = \'deleted\'');
			$this->db->orderby('`zok_post`.`Id`', 'asc');
			$rRes = $this->db->get();
			$aData['Trash']['ItemList'] = $rRes->result_array();

		}
		elseif ( 'user' == $sGroup )
		{

// delete || restore
			if ( ( $sAction = $this->input->post('action') ) )
			{
				if ( 'deleted' == $sAction )
				{
					foreach( $this->input->post('ItemId') as $iId )
						$this->Catalog_admin_model->DeleteUserById( $iId );
				}
				else
				{
					$sId = '';
					foreach( $this->input->post('ItemId') as $iId )
						$sId .= $iId . ',';

					$sId .= '0';

					$this->db->where( ' Id IN (' . $sId . ')');
					$this->db->update('zok_user', array( 'Status' => $sAction ) );
				}
			}

// generate list
			$this->db->select('`zok_user`.`Id`, `zok_user`.`Name` as Title, CONCAT("user/profile/", `zok_user`.`Name`) as ViewUrl');
			$this->db->from('`zok_user`');
			$this->db->where('`zok_user`.`Status` = \'deleted\'');
			$this->db->orderby('`zok_user`.`Id`', 'asc');
			$rRes = $this->db->get();
			$aData['Trash']['ItemList'] = $rRes->result_array();

		}
		elseif ( 'category' == $sGroup )
		{

// delete || restore
			if ( ( $sAction = $this->input->post('action') ) )
			{
				if ( 'deleted' == $sAction )
				{
					foreach( $this->input->post('ItemId') as $iId )
						$this->Catalog_admin_model->DeleteCategoryById( $iId );
				}
				else
				{

					$sId = '';
					foreach( $this->input->post('ItemId') as $iId )
						$sId .= $iId . ',';

					$sId .= '0';

					$this->db->where( ' Id IN (' . $sId . ')');
					$this->db->update('zok_category', array( 'Status' => $sAction ) );
				}
			}

// generate list
			$this->db->select('`zok_category`.`Id`, `zok_category_lang`.`Title`, CONCAT("category/edit/", `zok_category`.`Id`) as ViewUrl');
			$this->db->join('`zok_category_lang`','`zok_category_lang`.`CategoryId`=`zok_category`.`Id`','left');
			$this->db->from('`zok_category`');
			$this->db->where('`zok_category`.`Status` = \'deleted\'');
			$this->db->orderby('`zok_category`.`Id`', 'asc');
			$rRes = $this->db->get();
			$aData['Trash']['ItemList'] = $rRes->result_array();

		}
		else
		{
// delete || restore

			if ( ( $sAction = $this->input->post('action') ) )
			{
				if ( 'deleted' == $sAction )
				{

					foreach( $this->input->post('ItemId') as $iId )
						$this->Catalog_admin_model->DeleteCommentBranchById( $iId );

				}
				else
				{
					$sId = '';
					foreach( $this->input->post('ItemId') as $iId )
						$sId .= $iId . ',';

					$sId .= '0';

					$this->db->where( ' Id IN (' . $sId . ')');
					$this->db->update('zok_comment', array( 'Status' => $sAction ) );
				}
			}

// generate list
			$this->db->select('`zok_comment`.`Id`, `zok_comment`.`Body` as Title, CONCAT("post/review/", `zok_comment`.`PostId`) as ViewUrl');
			$this->db->from('`zok_comment`');
			$this->db->where('`zok_comment`.`Status` = \'deleted\'');
			$this->db->orderby('`zok_comment`.`Id`', 'asc');
			$rRes = $this->db->get();
			$aData['Trash']['ItemList'] = $rRes->result_array();

		}


		$aData['Trash']['Group'] = $sGroup;

		$this->aTemplateVar['submenu'][] = $this->aSubmenu['trash_post'];
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['trash_user'];
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['trash_category'];
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['trash_comment'];
		
		
		$this->load->view( $this->aSystemVar['template_viewer_current'] . 'trash', $aData);

	}

/*

	add lang

*/
	function langs()
	{

		// delete lang
		if ( is_array($this->input->post("Del")) )
		{

			$rRes = $this->db->get('`zok_lang`');
			$iLangNum = $rRes->num_rows();

			foreach ($this->input->post("Del") as $value )
			{
				$iLangNum--;
				// .. at least one lang record should remain !
				if (1>$iLangNum)
					break;

				$this->db->where('`BaseName`=\''.$value.'\'');
				$this->db->delete('`zok_lang`');
			}
		}

		// set prim lang
		if ( $this->input->post("SetDef") )
		{
			$this->db->where('`BaseName`=\''.$this->input->post("SetDef").'\'');
			$this->db->update('`zok_lang`',array('Def'=>1));
			$this->db->where('`BaseName`!=\''.$this->input->post("SetDef").'\'');
			$this->db->update('`zok_lang`',array('Def'=>0));

			redirect('admin/langs');
		}

		$aData = array();

		$this->db->from('`zok_lang`');
		$rRes = $this->db->get();
		$aData['data']['ItemList'] = $rRes->result_array();

		$aData['data']['Msg'] = '';

		// add new lang
		if ( $this->input->post("BaseName") )
		{

			$sBaseName = $this->input->post("BaseName");
			// prepear basename
			$search = array('/[^A-Za-z]+/');
			$replace = array('');
			$sBaseName = preg_replace($search,$replace,strtolower(substr($sBaseName,0,20)));

			if ( '' == $sBaseName )
			{
				$aData['data']['Msg'] = "BaseName '".$this->input->post("BaseName")."' should contain only latin letters";
			}
			else
			{
				// check basename
				foreach ($aData['data']['ItemList'] as $aItem)
				{
					if ( $sBaseName == $aItem['BaseName'] )
					{
						// this basename already exist
						$aData['data']['Msg'] = "BaseName '{$sBaseName}' already exists";
					}
				}
			}

			if ( '' == $aData['data']['Msg'] )
			{

				$aLang = array(	'BaseName' 	=>	$this->input->post("BaseName"),
								'Title'		=>	$this->input->post("Title"),
								'Def'		=>	($this->input->post("Def")?1:0)
								);

				$this->db->insert('`zok_lang`',$aLang);

				$aData['data']['ItemList'][] = $aLang;
			}
		}

		$this->load->view( $this->aSystemVar['template_viewer_current'] . 'langs', $aData);

	}

/*

	statis pages

*/
	function stat_list()
	{

		if ( ( $sAction = $this->input->post('action') ) )
		{
			if ('deleted' == $sAction)
			{
				if ( is_array($this->input->post('StatId')) )
					foreach ($this->input->post('StatId') as $Id )
					{
// TODO: DELETE files too !!
						$this->db->where('`zok_static_content`.`Id`=\''.$Id.'\'');
						$this->db->delete('`zok_static_content`');

						$this->db->where('`zok_static_lang`.`PageId`=\''.$Id.'\'');
						$this->db->delete('`zok_static_lang`');
					}
			}
		}


		$aData['Item']['ItemList'] = array();

		$this->db->select('`zok_static_content`.*');
		$rRes = $this->db->get('`zok_static_content`');

		foreach ( $rRes->result_array() as $aStat )
		{
			// langs tricks
			$this->db->where('`PageId`=\''.$aStat['Id'].'\'');
			$rRes2 = $this->db->get('`zok_static_lang`');
			foreach ($rRes2->result_array() as $aItem)
			{
				if ($aItem['Lang'] == $this->aSystemVar['cur_lang'])
				{
					$aStat['Title'] = $aItem['Title'];
					$aStat['Content'] = $aItem['Content'];
					$aStat['Lang'] = true;
				}
				else
				{
					$aStat['TTitle'] = $aItem['Title'];
					$aStat['TContent'] = $aItem['Content'];
				}
			}

			// if there are no translation to default language use any other.
			if (empty($aStat['Title']))
			{
				$aStat['Title'] = $aStat['TTitle'];
				$aStat['Content'] = $aStat['TContent'];
				$aStat['Lang'] = false;
			}

			$aData['Item']['ItemList'][] = $aStat;

		}

		$this->aTemplateVar['submenu'][] = $this->aSubmenu['stat_list'];
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['stat_translate'];

		$this->load->view( $this->aSystemVar['template_viewer_current'] . 'stat_list', $aData);

	}



	function stat_lang()
	{


		$aData['Item']['ItemList'] = array();

		$this->db->select('`zok_static_content`.*,`zok_static_lang`.`Lang`,`zok_static_lang`.`Title`,`zok_static_lang`.`Content`');
		$this->db->join('`zok_static_lang`','`zok_static_content`.`Id`=`zok_static_lang`.`PageId` AND `Lang`=\''.$this->aSystemVar['cur_lang'].'\'','left');
		$rRes = $this->db->get('`zok_static_content`');

		$aData['Item']['ItemList'] = $rRes->result_array();

// select translations
		$aLangList = array();
		$rRes = $this->db->get('`zok_static_lang`');
		foreach ( $rRes->result_array() as $aItem )
		{
			$aData['Item']['LangList'][$aItem['PageId']][$aItem['Lang']] = true;
		}

		$aData['Item']['LangNum'] = count($this->aSystemVar['lang_list']);

		$this->aTemplateVar['submenu'][] = $this->aSubmenu['stat_list'];
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['stat_translate'];

		$this->load->view( $this->aSystemVar['template_viewer_current'] . 'stat_lang', $aData);

	}


	function stat_trans($iPageId='',$sLang='')
	{


	}


/*	
	function customfield_tree()
	{
	
		$aData = array();
		$aCatList = $this->Catalog_model->GetCategoryTree($this->aSystemVar['cur_lang'],'');
		
// get custom fields grouped by categories
		$this->db->select('COUNT(`Id`) as Num, `CategoryPath`');
		$this->db->groupby('`CategoryPath`');
		$rRes = $this->db->get('`zok_post_cfield`');
		$aCField = $rRes->result_array();
		
		foreach ($aCatList as &$aCat)
		{
			$aCat['CFileldNum'] = 0;
			foreach ($aCField as $aItem)
			{
				if ( false !== strpos($aCat['BreadCramb'],$aItem['CategoryPath']) )
					$aCat['CFileldNum']+=$aItem['Num'];
			}
		}

		$aData['Category_list']['CategoryList'] = $aCatList;
	
		$this->load->view( $this->aSystemVar['template_viewer_current'] . 'customfield_categ_roll', $aData);	
	
	}
*/	
	
/*

	add custom fields

*/
	function customfield($sAction='view',$iItemId='',$sLang='')
	{

		switch ( $sAction )
		{
			case 'add':
						$this->_custom_field_add();
						break;
			case 'save':
						$this->_custom_field_save();
						break;
			case 'edit':
						$this->_custom_field_edit($iItemId,$sLang);
						break;
			case 'delete':
						$this->_custom_field_del($iItemId);
						break;
			default:
						$this->_custom_field_roll();
						break;
		}

		return true;

	}


	function _custom_field_add()
	{

		$aData = array();

		$aData['data']['CategoryList'] = $this->Catalog_model->GetCategoryTree($this->aSystemVar['cur_lang']);		
		
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['post_list'];
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['post_translate'];
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['post_custom_field'];

		$this->load->view( $this->aSystemVar['template_viewer_current'] . 'customfield_add', $aData);
	}


	function _custom_field_save()
	{

		$sBaseName = $this->input->post('basename');

		$iFieldId = $this->input->post('fieldId');

		if ( empty($sBaseName) )
			redirect('admin/customfield/add');

		$sLang = $this->input->post('lang');
		if ( empty($sLang) )
			$sLang = $this->aSystemVar['cur_lang'];

		// get unique basename
		$sBaseName = $this->Catalog_model->GetUniqBaseName($sBaseName,'`zok_post_cfield`',$iFieldId);
		
		// field category
		$iCategoryId = (int)$this->input->post('CategoryId');
		
		// add field to cfield table
		$aCField= array(
			'BaseName'	=>	$sBaseName,
			'FieldType'	=>	$this->input->post('field_type'),
			'CategoryId' => $iCategoryId,			
			'Display'	=>	$this->input->post('display'),
			'Mode'		=>	$this->input->post('mode')
		);

		if ( !empty($iFieldId) )
		{
			// update
			$this->db->where('`Id`=\''.$iFieldId.'\'');
			$this->db->update('`zok_post_cfield`',$aCField);

			$aCData= array(
				'Title'		=>	$this->input->post('title'),
				'Values'	=>	$this->input->post('values')
			);

			// check if record exists
			$this->db->where('`FieldId`=\''.$iFieldId.'\' AND `Lang`=\''.$sLang.'\'');
			$rRes = $this->db->get('`zok_post_cdata`');

			if ( 0 == $rRes->num_rows() )
			{
				$aCData['FieldId'] = $iFieldId;
				$aCData['Lang'] = $sLang;

				$this->db->insert('`zok_post_cdata`',$aCData);
			}
			else
			{
				$this->db->where('`FieldId`=\''.$iFieldId.'\' AND `Lang`=\''.$sLang.'\'');
				$this->db->update('`zok_post_cdata`',$aCData);
			}
			
			// if category changed - delete clang data from all posts that dotn't have this cfield
			// TODO: check if category id has been changed
			// TODO: 1 request from categories intead of 2 ????
			// ===============================================================
			// select breadcramb from current category
			if ( !empty($iCategoryId) )
			{
				$this->db->where('`Id` = \''.$iCategoryId.'\'');
				$rRes = $this->db->get('`zok_category`');
				$aItem = $rRes->row_array();
			}
			else
				$aItem['BreadCramb'] = '0/';

			// select all categories that match with breadcramb of current category
			$this->db->where('`BreadCramb` LIKE \''.$aItem['BreadCramb'].'%\'');
			$rRes = $this->db->get('`zok_category`');
			$sIdList = '';
			foreach( $rRes->result_array() as $aItem )
			{
				$sIdList .= $aItem['Id'] . ',';
			}	
			
			$sIdList=substr($sIdList,0,-1);
			
			$this->db->query("DELETE FROM `zok_post_clang` USING zok_post_clang, zok_post
					WHERE `zok_post`.`Id` = `zok_post_clang`.`PostId`
					AND `zok_post_clang`.`FieldId` = '{$iFieldId}'
					AND `zok_post`.`CategoryId` NOT IN ({$sIdList})");
			// ===============================================================			
			
		}
		else
		{
			// add new field
			// insert

			$this->db->insert('`zok_post_cfield`',$aCField);

			$iFieldId = $this->db->insert_id();

			$aCData= array(
					'FieldId'	=>	$iFieldId,
					'Lang'		=>	$sLang,
					'Title'		=>	$this->input->post('title'),
					'Values'	=>	$this->input->post('values')
				);

			$this->db->insert('`zok_post_cdata`',$aCData);

		}

		redirect('admin/customfield');

	}


	function _custom_field_edit($iFieldId,$sLang)
	{

		$aData = array();


		if ( empty($sLang) )
			$sLang = $this->aSystemVar['cur_lang'];

		// get custom fields
		$this->db->select('`zok_post_cfield`.*,zok_post_cdata.`Title`,zok_post_cdata.`Values`');
		$this->db->join('`zok_post_cdata`','`zok_post_cdata`.`FieldId`=`zok_post_cfield`.`Id` AND `zok_post_cdata`.`Lang`=\''.$sLang.'\'','left');
		$this->db->where('`zok_post_cfield`.`Id`=\''.$iFieldId.'\'');
		$rRes = $this->db->get('`zok_post_cfield`');

		$aData['data']['CustomField'] = $rRes->row_array();

		$aData['data']['Lang'] = $sLang;

		// get category list
		$aData['data']['Category']['CategoryList'] = $this->Catalog_model->GetCategoryTree($sLang);
        
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['post_list'];
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['post_translate'];
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['post_custom_field'];

		$this->load->view( $this->aSystemVar['template_viewer_current'] . 'customfield_edit', $aData);

	}


	function _custom_field_roll()
	{

// save fields order
		$aOrder = $this->input->post('Order');
		if ( is_array($aOrder) )
		{
			foreach ($aOrder as $Id => $Order)
			{
				$this->db->where('`zok_post_cfield`.`Id`=\''.$Id.'\'');
				$this->db->update('`zok_post_cfield`',array('FieldOrder'=>$Order));
			}
		}


// get custom fields
		$iCategoryId = (int)$this->input->post('CategoryId');
		
		if ( !empty($iCategoryId) )
		{
			$this->db->where('`Id` = \''.$iCategoryId.'\'');
			$rRes = $this->db->get('`zok_category`');
			$aCCategory = $rRes->row_array();
			
			$sId = str_replace('/',',',$aCCategory['BreadCramb']);
			$sId = substr($sId,0,-1);
			
			/*
			$aIdList = explode('/',$aCCategory['BreadCramb']);
			
			$sId = '';
			foreach( $aIdList as $iId )
				if ( !empty($iId) )
					$sId .= $iId . ',';

			$sId .= '0';
			*/
			
			$this->db->where('`zok_post_cfield`.`CategoryId` IN ('.$sId.')');
		}

		$this->db->select('`zok_post_cfield`.*,`zok_category`.`BaseName` as CatBaseName,`zok_category_lang`.`Title` as CatTitle');
		$this->db->join('`zok_category`','`zok_post_cfield`.`CategoryId` = `zok_category`.`Id`','left');
		$this->db->join('`zok_category_lang`',' `zok_category`.`Id`=`zok_category_lang`.`CategoryId` AND `zok_category_lang`.`Lang`=\''.$this->aSystemVar['cur_lang'].'\'','left');
			
		$this->db->orderby('`zok_post_cfield`.`FieldOrder`');
		$rRes = $this->db->get('`zok_post_cfield`');

		$aData['data']['CustomFields'] = $rRes->result_array();

// select translations
		$rRes = $this->db->get('`zok_post_cdata`');
		foreach ( $rRes->result_array() as $aItem )
		{
			$aData['data']['LangList'][$aItem['FieldId']][$aItem['Lang']] = $aItem['Title'];
		}

// get category list
		$aData['data']['CategoryList'] = $this->Catalog_model->GetCategoryTree($this->aSystemVar['cur_lang']);
		$aData['data']['Filter']['CatId'] = $iCategoryId;
		
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['post_list'];
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['post_translate'];
		$this->aTemplateVar['submenu'][] = $this->aSubmenu['post_custom_field'];


		$this->load->view( $this->aSystemVar['template_viewer_current'] . 'customfield_roll', $aData);

	}

	function _custom_field_del($iItemId)
	{

		// delete from cfield
		$this->db->where('`Id`='.$iItemId);
		$this->db->delete('`zok_post_cfield`');

		// delete from cdata
		$this->db->where('`FieldId`='.$iItemId);
		$this->db->delete('`zok_post_cdata`');

		// delete from clang
		$this->db->where('`FieldId`='.$iItemId);
		$this->db->delete('`zok_post_clang`');

		redirect('admin/customfield');

	}


/*
*
*	generate country list
*	this is callback function. Instruction to call it keeps at database.
*	the function itself calls from OptionList function.
*
*	@param - post status
*	@param - user id ( for personalized list )
*	@param - pagination page number
*
*	@return string
*
*/
	function _get_country_list()
	{

		$sReturn = "'all',";

		$this->db->select('`zok_country`.`ISO2`');
		$rRes = $this->db->get('`zok_country`');
		foreach ( $rRes->result_array() as $aCountry )
			$sReturn .= '\'' . $aCountry['ISO2'] . '\',';

		return $sReturn;

	}


/*
*
*	generate global site statistic
*
*	@return array
*
*/
	function _get_global_statistic()
	{

		$aRet = array();

		$this->db->select('`Id`');
		$this->db->where('`Status` = \'inactive\'');
		$rRes = $this->db->get('`zok_post`');
		$aRet['Stat']['post_list']['Inactive'] = $rRes->num_rows();

		$this->db->select('`Id`');
		$this->db->where('`Status` = \'inactive\'');
		$rRes = $this->db->get('`zok_category`');
		$aRet['Stat']['category_list']['Inactive'] = $rRes->num_rows();

		$this->db->select('`Id`');
		$this->db->where('`Status` = \'inactive\'');
		$rRes = $this->db->get('`zok_user`');
		$aRet['Stat']['user_list']['Inactive'] = $rRes->num_rows();

		$this->db->select('`Id`');
		$this->db->where('`Status` = \'reported\'');
		$rRes = $this->db->get('`zok_comment`');
		$aRet['Stat']['comment_list']['Reported'] = $rRes->num_rows();

		return $aRet;

	}

/*
*	remove sub categories if parent is present
*/	
	function _prepCatList($aItem)
	{

		$aData = array();
		
		// get all categories
		$this->db->select('`Id`,`BreadCramb`');
		$rRes = $this->db->get('`zok_category`');
		
		foreach ( $rRes->result_array() as $aValue )
		{
			if ( in_array($aValue['Id'],$aItem) )
				$aData[] = $aValue;
		}
		
		// add root breadcramb
		if ( in_array(0,$aItem) )
			$aData[] = array('Id'=>'0','BreadCramb'=>'0/');
		

		$aRemKey = array();
		$iCatNum = count($aData);
		for ($i = 0;$i<$iCatNum;$i++)
			for ($j = 0;$j<$iCatNum;$j++)
			{
				if ( $i != $j && false !== strpos($aData[$j]['BreadCramb'],$aData[$i]['BreadCramb']) )
				{
					$aRemKey[] = $j;
				}
			}

		$aFinalData = array();
		// emulate array_diff_key for php < 5
		foreach ( $aData as $iKey => $aValue )
			if ( !in_array($iKey,$aRemKey) )
				$aFinalData[] = $aValue['Id'];

		return $aFinalData;
	
	}

}

/* End of file admin.php */
/* Location: ./system/application/controllers/admin.php */