<?php
// +----------------------------------------------------------------------
// | YZCMS <XueHen CMS>
// +----------------------------------------------------------------------
// | Copyright (c) http://www.xuehen.org
// +----------------------------------------------------------------------
// | Author XueHen <490860758@qq.com>
// +----------------------------------------------------------------------
namespace Admin\Controller;
define('TYPE','page');

class PageController extends BaseController {
	
	function edit(){
		$id = I('id');
		if(!$id){
			$this->error('无效的参数');
			exit;
		}
		$db = M('category');
		$re = $db->where(array('id'=>$id))->find();
		
		if($re){
			$this->assign('content',$re);
			$cat = $db->where(array('type'=>TYPE,'pid'=>0))->order('ord desc, id asc')->select();
		    $cat = getCatSon($cat);
			
			foreach($cat as $k=>$v){
				if($v['id'] == $id) unset($re[$k]);
			}
			$this->cat = $cat;
			$this->display();
		}else{
			$this->error('无效的参数');
		}
	}
	
	function editok(){
		if(IS_POST){
			if($_POST['name'] == ''){
				$this->error('名称不能为空');
				exit;
			}
		}else{
			$this->error('无效的访问');
			exit;
		}
		//验证URL
		if(I('url')){
			$re = checkUrl('category',I('url'));
			if($re && $re != I('id')){
				$this->error('别名有重复');
				exit;
			}
		}
		$db = M('category');
		//上级分类
		if(I('post.pid')){
			$db->where(array('id'=>I('post.pid')))->save(array('level'=>1));
		}
		$db->create();
		$rid = $db->save();
		if($rid){
			$this->success('修改成功！',U('index'));
		}else{
			$this->error('修改失败！');
		}	
	}
	function index(){
		$db = M('category');
		$cat = $db->where(array('type'=>TYPE,'pid'=>0))->order('ord desc, id asc')->select();
		$this->cat = getCatSon($cat);
		$this->display();
	}
	
	function add(){
		$db = M('category');
		$cat = $db->where(array('type'=>TYPE,'pid'=>0))->order('ord desc, id asc')->select();
		$this->cat = getCatSon($cat);
		$this->display();
	}
	
	function addok(){
		if(IS_POST){
			if($_POST['name'] == ''){
				$this->error('名称不能为空');
				exit;
			}
			if($_POST['url'] == ''){
				$this->error('别名不能为空');
				exit;
			}
		}else{
			$this->error('无效的访问');
			exit;
		}
		//验证URL
		if(I('url')){
			$re = checkUrl('category',I('url'));
			if($re){
				$this->error('别名有重复');
				exit;
			}
		}
		$db = M('category');
		//上级分类
		if(I('post.pid')){
			$db->where(array('id'=>I('post.pid')))->save(array('level'=>1));
		}
		$_POST['type'] = TYPE;
		$db->create();
		$rid = $db->add();
		if($rid){
			$this->success('添加成功！',U('index'));
		}else{
			$this->error('添加失败！');
		}
		
	}
	
	function delete(){
		$id = I('id');
		if(!$id){
			$this->error('无效的参数');
			exit;
		}
		$db = M('category');
		$rid = $db->where('id = '.I('id'))->delete();
		if($rid){
			$this->success('删除成功！',U('index'));
		}else{
			$this->error('删除失败!');
		}
		
	}
	
	
}