<?php

// 使用代金券
require_once ("../user_include.inc");

$user_coupon_dat_id = ParamUtil::getRequestNumber("user_coupon_dat_id", 0);
$coupon_id = ParamUtil::getRequestNumber("coupon_id", 0);
ErrorLogger::doOutput("Koala...ajax_user_use_coupon.php....Start.", 0);

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

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

$user_coupon_dat = UserCouponDat::getById($user_coupon_dat_id);
if(empty($user_coupon_dat)) {
	responseNG("参数错误！");
}
if($user_coupon_dat->user_id != $ta->user->id || $user_coupon_dat->coupon_id != $coupon_id){
	responseNG("参数错误！");
}

if($user_coupon_dat->coupon_count <= 0) {
	responseNG("代金券数量不足！");
}

//有效期
$dead_time = $user_coupon_dat->dead_time;
if(date("Y-m-d H:i:s") > $dead_time) {
	responseNG("已过有效期！");
}

//一个代金券只能使用一次
$param = array();
$param["user_id"] = $ta->user->id;
$param["coupon_id"] = $coupon_id;
$param["status_NOT"] = "BACK";
$param["delete_flg"] = false;
$user_use_coupon_list = UserUseCouponDat::getList($param);
if(!empty($user_use_coupon_list)) {
	responseNG("每次只能使用一张代金券！");
}

//使用代金券
$user_coupon_dat->coupon_count = 0;
$user_coupon_dat->save();

$user_use_coupon_dat = new UserUseCouponDat();
$user_use_coupon_dat->user_id = $ta->user->id;
$user_use_coupon_dat->coupon_id = $coupon_id;
$user_use_coupon_dat->status = "APPLY";
$user_use_coupon_dat->save();

ErrorLogger::doOutput("Koala...ajax_user_use_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;
}
?>