<?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 Category extends Catalog_Controller
{

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


/*
*
*	Constructor
*
*/
	function Category()
	{

		parent::Catalog_Controller();

		$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_category');

	}


/*
*
*	index
*
*/
	function index()
	{
		redirect('category/add');
	}


/*
*
*	add category
*
*	@param - category parent id
*
*/
	function add($iParentId=0,$aPreFill=array())
	{

		$aData = array();
	
		// get category list
		$aData['data']['CategoryList'] = $this->Catalog_model->GetCategoryTreeForCategory($this->aSystemVar['cur_lang']);
		
		// if category list empty - it means that category adding is restricted		
		if ( 0 == count($aData['data']['CategoryList']) )
		{
			$this->load->view($this->aSystemVar['template_viewer_root'] . 'design_items/gr_noaccess', array());
			return false;
		}
		
		$this->aHeaderVar['page_title'] = $this->lang->line('add_category');

		if ( !$this->bLogIn )
			redirect('user/login/category:add:' . $iParentId );

		$this->load->library('validation');

		$aData['data']['Category'] = array(
			'Id'			=> '',
			'ParentId'		=> $iParentId,
			'CatLang'		=> $this->aSystemVar['cur_lang'],
			'Title'			=> '',
			'BaseName'		=> '',
			'Description'	=> '',
			'Keywords'		=> '',
			'Icon'			=> '',
			'SecurityCode'	=>	$this->config->item('security_code')
		);

		// fill data array with default values
		foreach ( $aData['data']['Category'] as $key => $value )
			if ( !empty($aPreFill[$key]) )
				$aData['data']['Category'][$key] = $aPreFill[$key];

// parent category
		$aData['data']['Category']['BreadCrambList'] = array();
		$aPCat = $this->Catalog_model->getLocCategory($iParentId,$aData['data']['Category']['CatLang']);
		if (0 < count($aPCat))
		{
			$aData['data']['ParentCategory']['Id'] = $aPCat['Id'];
			$aData['data']['ParentCategory']['Title'] = $aPCat['Title'];
			$aData['data']['Category']['BreadCrambList'] = $this->Catalog_model->GetNamedBreadCramb($aPCat['BreadCramb'],$aData['data']['Category']['CatLang']);
		}
		else
			$aData['data']['ParentCategory']['Id'] = 0;

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

	}

/*
*
*	edit category
*
*	@param - id of category to edit
*
*/
	function edit( $iCategoryId = '' )
	{

		if ( '' == $iCategoryId || !is_numeric($iCategoryId) )
			redirect('');

		$this->load->library('validation');

		$aData['data']['Category'] = $this->Catalog_model->getLocCategory($iCategoryId,$this->aSystemVar['cur_lang']);

		if( $this->Catalog_model->ext_file_exists($this->config->item('base_dir').$this->config->item('category_pic_url').$aData['data']['Category']['Id'].'/'.$aData['data']['Category']['Pic'].$aData['data']['Category']['Ext']) )
			$aData['data']['Category']['IconUrl'] = base_url() . $this->config->item('category_pic_url') . $aData['data']['Category']['Id'] . '/' . $aData['data']['Category']['Pic'] . $aData['data']['Category']['Ext'];
		else
			$aData['data']['Category']['IconUrl'] = '';

// parent category
		$aData['data']['Category']['BreadCrambList'] = array();
		$aPCat = $this->Catalog_model->getLocCategory($aData['data']['Category']['ParentId'],$this->aSystemVar['cur_lang']);
		if (0 < count($aPCat))
		{
			$aData['data']['ParentCategory']['Id'] = $aPCat['Id'];
			$aData['data']['ParentCategory']['Title'] = $aPCat['Title'];
			$aData['data']['Category']['BreadCrambList'] = $this->Catalog_model->GetNamedBreadCramb($aPCat['BreadCramb'],$this->aSystemVar['cur_lang']);
		}
		else
			$aData['data']['ParentCategory']['Id'] = 0;

// get category list
		$aData['data']['CategoryList'] = $this->Catalog_model->GetCategoryTreeForCategory($this->aSystemVar['cur_lang']);
// add root caregory
		$aData['data']['CategoryList']['-1'] = array('Id'=>0,'Title'=>'-- add as primary --');

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

	}

/*
*
*	save category
*
*/
	function save()
	{

		$this->load->library('validation');

		$rules['CategoryId']	= "trim|numeric";
		$rules['ParentId']		= "trim|required|numeric|callback__gr_categ_check";
//		$rules['CatLang']		= "trim|required|alfa";
		$rules['Title']			= "trim|required|xss_clean";
		$rules['BaseName']		= "trim|required|callback__basename_check";
		$rules['Description']	= "trim|required|xss_clean";
		$rules['Keywords']		= "trim|xss_clean";
		if ( $this->config->item('security_code') && !$this->input->post('CategoryId') && !$this->bAdmin )
			$rules['SecurityCode']	= "required|strtoupper|callback__security_code_check";

		$this->validation->set_rules($rules);
		$this->validation->set_error_delimiters('<div class="error">', '</div>');
		if ($this->validation->run() == FALSE)
		{

			$aData = array(
				'Id'			=> '',
				'CategoryId'	=> $this->input->post('CategoryId'),
				'ParentId'		=> $this->input->post('ParentId'),
				'CatLang'		=> $this->input->post('CatLang'),
				'Title'			=> htmlspecialchars(wordwrap( ucwords( str_replace( '& ', '&amp; ', $this->input->post('Title') ) ), 35, ' ', true)),
				'BaseName'		=> $this->input->post('BaseName'),
				'Description'	=> htmlspecialchars(wordwrap( $this->input->post('Description'), 35, ' ', true)),
				'Keywords'		=> htmlspecialchars(wordwrap( $this->input->post('Keywords'), 35, ' ', true)),
				'SecurityCode' 	=>	$this->config->item('security_code')
			);

			$this->add(($this->input->post('NewParentId')?$this->input->post('NewParentId'):$this->input->post('ParentId')),$aData);
			return false;
		}

// check for anonimous mod
		if ( !$this->bLogIn )
			redirect('');

// check for admin rights if someone edit existing category
		if ( $this->input->post('CategoryId') && !$this->bAdmin )
			redirect('');

		$aData = array(
			'ParentId'		=>	( $this->input->post('NewParentId') ? $this->input->post('NewParentId') : $this->input->post('ParentId') ),
		);

// generate unique basename for category
		$sBaseName = $this->input->post('BaseName') ? $this->input->post('BaseName') : $this->input->post('Title');
		$aData['BaseName'] = $this->Catalog_model->GetUniqBaseName($sBaseName, 'zok_category', $this->input->post('CategoryId'));

// set category status = 'active' if it is posted by admin
		if ( $this->bAdmin )
			$aData['Status'] = 'active';
		elseif ( !$this->input->post('CategoryId') )
			$aData['Status'] = $this->_grGetValue('new_categ_status');

// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// update category table
		if ( $this->input->post('CategoryId') )
		{
			$this->db->where('`zok_category`.`Id` = \'' . $this->input->post('CategoryId') . '\'');
			$this->db->update( 'zok_category', $aData );

		}
		else
		{
			$this->db->insert( 'zok_category', $aData );
			$iLastId = $this->db->insert_id();
			$this->db->update( 'zok_category', array ( 'BreadCramb'	=>	addslashes( $this->Catalog_model->GetNumericBreadCramb( $iLastId ) ) ), 'Id=\'' . $iLastId . '\'' );
		}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// update category lang table

		$iCategoryId = $this->input->post('CategoryId')?(int)$this->input->post('CategoryId'):$iLastId;
		$iCatLang = $this->input->post('CatLang')?$this->input->post('CatLang'):$this->aSystemVar['cur_lang'];

		$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('Title', true)), 35, ' ', true)),
			'Description'	=>	htmlspecialchars(wordwrap( $this->input->post('Description', true), 35, ' ', true)),
			'Keywords'		=>	htmlspecialchars(wordwrap( $this->input->post('Keywords', 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);
		}

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

		$sCatPath = $this->config->item('base_dir') . $this->config->item('category_pic_path') . $iCategoryId . '/';

// get original category info
// Uses for picture upload
		if ( !empty($iCategoryId) )
		{
			$this->db->select('`zok_category`.*');
			$this->db->where('`zok_category`.`Id` = \'' . $iCategoryId . '\'');
			$rRes = $this->db->get('`zok_category`');
			$aOldData = $rRes->row_array();
		}

		if( !empty($_FILES['Icon']['name']) )
		{
			$this->Catalog_model->createFolder($iCategoryId,$this->config->item('base_dir').$this->config->item('category_pic_path'));

			$config['upload_path']		= $sCatPath;
			$config['encrypt_name']		= true;
			$config['allowed_types']	= $this->config->item('catalog_image_type');
			$config['max_size']			= $this->config->item('max_upload_size');
			$config['max_width']		= $this->config->item('max_upload_width');
			$config['max_height']		= $this->config->item('max_upload_height');

			$this->load->library('upload', $config);

			if ( $this->upload->do_upload('Icon') )
			{

				$aFileData = $this->upload->data();

				$config['image_library'] = $this->config->item('catalog_image_library');
				$config['source_image'] = $aFileData['full_path'];
				//$config['new_image'] = $aFileData['raw_name'] . '_thumb' . $aFileData['file_ext'];
				$config['maintain_ratio'] = TRUE;
				$config['width'] = $this->config->item('category_icon_width');
				$config['height'] = $this->config->item('category_icon_height');;
				//$config['width'] = $this->config->item('post_thumb_width');
				//$config['height'] = $this->config->item('post_thumb_height');

				$this->load->library('image_lib');
				$this->image_lib->initialize($config);
				$this->image_lib->resize();
				$this->image_lib->clear();

				$aIconData['Pic']	= $aFileData['raw_name'];
				$aIconData['Ext']	= $aFileData['file_ext'];

				$this->db->where('`zok_category`.`Id` = \'' . $iCategoryId . '\'');
				$this->db->update( 'zok_category', $aIconData );
			}
			else
			{
				$error = array('error' => $this->upload->display_errors());
				print_r($error);
				exit;
			}
		}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------

// delete pictures if necessary:
		if ( !empty($aOldData['Pic']) && !empty($aIconData['Pic']) )
		{
			@unlink($sCatPath.'/'.$aOldData['Pic'].$aOldData['Ext']);
		}

		if ( $this->input->post('DeletePic') && !empty($aOldData['Pic']) && empty($aIconData['Pic']) )
		{
			@unlink($sCatPath.'/'.$aOldData['Pic'].$aOldData['Ext']);

			$this->db->where( '`Id`=\'' . $iCategoryId . '\'');
			$this->db->update('`zok_category`', array ( 'Pic' => '', 'Ext' => '' ));
		}

// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
		if ('0' == $this->input->post('ParentId') )
			redirect('');
		else
			redirect( 'catalog/index/' . $this->input->post('ParentId') );

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

	}


/*
*
*	check for security code
*
*	@param - user's version of security code
*
*	@return bool
*
*/
	function _security_code_check( $sCode = '' )
	{

		if ( '1' != $this->config->item('security_code') )
		return TRUE;


		if ( empty($sCode) || md5($sCode) != $this->session->userdata('securityhash') )
		{
			$this->validation->set_message('_security_code_check', $this->lang->line('security_code_check') );
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}

/*
*
*	check for proper basename
*
*	@param - user's version of basename
*
*	@return bool
*
*/
	function _basename_check( $sBaseName = '' )
	{

		if ( !empty($sBaseName) && !preg_match('/^[A-Za-z0-9_\-]+$/', $sBaseName) )
		{
			$this->validation->set_message('_basename_check', $this->lang->line('basename_check') );
			return FALSE;
		}
		else
		{
			return TRUE;
		}

	}
	
	
	function _gr_categ_check( $iCategoryId )
	{

		if ( false === $this->_grIsAllowed('categ_to_categ',$iCategoryId) )
		{
			$this->validation->set_message('_gr_categ_check', 'this action restricted for your group');
			return false;
		}
		
		return true;
	}

}

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