<?php
if(!defined('MOD'))  die("access die");
if($admin_info['groupid'] > 2 ) qbase::purviewCheckDie();
$action = $_GET[action];
qbase::checkAction( $action);
$action = $_GET['action'];
switch($action){
	case 'manage':
		$data = qdb::fetchAll("select * from ".TABLEPRE."module order by pid asc, id asc");
	break;

	case 'ordering':
		checkAdminReferer();
		$ordering = $_POST['ordering'];
		$id = intval($_GET['id']);
		if(is_array($ordering)) foreach($ordering as $key=>$val){
			$val = intval($val);
			qdb::query("update ".TABLEPRE."extend set ordering = '{$val}' where eid = '{$key}' ");
		}
		qbase::showmsg("操作成功", 'default', 'system.php?sys=extend&action=extend_manage&id=' . $id);
	break;

	case 'add':
		if($_POST['update']){
			$name = trim($_POST['name']);
			$pid = intval($_POST['pid']);
			if(empty($name)) qbase::showmsg("输入了错误信息", 'default', 'system.php?sys=extend&action=add');
			$check = qdb::queryAlone("select count(*) as num from ".TABLEPRE."module where name = '{$name}' ");
			if($check > 0) qbase::showmsg("出错了，该模型名称已经被占用了", 'default', 'system.php?sys=extend&action=add');
			$param = qdb::queryFirst("select * from ".TABLEPRE."module where id = {$pid} ");
			if(empty($param) || $param['is_hidden'] > 0){
				qbase::showmsg("输入了错误信息", 'default', 'system.php?sys=extend&action=add');
			}
			$param['pid'] = $pid;
			$param['is_hidden'] = 0;
			$param['name'] = $name;
			$param['appname'] = trim($_POST['appname']);
			unset($param['id']);
			qdb::query(qbase::createSql(TABLEPRE.'module', $param));
			commonCache();
			qbase::showmsg("新模型添加成功", 'default', 'system.php?sys=extend&action=manage');
		}else{
			$data = qdb::fetchAll("select * from ".TABLEPRE."module where pid = 0 and is_hidden = 0");
		}
	break;

	case 'modify':
		$id = intval($_GET['id']);
		$item = qdb::queryFirst("select * from  ".TABLEPRE."module where id = {$id}  ");
		if(empty($item)) qbase::showmsg("bad request");
		if($_POST['update']){
			$name = trim($_POST['name']);
			if(empty($name)) qbase::showmsg("输入了错误信息", 'default', 'system.php?sys=extend&action=modify&id=' . $id);
			$check = qdb::queryAlone("select count(*) as num from ".TABLEPRE."module where name = '{$name}' and id != '{$id}' ");
			if($check > 0) qbase::showmsg("出错了，该模型名称已经被占用了", 'default', 'system.php?sys=extend&action=modify&id=' . $id);
			$param = array();
			$param['name'] = $name;
			$param['appname'] = trim($_POST['appname']);

			qdb::query(qbase::createSql(TABLEPRE.'module', $param, "update") . " where id = '{$id}' ");
			commonCache();
			qbase::showmsg("新模型添加成功", 'default', 'system.php?sys=extend&action=manage');
		}else{
			
		}
	break;

	case 'delete':
		checkAdminReferer();
		$id = intval($_GET['id']);
		$check = qdb::queryAlone("select count(*) as num from ".TABLEPRE."channel where channelselect = '{$id}' ");
		if($check > 0) qbase::showmsg("出错了，请先删除该模型下的相关频道", 'default', 'system.php?sys=extend&action=manage');
		$param = qdb::queryFirst("select * from ".TABLEPRE."module where id = {$id} ");
		if($param['pid'] == 0 || $param['is_hidden'] > 0) qbase::showmsg("error request");
		qdb::query("delete from ".TABLEPRE."module where id = '{$id}' and pid > 0");
		qdb::query("delete from ".TABLEPRE."extend where id = '{$id}' ");
		commonCache();
		qbase::showmsg("请求成功", 'default', 'system.php?sys=extend&action=manage');
	break;

	case 'extend_manage':
		$id = intval($_GET['id']);
		$param = qdb::queryFirst("select * from ".TABLEPRE."module where id = {$id} ");
		if(empty($param)) qbase::showmsg("提交了错误的请求", 'default', 'system.php?sys=extend&action=manage');
		$data = qdb::fetchAll("select * from ".TABLEPRE."extend where id = '{$id}' order by ordering asc");
	break;

	case 'extend_delete':
		checkAdminReferer();
		$eid = intval($_GET['eid']);
		$param = qdb::queryFirst("select * from ".TABLEPRE."extend where eid = {$eid} ");
		if(empty($param)) qbase::showmsg("提交了错误的请求", 'default', 'system.php?sys=extend&action=manage');
		qdb::query("delete from ".TABLEPRE."extend where eid = {$eid} ");
		$tableName = getExtendTable($param['id']);
		if(checkTableExists($tableName)){
			if(checkFieldExists($tableName, "ext_{$param['ext']}")) qdb::query("alter table {$tableName} drop ext_{$param['ext']}");
			$num = qdb::queryAlone("select count(*) from ".TABLEPRE."extend where id = {$param['id']} ");
			if($num == 0) qdb::query("drop table {$tableName}");
		}
		commonCache();
		qbase::showmsg("请求成功", 'default', "system.php?sys=extend&action=extend_manage&id={$param['id']}");
	break;

	case 'extend_add':
		$eid = intval($_GET['eid']);
		if($eid > 0){
			$param = qdb::queryFirst("select * from ".TABLEPRE."extend where eid = {$eid} ");
			if(empty($param)) qbase::showmsg("提交了错误的请求", 'default', 'system.php?sys=extend&action=manage');
			$param['data'] = implode("\n", unserialize($param['data']));
		}else{
			$param['id'] = intval($_GET['id']);
			$param['word_num'] = 250;
		}

		if($_POST['update']){
			$param = $_POST['param'];
			$id = intval($param['id']);
			if(empty($param['name']) || empty($param['ext'])) qbase::showmsg("出错了，必须填写相应的信息");
			if($param['type'] == 'input') $param['data'] = '';
			$temp = explode("\n", $param['data']);
			$data = array();
			foreach($temp as $val){
				$val = trim($val);
				if(strpos($val, ',') !== false) continue;
				if(empty($val)) continue;
				$data[] = $val;
			}
			$data = array_unique($data);
			$param['data'] = addslashes(serialize(qbase::sstripslashes($data)));
			$param['need'] = intval($param['need']);
			$param['word_num'] = intval($param['word_num']) ? intval($param['word_num']) : 250;
			$param['word'] = trim($param['word']);
			$param['filter'] = trim($param['filter']);
			$param['ordering'] = intval($param['ordering']);

			$temp = array();
			foreach($data as $val){
				$temp[] = "'" . $val . "'";
			}

			switch($param['type']){
				case 'input':
					$sql = " varchar({$param['word_num']}) not null default '{$param['word']}' ";
				break;

				case 'map':
					$sql = " varchar(25) not null default '{$param['word']}' ";
				break;

				case 'date':
					$sql = " char(10) not null default ''";
				break;
				
				case 'textarea':
					if($param['word_num'] < 255){
						$sql = " varchar({$param['word_num']}) not null default '{$param['word']}' ";
					}else{
						$sql = " text not null ";
					}
				break;	

				case 'radio':
				case 'select':
					if(!$param['word'] || !in_array($param['word'], $data)){
						qbase::showmsg("默认值错误，默认值必须是扩展选项中的一个值");
					}
					$sql = " enum(" . implode(',', $temp) . ") not null default '{$param['word']}' ";
				break;
				
				case 'checkbox':
					if($param['word'] && !in_array($param['word'], $data)){
						qbase::showmsg("默认值错误，默认值必须是扩展选项中的一个值");
					}else{
						$param['word'] = '';
						$temp = array_unshift($param['word'], $temp);
					}
					$sql = " set(" . implode(',', $temp) . ") not null default '{$param['word']}' ";
				break;
				
				case 'html':
					$sql = " text not null ";
				break;
				
				default:
					qbase::showmsg("error request", 'default', 'system.php?sys=extend&action=manage');
				break;
			}
			
			if($eid > 0){
				$temp = $param;
				unset($temp['id']);
				unset($temp['ext']);
				qdb::query(qbase::createSql(TABLEPRE.'extend', $temp, 'update') . " where eid = '{$eid}' ");
			}else{
				$num = qdb::queryAlone("select count(*) as num from ".TABLEPRE."extend where id = '{$param['id']}' and ext = '{$param['ext']}' ");
				if($num > 0) qbase::showmsg("出错了，在同一模型中，不能出现相同的扩展名", 'default', 'system.php?sys=extend&action=manage');
				$param['eid'] = qdb::query(qbase::createSql(TABLEPRE.'extend', $param, 'insert'), true);
			}
			
			/*更新table*/
			$tableName = getExtendTable($param['id']);

			if(!checkTableExists($tableName)){
				$create_sql = "CREATE TABLE IF NOT EXISTS {$tableName} (
					`channelid` int(10) unsigned NOT NULL default '0',
					`id` int(10) unsigned NOT NULL default '0',
					KEY `id` (`channelid`,`id`)
				) ENGINE=MyISAM";
				qdb::query($create_sql);
			}
			

			if(!checkFieldExists($tableName, "ext_{$param['ext']}")){
				qdb::query("alter table {$tableName} add ext_{$param['ext']} {$sql}");
			}else{
				qdb::query("alter table {$tableName} modify ext_{$param['ext']} {$sql}");
			}
			commonCache();
			$data = array('status'=>200, 'data'=>'system.php?sys=extend&action=extend_manage&id=' . $id);
			echo qbase::xmlPrint(qbase::jsonencode($data));
			exit();
		}
	break;
}

function checkTableExists($name){
	$temp = qdb::fetchAll("show tables");
	$tables = array();
	foreach($temp as $val){
		$tables[] = array_shift($val);
	}
	return in_array($name, $tables);
}

function checkFieldExists($tableName, $name){
	$temp = qdb::fetchAll("show fields from $tableName");
	$fields = array();
	foreach($temp as $val){
		$fields[] = array_shift($val);
	}	
	return in_array($name ,$fields);
}

function getExtendTable($mid){
	return TABLEPRE . "extend_data_" . $mid;
}

function deleteCategoryCache(){
	$data = qdb::fetchAll("select cid from ".TABLEPRE."acategory");
	foreach($data as $val){
		cache::delete('cid_' . $val['cid']);
	}
}
include qbase::template($path . 'extend');
?>
