<?php

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

if(!isset($_SESSION['userID']) || !isset($_POST['activityID']))
{
	exit("{}");
}

$userID = $_SESSION['userID'];
$activityID = $_POST['activityID']; 

$sessionKey = 'hasAnswerRight_' . $activityID;

$_SESSION[$sessionKey] = 1; //忽略掉答题, 直接进入抽奖

if(!isset($_SESSION[$sessionKey]))
{
	exit("{}");
}
$canRoll = (intval($_SESSION[$sessionKey]) == 1);
if(!$canRoll)
{
	exit("{}");
}

if(!ENABLE_TEST)
{
	unset($_SESSION[$sessionKey]);
}
//$userID = 25586;
//$activityID = 15;
$dbLink = new mysqli(DB_HOST, DB_USER, DB_PWD, DB_NAME, DB_PORT);

$sql = "SELECT `status`, `user_id` FROM `pingan_user_info` WHERE `user_id` = $userID AND `activity_id` = $activityID";
$queryResult = $dbLink->query($sql);
$rows = $queryResult->fetch_assoc();

$queryResult->free();

if($rows['status'] > 0)
{
	exit("{}");
}

$sql = "SELECT `id`, `order`,`prize_name`, `prize_rate`, `sum`, `cur` FROM `pingan_prize_config` WHERE `activity_id` = $activityID ORDER BY `order` ASC";
$queryResult = $dbLink->query($sql);

$rollRate = [];
while($row = $queryResult->fetch_assoc()){
	$rollRate[$row['order']] = [$row['prize_name'], $row['prize_rate'], $row['sum'], $row['cur'], $row['id']];
}
$queryResult->free();

$rand = mt_rand(1, 10000);
//echo "rand1 = " . $rand . "<br/>";
$pack_id = 0;
$prizeID = 0;
$rate = 0;
$count = 0;
for ($i = 1; $i <= count($rollRate); $i++) {
	$rate += $rollRate[$i][1] * 100;
	$sum = $rollRate[$i][2];
	$cur = $rollRate[$i][3];

	//echo "compare i = " . $i . ", itemRate = " . $rollRate[$i][1] . ",totalRate = " . $rate . "<br/>";
	if ($rate >= $rand) {
		if($cur + 1 <= $sum)
		{
		  $pack_id = $i;
		  $prizeID = $rollRate[$i][4];
		  //echo "packID = " . $pack_id . "<br/>";
		  $msg = $rollRate[$i][0];
		  break;
		}
		else
		{
			//本奖品无剩余，重新抽
			$count++;
			$rate = 0;
			$i = 1;
			$rand = mt_rand(1, 10000);
			
			//echo "reroll = " . $rand . "<br/>";
		}
	}
	
	if($count > 100)
	{
		//echo "max count break <br/>";
		break;
	}
}

if($pack_id > 0)
{
	$updateSQL = 'UPDATE `pingan_user_info` SET `status` = ?, `prize` = ? WHERE `user_id` = ? AND `activity_id` = ?';
	if (!($stmt = $dbLink->prepare($updateSQL))) {
		echo "Prepare failed: (" . $dbLink->errno . ") " . $dbLink->error;
	}
	$s = ENABLE_TEST ? 0 : 1;
	$stmt->bind_param("iiii", $s, $pack_id, $userID, $activityID);
	$stmt->execute();
	
	$updateSQL = 'UPDATE `pingan_prize_config` SET `cur` = `cur` + 1 WHERE `id` = ? AND `activity_id` = ?';
	if (!($stmt = $dbLink->prepare($updateSQL))) {
		echo "Prepare failed: (" . $dbLink->errno . ") " . $dbLink->error;
	}
	$stmt->bind_param("ii", $prizeID, $activityID);
	$stmt->execute();
	
	$data = [
		'code' => 200,
		'data' => [
			'id' => $pack_id,
			'name' => $msg
		]
	];
	exit(json_encode($data));
}

exit(json_encode(array("code"=>444)));


