<?php

if (!session_id()) {
	session_start();
}

require_once("config.php");

if (!isset($_POST['appToken'])) {
	$data = [
		'code' => 1000,
		'msg' => 'URL缺少appToken参数'
	];
	exit(json_encode($data));
}

if (!isset($_POST['activityID'])) {
	$data = [
		'code' => 1001,
		'msg' => 'URL缺少activityID参数'
	];
	exit(json_encode($data));
}

$appToken = $_POST['appToken'];
$activityID = $_POST['activityID'];

$params = array();
$params['token'] = $appToken;

$ch = curl_init();

$header = array();
$header[] = 'Content-Type: application/json;charset=UTF-8';
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

$data = $params;
if (is_array($params) && count($params) > 0) {
	$data = http_build_query($params);
}
$url = stripos(USER_API, '?') ? USER_API . '&' . $data : USER_API . '?' . $data;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($ch);

curl_close($ch);

$result = json_decode($result, true);

if(ENABLE_TEST == 1 && SKIP_USER_API == 1)
{
	$result = [
		"code" => 200,
		"data" => [
			"userNumber" => "11197381_xh",
			"userName" => "毛清艳",
			"userId" => 25592,
			"umNo" => "E00011197381"
		]
	];
}
else if ($result['code'] != 200) {
	$data = [
		'code' => $result['code'],
		'msg' => $result['msg']
	];
	exit(json_encode($data));
}

$config = [
	'token' => session_id(),
	'tips' => '',
	'activityName' => '',
	'lotteryItems' => [],
	'lotteryPrize' => [],
	'questions' => []
];


$dbLink = new mysqli(DB_HOST, DB_USER, DB_PWD, DB_NAME, DB_PORT);
if ($dbLink->connect_error) {
	if (isset($_GET["showerror"])) {
		die("连接失败：" . $dbLink->connect_error);
	}
}

//获取活动名称和领奖提示
$sqlConfig = "SELECT `activity_name`, `activity_tips`, `bg_img`, `title_img` FROM `pingan_activity_list` WHERE `id` = $activityID";
$configResult = $dbLink->query($sqlConfig);
if ($configResult == false) {
	$data = [
		'code' => 1002,
		'msg' => '活动不存在'
	];
	exit(json_encode($data));
}
$configData = $configResult->fetch_assoc();
$configResult->free();
if (count($configData) > 0) {
	$config['tips'] = $configData['activity_tips'];
	$config['activityName'] = $configData['activity_name'];
	$config['bg_img'] = $configData['bg_img'] ? (URL_FOR_SAVE_PATH . $configData['bg_img']) : null;
	$config['title_img'] = $configData['title_img'] ? (URL_FOR_SAVE_PATH . $configData['title_img']) : null;
}

//获取奖品列表
$prizeSql = "SELECT `order`, `prize_name`, `prize_type`, `prize_img` FROM `pingan_prize_config` WHERE `activity_id` = $activityID ORDER BY `order` ASC";
//echo $prizeSql;
$prizeResult = $dbLink->query($prizeSql);
while ($prizeData = $prizeResult->fetch_assoc()) {
	$config['lotteryPrize'][$prizeData['order']] = $prizeData['prize_name'];
	$config['lotteryItems'][$prizeData['order']] = $prizeData['prize_type'];
	$config['lotteryImgs'][$prizeData['order']] = $prizeData['prize_img'] ? (URL_FOR_SAVE_PATH . $prizeData['prize_img']) : null;
}
$prizeResult->free();

//获取问题列表
$questionSql = "SELECT `id`, `type`, `question`, `options` FROM `pingan_question_list` WHERE `activity_id` = $activityID ORDER BY `order` ASC";
//echo $questionSql;
$questionResult = $dbLink->query($questionSql);
while ($questionData = $questionResult->fetch_assoc()) {
	$config['questions'][] = array(
		'id' => $questionData['id'],
		'type' => $questionData['type'],
		'question' => $questionData['question'],
		'options' => $questionData['options'] == null ? null : json_decode($questionData['options'], true)
	);
}
$questionResult->free();

//获取玩家信息
$userID = $result['data']['userId'];
$sql = "SELECT `user_id`, `user_name`, `user_number`, `options`, `custom_input`, `status`, `prize`, `update_time` FROM `pingan_user_info` WHERE `user_id` = $userID AND `activity_id` = $activityID";
//echo $sql;
$queryResult = $dbLink->query($sql);
$rows = $queryResult->fetch_assoc();
$queryResult->free();

if ($rows == false || count($rows) == 0) {
	$insertSql = 'INSERT INTO `pingan_user_info` (`activity_id`,`user_id`, `user_number`, `user_name`, `um`) VALUES(?, ?, ?, ?, ?)';
	if (!($stmt = $dbLink->prepare($insertSql))) {
		echo "Prepare failed: (" . $dbLink->errno . ") " . $dbLink->error;
	}
	$stmt->bind_param("iisss", $activityID, $userID, $result['data']['userNumber'], $result['data']['userName'], $result['data']['umNo']);
	$stmt->execute();

	$queryResult = $dbLink->query($sql);
	$rows = $queryResult->fetch_assoc();
	$queryResult->free();
	$data = [
		'code' => 200,
		'data' => array_merge($rows, $config)
	];
	echo json_encode($data);
} else {
	$data = [
		'code' => 200,
		'data' => array_merge($rows, $config)
	];
	echo json_encode($data);
}

$_SESSION['userID'] = $userID;
$dbLink->close();
