<?php
session_id($_POST['token']);
session_start();
require_once("config.php");


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

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

$dbLink = new mysqli(DB_HOST, DB_USER, DB_PWD, DB_NAME, DB_PORT);

$activityID = $_POST['activityID'];
$answers = json_decode($_POST['answers'], true);
$user_id = $_SESSION['userID'];

$rightAnswer = [];

//获取问题列表
$questionSql = "SELECT `id`, `answer` FROM `pingan_question_list` WHERE `activity_id` = $activityID ORDER BY `order` ASC";
//echo $questionSql;
$questionResult = $dbLink->query($questionSql);
$questionCnt = 0;
while ($questionData = $questionResult->fetch_assoc()) {
	$questionCnt++;
	if (isset($questionData['answer']) && $questionData['answer'] != null) {
		$tmpArr = json_decode($questionData['answer'], true);
		$rightAnswer[$questionData['id']] = implode(',', $tmpArr);
	}
}
$questionResult->free();

$selections = "";
$customInput = "";
$rightCount = 0;
for ($i = 1; $i <= count($answers); ++$i) {
	$obj = $answers[$i];
	$questionID = $obj['id'];
	if (isset($obj['options'])) {
		$an = implode(',', $obj['options']);
		$selections .= $an;
		if (strcmp($rightAnswer[$questionID], $an) == 0) {
			$rightCount++;
		}
		$selections .= ';';
	} else if (isset($obj['input'])) {
		$customInput = $obj['input'];
		if (mb_strlen($customInput, "utf-8") > 0) {
			$rightCount++;
		}
	}
}

$updateSql = 'UPDATE `pingan_user_info` SET `options` = ?, `custom_input` = ? WHERE `user_id` = ? AND `activity_id` = ?';
if (!($stmt = $dbLink->prepare($updateSql))) {
	echo "Prepare failed: (" . $dbLink->errno . ") " . $dbLink->error;
}
$stmt->bind_param("ssii", $selections, $customInput, $user_id, $activityID);
$stmt->execute();

$_SESSION['hasAnswerRight_' . $activityID] = ($rightCount == $questionCnt) ? 1 : 0;
$data = [
	'code' => 200,
	'data' => [
		'lottery' => ($rightCount == $questionCnt),
		'rightCount' => $rightCount
	]
];
echo json_encode($data);
