<?php
@header('Content-Type: application/json; charset=UTF-8');
include(dirname(__DIR__) . '/includes/common.php');
if($islogin!=1)exit("<script language='javascript'>window.location.href='./login.php';</script>");
$act=isset($_GET['act'])?daddslashes($_GET['act']):null;
switch($act){
case 'list':
	$numrows=$DB->getColumn("SELECT count(*) FROM pre_user_vip");
	$pagesize=isset($_GET['limit'])?intval($_GET['limit']):30;//每页显示数量
	if($pagesize>200)$pagesize=200;
	$pages=ceil($numrows/$pagesize);//总页数
	$page=isset($_GET['page'])?intval($_GET['page']):1;//当前页数
	$offset=isset($_GET['offset'])?intval($_GET['offset']):$pagesize*($page - 1);//SQL语句起始索引
	$i=1;
	$rows = [];
	$rs=$DB->query("SELECT * FROM `pre_user_vip` ORDER BY vip ASC LIMIT $offset,$pagesize");
	while($res = $rs->fetch(PDO::FETCH_ASSOC)){
		if($i == $numrows)$res['delete'] = 1;
		$rows[] = $res;
		$i++;
	}
	exit(json_encode(array('total'=>$numrows,'rows'=>$rows)));
break;
case 'edit':
	$id = intval($_POST['id']);
	$zt = intval($_POST['zt']);
	$type = daddslashes($_POST['type']);
	if($type == 'del'){
		$_del = [1,2,3,4,5];
		$row = $DB->getRow("SELECT * FROM pre_user_vip ORDER BY vip DESC LIMIT 1");
		if(in_array($row['vip'],$_del))exit('{"code":-1,"msg":"默认的等级不能删除"}');
		$sql = "DELETE FROM pre_user_vip WHERE id='{$row['id']}'";
	}else{
		exit('{"code":-1,"msg":"类型错误"}');
	}
	if($DB->exec($sql)){
		if($type == 'del'){
			$DB->exec("UPDATE `pre_user` SET vip='".($row['vip']-1)."' WHERE vip='{$row['vip']}'");
		}
		exit('{"code":1,"msg":"操作成功"}');
	}else{
		exit('{"code":-1,"msg":"操作失败"}');
	}
break;
case 'add':
	$id = intval($_POST['id']);
	$name = daddslashes($_POST['name']);
	$act = daddslashes($_POST['act']);
	unset($_POST['id']);
	unset($_POST['act']);
	$vip=$DB->getColumn("SELECT vip FROM pre_user_vip ORDER BY vip DESC");
	if($act == 'add'){
		$vip = intval($vip)==0?1:$vip+1;
		$_POST['vip'] = $vip;
		$skey = array();
		$value = array();
		foreach ($_POST as $k => $v) {
			$skey[] = '`'.$k.'`';
			$value[] = "'".$v."'";
		}
		if($DB->exec("INSERT INTO `pre_user_vip` (".implode(',',$skey).") VALUES (".implode(',',$value).")")){
			exit('{"code":1,"msg":"添加成功"}');
		}else{
			exit('{"code":-1,"msg":"添加失败'.$DB->error().'"}');
		}
	}

	if($act == 'edit'){
		$key = array();
		$data = array();
		foreach ($_POST as $k => $v) {
			$key[] = '`'.$k.'`=:'.$k;
			$data[':'.$k] = $v;
		}
		$sql = "UPDATE `pre_user_vip` SET ".implode(',',$key)." WHERE id='{$id}'";
		if($DB->exec($sql,$data)){
			exit('{"code":1,"msg":"修改成功"}');
		}else{
			exit('{"code":-1,"msg":"修改失败'.$DB->error().'"}');
		}
	}
	exit('{"code":-1,"msg":"未知类型"}');
case 'set':
	foreach($_POST as $k=>$v){
		$DB->query("REPLACE INTO pre_config SET v='".daddslashes($v)."',k='".$k."'");
	}
	exit('{"code":1,"msg":"修改成功"}');
break;
default:
	exit('{"code":-4,"msg":"No Act"}');
break;
}