<?php
// 支付的时候，创建订单及返回结果
require_once ("../user_include.inc");

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

// 参数取得
$course_id = ParamUtil::getRequestString("course_id");
$price = ParamUtil::getRequestNumber("price");
$pay_type = ParamUtil::getRequestString("pay_type","ZFB");
$course_mst = CourseMst::getById($course_id);
if ($course_mst == null) {
	response("ERROR", "课程不存在！");
}

if (!$course_mst->is_valid) {
	response("ERROR", "产品已下架！");
}

if ($course_mst->price != $price) {
	response("ERROR", "价格错误！");
}

//删除该用户所有未支付订单
$sql = "update user_buy_couse_dat set delete_flg=true where status='WAITING' and user_id='{$ta->user->id}'";
$db = &KoalaDBManager::getInstance();
$db->executeQuery($sql);

// 创建订单
$user_buy_couse_dat = new UserBuyCouseDat();
$user_buy_couse_dat->user_id = $ta->user->id;
$user_buy_couse_dat->pay_type = $pay_type;
$user_buy_couse_dat->trade_no = 'course'. $course_mst->id . strtolower(PasswordMaker::humanChars(6)) . date("YmdHis");
$user_buy_couse_dat->course_id = $course_mst->id;
$user_buy_couse_dat->numbers = 1;
$user_buy_couse_dat->price = $course_mst->price;
$user_buy_couse_dat->status = "WAITING";
$user_buy_couse_dat->save();

$response = array(
		"WIDout_pay_type"=>$pay_type,
		"WIDout_trade_no"=>$user_buy_couse_dat->trade_no,
		"WIDsubject"=>$course_mst->title,
		"WIDtotal_amount"=>$user_buy_couse_dat->numbers * $course_mst->price,
		"WIDshow_url"=>"http://" . HOST_NAME . "/alipay_return.php?act=cancel",
		"WIDbody"=>$course_mst->title
);
response("OK", $response);

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

?>

