<?php if( ! defined('BASEPATH')) exit('No direct script access allowed');
class Hot_cats extends Controller
{
	function Hot_cats()
	{
		parent::Controller();
		check_is_login();
		$this->load->database();
	}
	
	function index()
	{
		$this->load->config('hot_cats_config');
		$data = array(
			'hot_cats' => $this->config->item('hot_cats'),
			'catalog'	=> $this->_parse_catalog()
		);
		$this->load->view(TPL_FOLDER."hot_cats",$data);
	}
	
	function _parse_catalog()
	{
		$this->db->select('cat_name,cid');
		$this->db->where('parent_id',0);
		$this->db->order_by('seqorder','asc');
		$query=$this->db->get("shop_industry_catalog");
		return $query->result();
	}
	
	function _get_catalog($cid)
	{
		$query = $this->common_model->get_record('SELECT id FROM '.$this->db->dbprefix.'shop_industry_catalog WHERE cid = ?',array($cid));
		if($query)
		{
			$this->db->select('cat_name,cid');
			$this->db->where('parent_id',$query->id);
			$this->db->order_by('seqorder','asc');
			$query1=$this->db->get("shop_industry_catalog");
			return $query1->result_array();
		}
		else
		{
			return array();
		}
	}
	
	function save_hot_cats()
	{
		$hot_cats = $this->input->post('hot_cats');
		if( ! is_array($hot_cats))
		{
			$tx_msg="<li>热门分类不能为空.</li>";
			echo_msg($tx_msg,'','no');
		}
		$str = '$config["hot_cats"] = array(';
		$t = '';
		$i = 1;
		foreach($hot_cats as $v)
		{
			$t = explode('|',$v);
			if(count($hot_cats) == $i) $str .= 'array("cat_name"=>"'.$t[0].'","cid"=>"'.$t[1].'","item"=> '.var_export($this->_get_catalog($t[1]),true).')';
			else $str .= 'array("cat_name"=>"'.$t[0].'","cid"=>"'.$t[1].'","item"=> '.var_export($this->_get_catalog($t[1]),true).'),';
			$i++;
		}
		$str .= ');';
		$this->load->helper('file');
		$string = read_file(APPPATH.'config/hot_cats_config'.EXT);
		$reg = '/\$config\[\"hot_cats\"\].+;/is';
		preg_match_all( $reg ,$string , $out  );
		if(isset($out[0][0]))
		{
			$string = str_replace($out[0][0],$str,$string);
			write_file(APPPATH.'config/hot_cats_config'.EXT, $string);
			$tx_msg="<li>热门分类修改成功.</li>";
			echo_msg($tx_msg,'','yes');
		}
		else
		{
			$tx_msg="<li>热门分类修改失败.</li>";
			echo_msg($tx_msg,'','no');
		}
	}
}
?>