<?php 

/**
 * 名称：系统配置控制器
 * 作者：荷塘月色
 * 邮箱：kujiw@qq.com
 * 说明：
 */

namespace Admin\Controller;
class ConfigController extends CommonController {

	public function index(){
		if (IS_POST) {
			$this -> ajaxReturn($this -> getData());
		}elseif (IS_GET) {
			$this -> display(I('tpl'));
		}
	}

	public function add(){
		if (IS_GET) {
			$this -> display();
		}elseif (IS_POST) {
			$this -> ebAdd();
		}
	}

	public function save(){
		if (IS_GET) {
			$this -> assign(M('Config') -> find(I('id','','intval')));
			$this -> display(I('tpl'));
		}elseif (IS_POST) {
			if (I('acttype') != 'part') {
				$data = $this -> ebSave();
			}else{
				$data = I('data');
				foreach ($data as $key => $value) {
					M('Config') -> where(array('id'=>array('eq',$key))) -> setField('value',$value);
				}
				$this -> success('修改成功');
			}
		}
	}

	// 修改子分类分类id
	public function _after_save(){
		if (IS_POST) {
			if (I('acttype') != 'part') {
				$category_id = I('category_id',-1,'intval');
				if ($category_id) {
					$datas = M('Config') -> getField('id,pid,sort',true);
					$subid = subtreeid($datas,I('id','','intval'));
					if (count($subid)) {
						M('Config') -> where(array('id'=>array('in',$subid))) -> setField('category_id',$category_id);
					}
				}
			}
		}
	}
	
	public function delete(){
		if (IS_POST) {
			$this -> ebDelete();
		}
	}

	public function status(){
		if (IS_POST) {
			$this -> ebStatus();
		}
	}

	public function build(){
		if (IS_POST) {
			$config = read_config();
			// 生成配置文件
			foreach ($config as $key => $value) {
				ksort($value);
				$str = "<?php 

/**
 * 名称：内容分类控制器
 * 作者：荷塘月色
 * 邮箱：kujiw@qq.com
 * 说明：
 */
 \n\r//配置文件由系统自动生成，如非必要请在后台修改！\n\rreturn ".var_export($value,true).';';
				$str = htmlspecialchars_decode($str);
				$patterns  = array(
					'/(\{\{)(.*)(\}\})/U',
					'/(=> \'\'\.)/U',
					'/(\.\'\',)(\r|\n)/U',
					'/(\.\'\'\.)/U',
					);
				$replace  = array(
					'\'.\2.\'',
					'=> ',
					',\2',
					'.',
					);
				$str = preg_replace($patterns, $replace, $str);
				$str = str_replace(array('[\\\'','\\\']'), array('[\'','\']'), $str);
				\Think\Storage::put(APP_PATH.$key.'/Conf/config.php',$str);
			}
			deldir(RUNTIME_PATH);
			$this -> success('成功更新系统配置！','',true);
		}
	}
}