<?php
// 提交用户签到结果
require_once ("../user_include.inc");

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

//文章ID
$article_id = ParamUtil::getRequestNumber("article_id", 0);

$ta = new TemplateAction();
if(!$ta->isLogin()) {
	responseNG("请先登录！");
}

//判断当天是否已经签到
$param = array();
$param["object_date"] = date("Y-m-d");
$param["user_id"] = $ta->user->id;
$param["delete_flg"] = false;
$sign_count = UserSignDat::getListCount($param);
if($sign_count >= 1) {
	responseNG("今天已经签到，请明天再来！");
}



//用户加点
$point_left = 0;
$add_point = rand(1, 10);

ErrorLogger::doOutput("Koala...ajax_user_sign.php....point_left=" . $point_left, 0);
ErrorLogger::doOutput("Koala...ajax_user_sign.php....add_point=" . $add_point, 0);

//签到操作
$user_sign_dat = new UserSignDat();
$user_sign_dat->object_date = date("Y-m-d");
$user_sign_dat->user_id = $ta->user->id;
$user_sign_dat->point = $add_point;
$user_sign_dat->article_id = $article_id;
$user_sign_dat->save();

//查找最后一条记录
$param = array();
$param["user_id"] = $ta->user->id;
$last_log_list = UserPointLog::getList($param, "id", "desc", 0, 1);
if(!empty($last_log_list)) {
	$point_left = $last_log_list[0]->point_left;
}
//添加一条新的记录
$user_point_log = new UserPointLog();
$user_point_log->user_id = $ta->user->id;
$user_point_log->action_type = 2;//签到
$user_point_log->point = $add_point;
$user_point_log->point_left = $point_left + $add_point;
$user_point_log->status = "SUCCESS";
$user_point_log->save();

//更新用户表的point字段值
$ta->user->point = $user_point_log->point_left;
$ta->user->save();

ErrorLogger::doOutput("Koala...ajax_user_sign.php....End.", 0);

responseOK("签到成功！获得" . $add_point . "积分！");


function responseNG($message) {
	$result = array("status"=>"NG", "message"=>$message);
	header("Access-Control-Allow-Origin: *");
	print json_encode($result);
	exit;
}
function responseOK($message) {
	$result = array("status"=>"OK", "message"=>$message);
	header("Access-Control-Allow-Origin: *");
	print json_encode($result);
	exit;
}
?>