<?php
define('IN_PHPQUAN', true);
require_once dirname(__FILE__) . '/include/common.php';
chkadmin('category');
//初始化act操作
$_REQUEST['act'] = $_REQUEST['act'] ? trim($_REQUEST['act']) : 'list' ;
switch ($_REQUEST['act'])
{
	case 'list':
		$cat = get_cat_list();
	    include tpl('list_category');
	break;
	case 'add':
        $cat = get_cat_list();
		$cats = $db->getAll("SELECT * from {$table}juan_cat");
		$maxorder = $db->getOne("SELECT MAX(catorder) FROM {$table}juan_cat");
		$maxorder = $maxorder + 1;
		$here = "添加券类型";
		$action = array('name'=>'券类型列表', 'href'=>'category.php?act=list');
	    include tpl('add_category');
	break;
	case 'insert':
		if(empty($_REQUEST[catname]))show("请填写分类名称");
		$len = strlen($_REQUEST[catname]);
		if($len < 2 || $len > 30)show("分类名必须在2个至30个字符之间");
		$catname     = trim($_REQUEST['catname']);
		$catorder    = intval($_REQUEST['catorder']);
		if(empty($catorder)) {
			$sql = "SELECT MAX(catorder) FROM {$table}juan_cat";
			$maxorder = $db->getOne($sql);
			$catorder = $maxorder + 1;
		}
		$sql = "INSERT INTO {$table}juan_cat (catname,catorder) VALUES ('$catname','$catorder')";
		$res = $db->query($sql);
		clear_caches('phpcache');
		admin_log("插入分类 $cataname 成功");
		show('添加分类成功','category.php?act=add');
	break;
	case 'edit':
	    $catid = intval($_REQUEST['catid']);
		$sql = "SELECT * FROM {$table}juan_cat WHERE catid = '$catid'";
		$cat = $db->getRow($sql);
		$sql  = "SELECT * FROM {$table}juan_cat";
	    $cats = $db->getAll($sql);
		include tpl('edit_category');
	break;
	case 'update':
		if(empty($_REQUEST[catname]))show("请填写分类名称");
		$len = strlen($_REQUEST[catname]);
		if($len < 2 || $len > 30)show("分类名必须在2个至30个字符之间");
        
		$catid       = intval($_REQUEST['catid']);
		$catname     = trim($_REQUEST['catname']);
		$catorder    = intval($_REQUEST['catorder']);
		$sql = "UPDATE {$table}juan_cat SET catname='$catname',catorder='$catorder' WHERE catid = '$catid'";
		$res = $db->query($sql);
		
		clear_caches('phpcache');
		admin_log("编辑分类 $catname 成功");
		$link = "category.php?act=list";
		show('编辑分类成功', $link);
	break;
	case 'delete':
		$catid = intval($_REQUEST['catid']);
		if(empty($catid))show('没有选择记录');
		
		$sql = "SELECT COUNT(*) FROM {$table}juan WHERE catid = '$catid' ";
		if($db->getOne($sql)>0)show('该分类下有券信息，无法删除');
		$sql = "DELETE FROM {$table}juan_cat WHERE catid='$catid'";
	    $db->query($sql);
		$sql = "select cusid from {$table}custom where catid='$catid' ";
		$cusids = $db->getRow($sql);
		$cusids = is_array($cusids) ? join(',',$cusids) : '';
		if($cusids) {
			$db->query("delete from {$table}cus_value where cusid in ($cusids)");
			$db->query("delete from {$table}custom where catid=$catid");
		}
		clear_caches('phpcache');
		admin_log("删除分类 $catid 成功");
		$link = 'category.php?act=list';
		show('删除分类成功', $link);
	break;
}
?>