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

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

//代金券ID
$coupon_id = ParamUtil::getRequestNumber("coupon_id", 0);

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

//代金券是否存在
$coupon_dat = Coupon::getById($coupon_id);
if(empty($coupon_dat)) {
	responseNG("数据错误！");
}

//积分整合性判断
//获取用户数据
$point_left = 0;
$param = array();
$param["user_id"] = $ta->user->id;
$param["status"] = "SUCCESS";
$param["delete_flg"] = false;
$user_point_list = UserPointLog::getList($param, "id", "desc", 0, 1);
if(!empty($user_point_list)) {
	$point_left = $user_point_list[0]->point_left;
}
ErrorLogger::doOutput("Koala...ajax_user_exchange_coupon.php....point1=" . $ta->user->point, 0);
ErrorLogger::doOutput("Koala...ajax_user_exchange_coupon.php....point2=" . $point_left, 0);
if($ta->user->point != $point_left) {
	responseNG("数据错误2！");
}

if($point_left < $coupon_dat->point) {
	responseNG("积分不足！");
}

//开始兑换
//添加一条新的积分记录记录
$minus_point = $coupon_dat->point;
$user_point_log = new UserPointLog();
$user_point_log->user_id = $ta->user->id;
$user_point_log->action_type = 5;//兑换代金券
$user_point_log->point = (-1)*$minus_point;
$user_point_log->point_left = $point_left - $minus_point;
$user_point_log->status = "SUCCESS";
$user_point_log->save();

//添加代金券
$dead_time = time() + ($coupon_dat->valid_days)*24*3600;

$user_coupon_dat = new UserCouponDat();
$user_coupon_dat->user_id = $ta->user->id;
$user_coupon_dat->coupon_id = $coupon_id;
$user_coupon_dat->coupon_count = 1;
$user_coupon_dat->dead_time = date('y-m-d',$dead_time) . " 23:59:59";
$user_coupon_dat->transfer_count = 0;
$user_coupon_dat->save();

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

ErrorLogger::doOutput("Koala...ajax_user_exchange_coupon.php....point_left=" . $point_left, 0);
ErrorLogger::doOutput("Koala...ajax_user_exchange_coupon.php....minus_point=" . $minus_point, 0);

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

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

responseOK("兑换成功！");


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;
}
?>