<?
// クラス、設定読み込み
//添加或者删除用户的收藏记录
require_once ("../user_include.inc");

ErrorLogger::doOutput("Koala...ajax_operate_favorite.php....Start.", 0);

$action_type = ParamUtil::getRequestString("action_type");//delete/add
$data_type = ParamUtil::getRequestString("data_type");//word/article
$data_id = ParamUtil::getRequestNumber("data_id", 0);


ErrorLogger::doOutput("Koala...ajax_operate_favorite.php....action_type=" . $action_type, 0);
ErrorLogger::doOutput("Koala...ajax_operate_favorite.php....data_type=" . $data_type, 0);
ErrorLogger::doOutput("Koala...ajax_operate_favorite.php....data_id=" . $data_id, 0);

//参数错误
if(empty($action_type) || ($action_type!="delete" && $action_type!="add")) {
	responseNG("NG_PARAM", "参数错误！");
}
if(empty($data_type) || ($data_type!="word" && $data_type!="article")) {
	responseNG("NG_PARAM", "参数错误！");
}
if(empty($data_id) || $data_id==0) {
	responseNG("NG_PARAM", "参数错误！");
}

//判断用户登陆状态
$ta = new TemplateAction();
if(!$ta->isLogin()) {
	responseNG("NG_LOGIN", "未登录！");
}

//检查数据是否存在
if($action_type == "add" && $data_type == "word") {
	$word_dat = WordDat::getById($data_id);
	if(empty($word_dat)) {
		responseNG("NG_PARAM", "参数错误！");
	}
}
if($action_type == "add" && $data_type == "article") {
	$article_dat = ArticleDat::getById($data_id);
	if(empty($article_dat)) {
		responseNG("NG_PARAM", "参数错误！");
	}
}

$user_id = $ta->user->id;
//是否重复登陆
if($action_type == "add") {
	$param = array();
	$param["user_id"] = $user_id;
	$param["data_type"] = $data_type;
	$param["data_id"] = $data_id;
	$param["delete_flg"] = false;
	$tmp_favorite_count = UserFavoriteDat::getListCount($param);
	if ($tmp_favorite_count > 0) {
		responseNG("NG_REPEAT", "重复添加！");
	}
}

//数据操作
$sql = "";
if($action_type == "add") {
	$sql = "INSERT INTO user_favorite_dat(user_id, data_type, data_id) values('{$user_id}', '{$data_type}', '{$data_id}')";
}
if($action_type == "delete") {
	$sql = "DELETE FROM user_favorite_dat WHERE delete_flg=false and user_id='{$user_id}' and data_type='{$data_type}' and data_id='{$data_id}'";
}

ErrorLogger::doOutput("Koala...ajax_operate_favorite.php....sql=" . $sql, 0);

$db = &KoalaDBManager::getInstance();
$db->executeQuery($sql);

responseOK("操作成功！");

function responseNG($status, $message) {
	$result = array("status"=>$status, "message"=>$message);
	print json_encode($result);
	exit;
}
function responseOK($message) {
	$result = array("status"=>"OK", "message"=>$message);
	print json_encode($result);
	exit;
}

?>