<?php
include 'dbconn.php';
include 'func.php';

if (!isset($_SESSION['LoggedIn'.$session_app])) {
	echo '{"status":false, "message":"'.$lang['session-timeout'].'", "session":false}';	
	exit();
}

$data = array("setting_name","setting_value");
$data_length = count($data);
$result_return = true;
$result_valid_return = true;
$result_data;
$result_output = "{}";
$game_log_data = "{}";

if(!empty($_REQUEST['token']) && mysqli_real_escape_string($conn, $_REQUEST['token']) == $_SESSION['Token'])
{

	//members data
	$check_member_points = checkExistPoints($_SESSION['Member_ID'], $gameType);
	$member_point = $check_member_points[0]['member_point'];
	$member_chance = $check_member_points[0]['member_chance'];
	$member_score = $check_member_points[0]['member_score'];
	$last_member_point = $check_member_points[0]['member_point'];
	$last_member_chance = $check_member_points[0]['member_chance'];
	$last_member_score = $check_member_points[0]['member_score'];
	$win_point = 0;
	$debug_output = "";

	if($gameType == "luckywheels"){
		$setting_names = array("gameSettings","wheel_arr","wheelSecond_arr");
		$settings_json = '';
		$wheel_json = '';
		$wheel_inner_json = '';

		//load settings
		foreach ($setting_names as $value) {
			$stmt = $conn->prepare("SELECT setting_name, setting_value FROM $game_settings WHERE game_type = '$gameType' AND setting_status = 1 AND setting_name = '$value'");
			$stmt->execute();
			$stmt->store_result();
			$num_of_rows = $stmt->num_rows;
			$stmt -> bind_result($setting_name, $setting_value);
			$settings = [];
			while ($stmt->fetch()) {
				$settings[] = array(
					'setting_name' => $setting_name,
					'setting_value' => $setting_value
				);
			}
			$stmt->free_result();
			$stmt->close();

			if($num_of_rows > 0){
				if($settings_json == ''){
					$settings_json = json_decode($settings[0]['setting_value'], false);
				}else if($wheel_json == ''){
					$wheel_json = json_decode($settings[0]['setting_value'], false);
				}else{
					$wheel_inner_json = json_decode($settings[0]['setting_value'], false);
				}
			}else{
				$result_return = false;
			}
		}

		if($result_return){
			$wheel_count  = count($wheel_json);
			$wheel_second_count  = count($wheel_inner_json);
			$player_bet = 0;
			
			//generate result
			$wheel_result = mt_rand(0, $wheel_count-1);
			$wheel_second_result = mt_rand(0, $wheel_second_count-1);
			
			if($settings_json->enablePercentage){
				//generate percentage
				$percentage_array = [];
				$percentage_inner_array = [];

				$wheel_index = 0;
				foreach ($wheel_json as $value) {
					if(is_numeric($value->percent)){
						for ($i = 0; $i < $value->percent; $i++){
							array_push($percentage_array,$wheel_index);
						}
					}
					$wheel_index++;
				}

				$wheel_inner_index = 0;
				foreach ($wheel_inner_json as $value) {
					if(is_numeric($value->percent)){
						for ($i = 0; $i < $value->percent; $i++){
							array_push($percentage_inner_array,$wheel_inner_index);
						}
					}
					$wheel_inner_index++;
				}
				
				shuffle($percentage_array);
				shuffle($percentage_inner_array);

				$wheel_result = $percentage_array[0];
				$wheel_second_result = $percentage_inner_array[0];
			}

			//calculate
			if($settings_json->secondWheel){
				$win_point = $wheel_json[$wheel_result]->point * $wheel_inner_json[$wheel_second_result]->mutiply;
			}else{
				$win_point = $wheel_json[$wheel_result]->point;
			}

			if($settings_json->gamePlayType){
				if($member_chance > 0){
					$member_chance--;

					if($wheel_json[$wheel_result]->type == 1){
						//loss
						$member_point = 0;
					}else{
						//win or jackpot
						$member_point += $win_point;
					}
				}else{
					$result_valid_return = false;
				}
			}else{
				if(!empty($_REQUEST['result_data'])){
					$player_bet = mysqli_real_escape_string($conn, $_REQUEST['result_data']);
					$point_left = $member_point - $player_bet;
					if($point_left >= 0){
						$member_point -= $player_bet;

						$win_point = $win_point * $player_bet;
						if($wheel_json[$wheel_result]->type == 1){
							//loss
							$member_point = 0;
						}else{
							//win or jackpot
							$member_point += $win_point;
						}
					}else{
						$result_valid_return = false;
					}
				}else{
					$result_valid_return = false;
				}
			}

			$member_score = $member_point;
			$result_output = '{"fixedRotate":'.$wheel_result.', "fixedInnerRotate":'.$wheel_second_result.'}';
			$game_log_data = '{"type":"server", "status":"spin", "current":{"member_point":'.$last_member_point.', "member_chance":'.$last_member_chance.', "member_score":'.$last_member_score.'}, "update":{"member_point":'.$member_point.', "member_chance":'.$member_chance.', "member_score":'.$member_score.'}, "bet":'.$player_bet.', "win":'.$win_point.'}';
			//$debug_output = $player_bet.", ".$last_member_score.", ".$member_score.", ".$win_point;
		}
	}else if($gameType == "dicegame"){
		$setting_names = array("area_arr");
		$area_json = '';

		//retrieve data
		if(!empty($_REQUEST['result_data'])){
			$result_data = $_REQUEST['result_data'];
			$result_data = json_decode($result_data, false);
			
			$result_amount = [];
			foreach ($result_data as $value) {
				array_push($result_amount,$value->amount);
			}
		}else{
			$result_return = false;
			$result_valid_return = false;
		}

		//load settings
		foreach ($setting_names as $value) {
			$stmt = $conn->prepare("SELECT setting_name, setting_value FROM $game_settings WHERE game_type = '$gameType' AND setting_status = 1 AND setting_name = '$value'");
			$stmt->execute();
			$stmt->store_result();
			$num_of_rows = $stmt->num_rows;
			$stmt -> bind_result($setting_name, $setting_value);
			$settings = [];
			while ($stmt->fetch()) {
				$settings[] = array(
					'setting_name' => $setting_name,
					'setting_value' => $setting_value
				);
			}
			$stmt->free_result();
			$stmt->close();

			if($num_of_rows > 0){
				if($area_json == ''){
					$area_json = json_decode($settings[0]['setting_value'], false);
				}
			}else{
				$result_return = false;
			}
		}

		if($result_return){
			//generate result
			$dice_result = [mt_rand(1,6),mt_rand(1,6),mt_rand(1,6)];
			$player_bet = 0;
			$player_bet_left = 0;

			$area_count = 0;
			$area_amount = 0;
			foreach ($area_json as $value) {
				$area_amount = $result_amount[$area_count];
				if($area_amount > 0){
					$player_bet += $area_amount;
					$player_bet_left += $area_amount;
					$totaldiceresult = $dice_result[0] + $dice_result[1] + $dice_result[2];

					foreach ($value->type as $area_type) {
						$dice_check = $dice_result;
						if(substr($area_type,0,5) == "MATCH"){
							$match_count = 0;
							$match_total = 0;
							$match_arr = explode(",",substr($area_type,6,strlen($area_type)-7));
							foreach ($match_arr as $value) {
								$arraykey = array_search($value, $dice_check);
								if($arraykey !== false) {
									unset($dice_check[$arraykey]);
									$match_count++;
								}
								$match_total++;
							}
							if($match_count === $match_total){
								$win_point += $area_amount * $value->win;
								$player_bet_left -= $area_amount;
							}
						}else if(substr($area_type,0,5) == "TOTAL"){
							$totaldice = substr($area_type,6,strlen($area_type)-7);
							if($totaldice == $totaldiceresult){
								$win_point += $area_amount * $value->win;
								$player_bet_left -= $area_amount;
							}
						}else if(substr($area_type,0,7) == "BETWEEN"){
							$match_arr = explode(",",substr($area_type,8,strlen($area_type)-9));
							if($totaldiceresult >= $match_arr[0] && $totaldiceresult <= $match_arr[1]){
								$win_point += $area_amount * $value->win;
								$player_bet_left -= $area_amount;
							}
						}
					}
				}
				$area_count++;
			}

			//calculate point
			$point_left = $member_point - $player_bet;
			if($point_left >= 0){
				$member_point += $win_point;
				$member_point -= $player_bet_left;
				$result_output = '{"dice":['.$dice_result[0].','.$dice_result[1].','.$dice_result[2].']}';
				$game_log_data = '{"type":"server", "status":"roll", "current":{"member_point":'.$last_member_point.', "member_chance":'.$last_member_chance.', "member_score":'.$last_member_score.'}, "update":{"member_point":'.$member_point.', "member_chance":'.$member_chance.', "member_score":'.$member_score.'}, "bet":'.$player_bet.', "win":'.$win_point.'}';
			}else{
				$result_valid_return = false;
			}
		}
	}else if($gameType == "junglescratch"){
		$setting_names = array("gameSettings","icon_arr","paytable_arr");
		$settings_json = '';
		$icon_json = '';
		$paytable_json = '';

		//retrieve data
		if(!empty($_REQUEST['result_data'])){
			$player_bet = mysqli_real_escape_string($conn, $_REQUEST['result_data']);
		}else{
			$result_return = false;
			$result_valid_return = false;
		}

		//load settings
		foreach ($setting_names as $value) {
			$stmt = $conn->prepare("SELECT setting_name, setting_value FROM $game_settings WHERE game_type = '$gameType' AND setting_status = 1 AND setting_name = '$value'");
			$stmt->execute();
			$stmt->store_result();
			$num_of_rows = $stmt->num_rows;
			$stmt -> bind_result($setting_name, $setting_value);
			$settings = [];
			while ($stmt->fetch()) {
				$settings[] = array(
					'setting_name' => $setting_name,
					'setting_value' => $setting_value
				);
			}
			$stmt->free_result();
			$stmt->close();

			if($num_of_rows > 0){
				if($settings_json == ''){
					$settings_json = json_decode($settings[0]['setting_value'], false);
				}else if($icon_json == ''){
					$icon_json = json_decode($settings[0]['setting_value'], false);
				}else{
					$paytable_json = json_decode($settings[0]['setting_value'], false);
				}
			}else{
				$result_return = false;
			}
		}

		if($result_return){
			$pay_index = -1;
			$total_per_icon = 3;

			if($settings_json->enablePercentage){
				//generate percentage
				$percentage_array = [];

				$paytable_index = 0;
				$total_percent = 0;
				foreach ($paytable_json as $value) {
					if(is_numeric($value->percent)){
						$total_percent += $value->percent;
						for ($i = 0; $i < $value->percent; $i++){
							array_push($percentage_array,$paytable_index);
						}
					}
					$paytable_index++;
				}
				
				$no_result_percent = 100 - $total_percent;
				for ($x = 0; $x < $no_result_percent; $x++) {
					array_push($percentage_array,-1);
				}
				
				shuffle($percentage_array);
				$pay_index = $percentage_array[0];
				$total_per_icon = 2;
			}

			//generate result
			$icon_array = [];
			$icon_index = 0;
			foreach ($icon_json as $value) {
				for ($x = 0; $x < $total_per_icon; $x++) {
					if($pay_index != -1){
						if($paytable_json[$pay_index]->id != $icon_index){
							array_push($icon_array,$icon_index);
						}
					}else{
						array_push($icon_array,$icon_index);
					}
				}
				$icon_index++;
			}

			if($settings_json->enablePercentage){
				shuffle($icon_array);

				$icon_index = 0;
				$icon_new_array = [];
				foreach ($icon_array as $value) {
					if($icon_index < $settings_json->totalScratchItem){
						array_push($icon_new_array,$icon_array[$icon_index]);
					}
					$icon_index++;
				}
				
				if($pay_index != -1){
					for ($x = 0; $x < $paytable_json[$pay_index]->total; $x++) {
						$icon_new_array[$x] = $paytable_json[$pay_index]->id;
					}
				}

				$icon_array = $icon_new_array;
			}
			shuffle($icon_array);
			$icon_array = array_slice($icon_array, 0, $settings_json->totalScratchItem);

			if($pay_index != -1){
				$win_point = $paytable_json[$pay_index]->point * $player_bet;
			}else{
				$win_point = 0;
				foreach ($paytable_json as $pay_value) {
					$total_icons = 0;
					foreach ($icon_array as $icon_value) {
						if($pay_value->id === $icon_value){
							$total_icons++;
						}
					}

					if($total_icons >= $pay_value->total){
						$win_point += $pay_value->point;
					}
				}
			}

			//calculate point
			$point_left = $member_point - $player_bet;
			if($point_left >= 0){
				$member_point -= $player_bet;
				$member_point += $win_point;

				$icon_output = '';
				foreach ($icon_array as $value) {
					$icon_output = $icon_output.(string)$value.", ";
				}
				$icon_output = rtrim($icon_output, ", ");
				$result_output = '{"icons":['.$icon_output.']}';
				$game_log_data = '{"type":"server", "status":"buy", "current":{"member_point":'.$last_member_point.', "member_chance":'.$last_member_chance.', "member_score":'.$last_member_score.'}, "update":{"member_point":'.$member_point.', "member_chance":'.$member_chance.', "member_score":'.$member_score.'}, "bet":'.$player_bet.', "win":'.$win_point.'}';
			}else{
				$result_valid_return = false;
			}
			//$debug_output = $player_bet." , ".$player_bet." , ".$win_point." , ".$icon_index." , ".$pay_index;
		}
	}else if($gameType == "lotterynumbers"){
		$setting_names = array("gameSettings","score_arr","bonusScore");
		$settings_json = '';
		$score_json = '';
		$bonus_json = '';

		//retrieve data
		if(!empty($_REQUEST['result_data'])){
			$result_data = $_REQUEST['result_data'];
			$result_data = json_decode($result_data, false);

			if($member_chance <= 0){
				$result_return = false;
				$result_valid_return = false;
			}
		}else{
			$result_return = false;
			$result_valid_return = false;
		}

		//load settings
		foreach ($setting_names as $value) {
			$stmt = $conn->prepare("SELECT setting_name, setting_value FROM $game_settings WHERE game_type = '$gameType' AND setting_status = 1 AND setting_name = '$value'");
			$stmt->execute();
			$stmt->store_result();
			$num_of_rows = $stmt->num_rows;
			$stmt -> bind_result($setting_name, $setting_value);
			$settings = [];
			while ($stmt->fetch()) {
				$settings[] = array(
					'setting_name' => $setting_name,
					'setting_value' => $setting_value
				);
			}
			$stmt->free_result();
			$stmt->close();

			if($num_of_rows > 0){
				if($settings_json == ''){
					$settings_json = json_decode($settings[0]['setting_value'], false);
				}else if($score_json == ''){
					$score_json = json_decode($settings[0]['setting_value'], false);
				}else{
					$bonus_json = json_decode($settings[0]['setting_value'], false);
				}
			}else{
				$result_return = false;
			}
		}

		$numbers_array = [];
		for ($i = 0; $i < $settings_json->totalBall; $i++){
			array_push($numbers_array,$i);
		}
		shuffle($numbers_array);
		
		if($result_return){
			$score_count  = count($score_json);
			$extra_ball = $settings_json->bonusBall == true ? 1 : 0;
			$total_loop = $score_count + $extra_ball;
			$total_percent = 0;

			if($settings_json->enablePercentage){
				//generate percent
				$percentage_array = [];

				$total_num = $score_count + $extra_ball;
				$total_ball = 0;
				$percent = 0;
				$is_bonus_ball = false;
				
				for ($i = 0; $i < $total_loop; $i++){
					$is_bonus_ball = false;
					
					if($settings_json->bonusBall){			
						if($i == 0){
							$total_num--;	
							$total_ball = $total_num;
							$percent = $score_json[$total_num-1]->percent;
						}else if($i == 1){
							$total_ball = $total_num;
							$percent = $bonus_json[0]->percent;
							$total_num++;
							$is_bonus_ball = true;
						}else{
							$total_ball = $total_num;
							$percent = $score_json[$total_num-1]->percent;
						}
					}else{
						$total_ball = $total_num;
						$percent = $score_json[$total_num-1]->percent;
					}
					
					$total_num--;
					if(is_numeric($percent)){
						if($percent > 0){
							$total_percent += $percent;
							for ($x = 0; $x < $percent; $x++){
								array_push($percentage_array,["total" => $total_ball, "bonus" => $is_bonus_ball]);
							}
						}
					}
				}
				
				$no_result_percent = 100 - $total_percent;
				for ($x = 0; $x < $no_result_percent; $x++) {
					array_push($percentage_array,["total" => 0, "bonus" => false]);
				}
				
				shuffle($percentage_array);

				//generate result
				$reveal_array = [];
				$select_array = [];
				foreach ($result_data as $value) {
					array_push($select_array,$value);
				}
				shuffle($select_array);

				$extra_ball = $settings_json->bonusBall == true ? 1 : 0;
				$number_index = 0;
				for ($i = 0; $i < $score_count; $i++){
					$arraykey = array_search($select_array[$i], $numbers_array);
					if($arraykey !== false) {
						array_push($reveal_array,$numbers_array[$number_index]);
					}else{
						$i--;
					}
					$number_index++;
				}
				
				$bonus_num = 0;
				if($percentage_array[0]['total'] > 0){
					for ($i = 0; $i < $percentage_array[0]['total']; $i++){
						$reveal_array[$i] = $select_array[$i];
						if($percentage_array[0]['bonus'] && $i == $percentage_array[0]['total']-1){
							$bonus_num = $select_array[$i+1];
						}
					}
					shuffle($reveal_array);
				}
				
				if($extra_ball){
					if($percentage_array[0]['bonus']){
						array_push($reveal_array,$bonus_num);
					}else{
						for ($i = 0; $i < 1; $i++){
							$arraykey = array_search($select_array[$i], $numbers_array);
							if($arraykey !== false) {
								array_push($reveal_array,$numbers_array[$number_index]);
							}else{
								$i--;
							}
							$number_index++;
						}
					}
				}
			}else{
				$reveal_array = [];
				for ($i = 0; $i < $total_loop; $i++){
					array_push($reveal_array,$numbers_array[$i]);
				}
			}

			//calculate
			$match_total = 0;
			$match_bonus_number = false;
			for ($i = 0; $i < count($reveal_array); $i++){
				$arraykey = array_search($reveal_array[$i], $result_data);
				if($arraykey !== false){
					if($i == count($reveal_array)-1 && $extra_ball){
						$match_bonus_number = true;
					}
					$match_total++;
				}
			}

			for ($i = 0; $i < $score_count; $i++){
				if($i+1 == $match_total){
					$win_point = $score_json[$i]->prize;
				}
			}
			if($match_bonus_number && $match_total == $score_count){
				$win_point = $bonus_json[0]->prize;
			}
			
			$member_chance--;
			$member_point += $win_point;

			$icon_output = '';
			foreach ($reveal_array as $value) {
				$icon_output = $icon_output.(string)$value.", ";
			}
			$icon_output = rtrim($icon_output, ", ");
			$result_output = '{"numbers":['.$icon_output.']}';
			$game_log_data = '{"type":"server", "status":"play", "current":{"member_point":'.$last_member_point.', "member_chance":'.$last_member_chance.', "member_score":'.$last_member_score.'}, "update":{"member_point":'.$member_point.', "member_chance":'.$member_chance.', "member_score":'.$member_score.'}, "win":'.$win_point.'}';
			
		}
	}else if($gameType == "slotmachine"){
		$setting_names = array("gameSettings","slots_arr","wild_arr","paytable_arr","lines_arr");
		$settings_json = '';
		$slots_json = '';
		$wild_json = '';
		$paytable_json = '';
		$lines_json = '';

		$player_min_bet;
		$player_bet;
		$player_lines;

		//retrieve data
		if(!empty($_REQUEST['result_data'])){
			$result_data = mysqli_real_escape_string($conn, $_REQUEST['result_data']);
			$result_data = json_decode($result_data, true);
		}else{
			$result_return = false;
			$result_valid_return = false;
		}

		//load settings
		foreach ($setting_names as $value) {
			$stmt = $conn->prepare("SELECT setting_name, setting_value FROM $game_settings WHERE game_type = '$gameType' AND setting_status = 1 AND setting_name = '$value'");
			$stmt->execute();
			$stmt->store_result();
			$num_of_rows = $stmt->num_rows;
			$stmt -> bind_result($setting_name, $setting_value);
			$settings = [];
			while ($stmt->fetch()) {
				$settings[] = array(
					'setting_name' => $setting_name,
					'setting_value' => $setting_value
				);
			}
			$stmt->free_result();
			$stmt->close();

			if($num_of_rows > 0){
				if($settings_json == ''){
					$settings_json = json_decode($settings[0]['setting_value'], false);
				}else if($slots_json == ''){
					$slots_json = json_decode($settings[0]['setting_value'], false);
				}else if($wild_json == ''){
					$wild_json = json_decode($settings[0]['setting_value'], false);
				}else if($paytable_json == ''){
					$paytable_json = json_decode($settings[0]['setting_value'], false);
				}else{
					$lines_json = json_decode($settings[0]['setting_value'], false);
				}
			}else{
				$result_return = false;
			}
		}

		if($result_return){
			$slots_count  = count($slots_json);
			$wild_count  = count($wild_json);
			$paytable_count  = count($paytable_json);
			$lines_count  = count($lines_json);

			$player_lines = $result_data[0];
			$player_min_bet = $settings_json->betAmount_arr[$result_data[1]];
			
			//generate result
			$slots_array = [];
			$slot_index = 0;
			foreach ($slots_json as $value) {
				$arraykey = array_search($slot_index, $wild_json);
				if($arraykey === false){
					array_push($slots_array,$slot_index);
				}
				$slot_index++;
			}
			shuffle($slots_array);

			$result_array = [];
			$slot_index = 0;
			for ($i = 0; $i < $settings_json->slotSettings->row * $settings_json->slotSettings->column; $i++){
				array_push($result_array,$slots_array[$slot_index]);
				$slot_index++;
				if($slot_index > count($slots_array)-1){
					$slot_index = 0;
					shuffle($slots_array);
				}
			}

			if($wild_count > 0){
				$wild_random = rand(1,3);
				if($wild_random == 3){
					$wild_slot_index = rand(0,$settings_json->slotSettings->row * $settings_json->slotSettings->column);
					$wild_index = rand(0,$wild_count-1);
					$result_array[$wild_slot_index] = $wild_json[$wild_index];
				}
			}

			if($settings_json->enablePercentage){
				//genereate percentage
				$percentage_array = [];

				$paytable_index = 0;
				$total_percent = 0;
				foreach ($paytable_json as $value) {
					if(is_numeric($value->percent)){
						for ($i = 0; $i < $value->percent; $i++){
							$total_percent += $value->percent;
							array_push($percentage_array,$paytable_index);
						}
					}
					$paytable_index++;
				}

				$no_result_percent = $settings_json->overallPercent - $total_percent;
				for ($x = 0; $x < $no_result_percent; $x++) {
					array_push($percentage_array,-1);
				}

				shuffle($percentage_array);
				$pay_index = $percentage_array[0];
				//$pay_index = 7;

				if($pay_index != -1){
					$random_line = rand(0,$lines_count-1);
					//$random_line = 3;
					$slot_result_index = 0;
					$start_line_index = rand(0,count($lines_json[$random_line]->slots)-count($paytable_json[$pay_index]->index));
					$start_pay_index = 0;

					//echo 'start '.$start_line_index.','.count($lines_json[$random_line]->slots).','.count($paytable_json[$pay_index]->index).'<br>';
					for ($r = 0; $r < $settings_json->slotSettings->row; $r++) {
						for ($c = 0; $c < $settings_json->slotSettings->column; $c++) {
							for ($n = $start_line_index; $n < count($paytable_json[$pay_index]->index); $n++) {
								if($lines_json[$random_line]->slots[$n]->c == $c && $lines_json[$random_line]->slots[$n]->r == $r){
									if($start_pay_index < count($paytable_json[$pay_index]->index)){
										//echo "inject from".$result_array[$slot_result_index].' to '.$paytable_json[$pay_index]->index[$start_pay_index];
										$arraykey = array_search($result_array[$slot_result_index], $wild_json);
										if($arraykey === false){
											$result_array[$slot_result_index] = $paytable_json[$pay_index]->index[$start_pay_index];
										}
										$start_pay_index++;
									}
								}
							}
							$slot_result_index++;
						}
					}
				}
			}else{
				//generate win
				$joy_random = rand(1,3);
				if($joy_random == 3){
					$joy_total = rand(2,5);
					$slot_index = rand(0,$slots_count-1);
					for ($n = 0; $n < $joy_total; $n++) {
						$arraykey = array_search($result_array[$n], $wild_json);
						if($arraykey === false){
							$result_array[$n] = $slot_index;
						}
					}
				}

				shuffle($slots_array);
			}

			/*$result_array = [9,6,4,0,9,
							1,2,3,2,3,
							6,2,1,2,3];*/

			$match_array = [];
			$line_index = 0;
			foreach ($lines_json as $value) {
				if($line_index <= $player_lines){
					$match_lines_array = [];
					$match_count = 1;
					$match_reset = false;
					$line_slot_index = 0;
					$last_index = -1;

					while($line_slot_index < count($value->slots)) {
						$slot_result_index = 0;
						for ($r = 0; $r < $settings_json->slotSettings->row; $r++) {
							for ($c = 0; $c < $settings_json->slotSettings->column; $c++) {
								if($line_slot_index < count($value->slots)){
									if($value->slots[$line_slot_index]->c == $c && $value->slots[$line_slot_index]->r == $r){
										$arraykey = array_search($result_array[$slot_result_index], $wild_json);
										$match_reset = false;
										if($arraykey === false){
											if($result_array[$slot_result_index] != $last_index){
												$match_reset = true;
											}
										}

										if($line_slot_index == count($value->slots)-1){
											if($result_array[$slot_result_index] == $last_index){
												$match_count++;
											}
											$match_reset = true;
										}

										if($match_reset){
											if($match_count > 1){
												array_push($match_lines_array,["index" => $last_index, "total" => $match_count]);
											}

											$last_index = $result_array[$slot_result_index];
											$match_count = 1;
										}else{
											$match_count++;
										}
										$line_slot_index++;
									}
								}
								$slot_result_index++;
							}
						}
					}

					$highest_pay = 0;
					foreach ($match_lines_array as $match_value) {
						for ($n = 0; $n < $paytable_count; $n++) {
							if($match_value['index'] == $paytable_json[$n]->index[0] && $match_value['total'] == count($paytable_json[$n]->index)){
								if($paytable_json[$n]->pay > $highest_pay){
									$highest_pay = $paytable_json[$n]->pay;
								}
							}
						}
					}

					if($highest_pay > 0){
						$win_point += $highest_pay * $player_min_bet;
					}
					$line_index++;
				}
			}

			//calculate
			$player_bet = $player_min_bet * ($player_lines+1);
			$point_left = $member_point - $player_bet;
			if($point_left >= 0){
				$member_point -= $player_bet;
				if($win_point > 0){
					$member_point += $win_point;
				}
				$member_point = floor($member_point);

				$icon_output = '';
				foreach ($result_array as $value) {
					$icon_output = $icon_output.(string)$value.", ";
				}
				$icon_output = rtrim($icon_output, ", ");
				$result_output = '{"result":['.$icon_output.']}';
				$game_log_data = '{"type":"server", "status":"spin", "current":{"member_point":'.$last_member_point.', "member_chance":'.$last_member_chance.', "member_score":'.$last_member_score.'}, "update":{"member_point":'.$member_point.', "member_chance":'.$member_chance.', "member_score":'.$member_score.'}, "bet":'.$player_bet.', "win":'.$win_point.'}';
			
				//$debug_output = $player_bet." , ".$player_bet." , ".$win_point;
			}else{
				$result_valid_return = false;
			}
		}
	}else if($gameType == "superplinko"){
		$setting_names = array("gameSettings","plinkoSettings","plinkoBonusSettings","coinSettings");
		$settings_json = '';
		$plinko_json = '';
		$plinko_bonus_json = '';
		$coin_json = '';

		//retrieve data
		if(!empty($_REQUEST['result_data'])){
			$result_data = $_REQUEST['result_data'];
			$result_data = json_decode($result_data, true);
		}else{
			$result_return = false;
			$result_valid_return = false;
		}

		//load settings
		foreach ($setting_names as $value) {
			$stmt = $conn->prepare("SELECT setting_name, setting_value FROM $game_settings WHERE game_type = '$gameType' AND setting_status = 1 AND setting_name = '$value'");
			$stmt->execute();
			$stmt->store_result();
			$num_of_rows = $stmt->num_rows;
			$stmt -> bind_result($setting_name, $setting_value);
			$settings = [];
			while ($stmt->fetch()) {
				$settings[] = array(
					'setting_name' => $setting_name,
					'setting_value' => $setting_value
				);
			}
			$stmt->free_result();
			$stmt->close();

			if($num_of_rows > 0){
				if($settings_json == ''){
					$settings_json = json_decode($settings[0]['setting_value'], false);
				}else if($plinko_json == ''){
					$plinko_json = json_decode($settings[0]['setting_value'], false);
				}else if($plinko_bonus_json == ''){
					$plinko_bonus_json = json_decode($settings[0]['setting_value'], false);
				}else {
					$coin_json = json_decode($settings[0]['setting_value'], false);
				}
			}else{
				$result_return = false;
			}
		}

		if($result_return){
			$drop_column = $result_data['column'];
			$coin_array = $result_data['coin'];
			$player_bet = $result_data['bet'];
			$bonus_round = $result_data['bonus'];
			$total_coins = ($plinko_json->row * $plinko_json->column)/100 * $settings_json->coinPercent;
			$plinko_result;
			$win_coin = 0;

			if($settings_json->enablePercentage){
				//generate percent
				$percentage_array = [];
				$percentage_bonus_array = [];

				$plinko_prize_index = 0;
				foreach ($plinko_json->prizes as $value) {
					if(is_numeric($value->percent)){
						for ($i = 0; $i < $value->percent; $i++){
							array_push($percentage_array,$plinko_prize_index);
						}
					}
					$plinko_prize_index++;
				}

				$plinko_bonus_index = 0;
				foreach ($plinko_bonus_json->prizes as $value) {
					if(is_numeric($value->percent)){
						for ($i = 0; $i < $value->percent; $i++){
							array_push($percentage_bonus_array,$plinko_bonus_index);
						}
					}
					$plinko_bonus_index++;
				}
				
				shuffle($percentage_array);
				shuffle($percentage_bonus_array);
				
				if(!$bonus_round){
					$plinko_result = $percentage_array[0];
				}else{
					$plinko_result = $percentage_bonus_array[0];
				}
			}

			//generate result
			$path_array = [];
			if(!$bonus_round){
				for ($n = 0; $n < $plinko_json->row; $n++) {
					$total_pins = $plinko_json->column;
					if($n % 2 != 0){
						$total_pins = $total_pins-1;
					}
	
					$column_array = [];
					for ($p = 0; $p < $total_pins; $p++) {
						array_push($column_array,$p);
					}
					array_push($path_array,$column_array);
				}
				$prizes_array = [];
				for ($n = 0; $n < count($plinko_json->prizes); $n++) {
					array_push($prizes_array,$n);
				}
				array_push($path_array,$prizes_array);
			}else{
				for ($n = 0; $n < $plinko_bonus_json->row; $n++) {
					$total_pins = $plinko_bonus_json->column;
					if($n % 2 != 0){
						$total_pins = $total_pins-1;
					}
	
					$column_array = [];
					for ($p = 0; $p < $total_pins; $p++) {
						array_push($column_array,$p);
					}
					array_push($path_array,$column_array);
				}
				$prizes_array = [];
				for ($n = 0; $n < count($plinko_bonus_json->prizes); $n++) {
					array_push($prizes_array,$n);
				}
				array_push($path_array,$prizes_array);
			}

			$move_row = 0;
			$move_column = $drop_column;
			$distance_column = -1;
			$move_array = [];
			$move_set_array = [];

			for ($n = 0; $n < count($path_array); $n++) {
				$move_row = $n;
				$move_random = true;
				$move_in = true;

				if($n == 0){
					//first
					array_push($move_array,["row" => $move_row, "column" => $move_column, "random" => false]);
				}else{
					if($n % 2 == 0){
						//is even
						$move_in = false;
					}

					if($settings_json->enablePercentage){
						$move_num = count($path_array) - $n;
						$safe_distance = ($distance_column * 2) + 1;
						if($safe_distance >= $move_num){
							$move_random = false;
						}
					}

					if($move_random){
						if($move_in){
							if($move_column == 0){
								$move_column = 0;
							}else if($move_column == count($path_array[$n])){
								$move_column = $move_column-1;
							}else{
								if (rand(0, 1)) {
									$move_column = $move_column-1;
								}
							}
						}else{
							if (rand(0, 1)) {
								$move_column = $move_column+1;
							}
						}
					}else{
						if($move_in){
							if($move_column < $plinko_result){
								$move_column = $move_column;
							}else{
								$move_column = $move_column-1;
							}
						}else{
							if($move_column == $plinko_result){
								if($n != count($path_array)-1){
									if (rand(0, 1)) {
										$move_column = $move_column-1;
									}
								}
							}else if($move_column < $plinko_result){
								$move_column = $move_column+1;
							}else{
								$move_column = $move_column;
							}
						}
					}

					if($n < count($move_set_array)){
						$move_column = $move_set_array[$n];
					}

					if($n == count($path_array)-1){
						$plinko_result = $move_column;
					}
					
					$coin_index = 0;
					if($settings_json->coin){
						foreach ($coin_array as $value) {
							if($coin_index < $total_coins){
								if($move_row == $value["r"] && $move_column == $value["c"]){
									$win_coin += $coin_json[$value["index"]]->value;
								}
							}
							$coin_index++;
						}
					}
					array_push($move_array,["row" => $move_row, "column" => $move_column, "random" => $move_random]);
				}
				
				if($settings_json->enablePercentage){
					$distance_column = abs($move_column - $plinko_result);
				}
			}

			if($bonus_round){
				$win_point += $plinko_bonus_json->prizes[$plinko_result]->value;
			}else{
				$win_point += $plinko_json->prizes[$plinko_result]->value;
			}

			//calculate
			if($settings_json->gamePlayType){
				if(!$bonus_round){
					if($member_chance > 0){
						if(!$bonus_round){
							$member_chance--;
						}
						$member_point += $win_point;

						if($win_point > 0){
							$member_point += $win_coin;
						}
					}else{
						$result_valid_return = false;
					}
				}else{
					$member_point += $win_point;
				}
			}else{
				if(!$bonus_round){
					$point_left = $member_point - $player_bet;
					if($point_left >= 0){
						$member_point -= $player_bet;
	
						$win_point = $win_point * $player_bet;
						$member_point += $win_point;
						if($win_point > 0){
							$member_point += $win_coin;
						}
					}else{
						$result_valid_return = false;
					}
				}else{
					$win_point = $win_point * $player_bet;
					$member_point += $win_point;
					if($win_point > 0){
						$member_point += $win_coin;
					}
				}
			}

			if($win_point > 0){
				$win_point += $win_coin;
			}
			//$debug_output = $member_point." , ".$win_point." , ".$win_coin;
			$member_score = $member_point;

			$path_output = '';
			foreach ($move_array as $value) {
				$random = $value['random'] == true ? "true" : "false";
				$path_output = $path_output.'{"r":'.$value['row'].', "c":'.$value['column'].', "random":'.$random.'}, ';
			}
			$path_output = rtrim($path_output, ", ");
			$result_output = '{"path":['.$path_output.']}';
			$game_log_data = '{"type":"server", "status":"drop", "current":{"member_point":'.$last_member_point.', "member_chance":'.$last_member_chance.', "member_score":'.$last_member_score.'}, "update":{"member_point":'.$member_point.', "member_chance":'.$member_chance.', "member_score":'.$member_score.'}, "bet":'.$player_bet.', "win":'.$win_point.'}';
			
		}
	}else if($gameType == "bingobash"){
		$setting_names = array("gameSettings");
		$settings_json = '';

		//retrieve data
		if(!empty($_REQUEST['result_data'])){
			$result_data = $_REQUEST['result_data'];
			$result_data = json_decode($result_data, false);

			if($member_chance <= 0){
				$result_return = false;
				$result_valid_return = false;
			}
		}else{
			$result_return = false;
			$result_valid_return = false;
		}

		//load settings
		foreach ($setting_names as $value) {
			$stmt = $conn->prepare("SELECT setting_name, setting_value FROM $game_settings WHERE game_type = '$gameType' AND setting_status = 1 AND setting_name = '$value'");
			$stmt->execute();
			$stmt->store_result();
			$num_of_rows = $stmt->num_rows;
			$stmt -> bind_result($setting_name, $setting_value);
			$settings = [];
			while ($stmt->fetch()) {
				$settings[] = array(
					'setting_name' => $setting_name,
					'setting_value' => $setting_value
				);
			}
			$stmt->free_result();
			$stmt->close();

			if($num_of_rows > 0){
				if($settings_json == ''){
					$settings_json = json_decode($settings[0]['setting_value'], false);
				}
			}else{
				$result_return = false;
			}
		}

		if($result_return){
			$return_type = $result_data->type;

			if($return_type == "start"){
				$numbers_array = [];
				for ($n = 0; $n < 75; $n++) {
					array_push($numbers_array,$n+1);
				}
				shuffle($numbers_array);

				//calculate
				$member_chance--;

				//output
				$numbers_output = '';
				foreach ($numbers_array as $value) {
					$numbers_output = $numbers_output.$value.', ';
				}
				$numbers_output = rtrim($numbers_output, ", ");
				$result_output = '{"numbers":['.$numbers_output.']}';
			}else if($return_type == "end"){
				if($_SESSION['result_type'] == "start"){
					if($result_data->complete){
						$win_point = ($settings_json->totalRevealBalls - $result_data->reveal) / 100 * $settings_json->resultScore->score;
						$member_point += $win_point;

						if($member_point != $result_data->score){
							$result_valid_return = false;
						}
					}
				}else{
					$result_valid_return = false;
				}
			}
			$_SESSION['result_type'] = $return_type;
			$game_log_data = '{"type":"server", "status":"'.$return_type.'", "current":{"member_point":'.$last_member_point.', "member_chance":'.$last_member_chance.', "member_score":'.$last_member_score.'}, "update":{"member_point":'.$member_point.', "member_chance":'.$member_chance.', "member_score":'.$member_score.'}, "win":'.$win_point.'}';
		}
	}else if($gameType == "extremeplinko"){
		$setting_names = array("gameSettings");
		$settings_json = '';

		//retrieve data
		if(!empty($_REQUEST['result_data'])){
			$result_data = $_REQUEST['result_data'];
			$result_data = json_decode($result_data, true);

		}else{
			$result_return = false;
			$result_valid_return = false;
		}

		//load settings
		foreach ($setting_names as $value) {
			$stmt = $conn->prepare("SELECT setting_name, setting_value FROM $game_settings WHERE game_type = '$gameType' AND setting_status = 1 AND setting_name = '$value'");
			$stmt->execute();
			$stmt->store_result();
			$num_of_rows = $stmt->num_rows;
			$stmt -> bind_result($setting_name, $setting_value);
			$settings = [];
			while ($stmt->fetch()) {
				$settings[] = array(
					'setting_name' => $setting_name,
					'setting_value' => $setting_value
				);
			}
			$stmt->free_result();
			$stmt->close();

			if($num_of_rows > 0){
				if($settings_json == ''){
					$settings_json = json_decode($settings[0]['setting_value'], false);
				}
			}else{
				$result_return = false;
			}
		}

		$row_index = $result_data['rows'];
		$risk_level = $result_data['risk'];
		$total_balls = $result_data['balls'];
		$player_bet = $result_data['bet'];

		if($settings_json->gamePlayType){
			if($member_chance > 0 && $total_balls <= $member_chance){
				
			}else{
				$result_return = false;
				$result_valid_return = false;
			}
		}else{
			$point_left = $member_point - ($player_bet * $total_balls);
			if($point_left >= 0){
				
			}else{
				$result_return = false;
				$result_valid_return = false;
			}
		}
		
		if($result_return){
			if($settings_json->enablePercentage){
				//generate percent
				$percentage_array = [];

				$plinko_prize_index = 0;
				foreach ($settings_json->rows[$row_index]->prizes as $value) {
					if(is_numeric($value->percent)){
						for ($i = 0; $i < $value->percent; $i++){
							array_push($percentage_array,$plinko_prize_index);
						}
					}
					$plinko_prize_index++;
				}
			}

			//generate result
			$path_array = []; //path array
			$total_rows = $settings_json->rows[$row_index]->total;
			$total_board_rows = $settings_json->rows[count($settings_json->rows)-1]->total;
			$total_column = $settings_json->board->startPin;

			for ($n = 0; $n < $total_board_rows; $n++) {
				$total_column++;
			}

			for ($n = 0; $n < $total_rows+1; $n++) {
				$column_array = [];
				for ($p = 0; $p < $total_column; $p++) {
					array_push($column_array,$p);
				}
				array_push($path_array,$column_array);
			}

			$total_prizes = 0; //total prizes
			$total_prizes = count($settings_json->rows[$row_index]->prizes) * 2;
			if(!$settings_json->rows[$row_index]->even){
				$total_prizes--;
			}

			$moves_array = [];
			for ($b = 0; $b < $total_balls; $b++) {
				//find prizes
				$plinko_result = -1;
				$plinko_column_index;

				if($settings_json->enablePercentage){
					shuffle($percentage_array);
					$plinko_result = $percentage_array[0];
				}

				if($plinko_result != -1){
					$plinko_column_index = (count($settings_json->rows[$row_index]->prizes)-1) - $plinko_result;
					if (rand(0, 1)) {
						if(!$settings_json->rows[$row_index]->even){
							$plinko_column_index = (count($settings_json->rows[$row_index]->prizes)-1) + $plinko_result;
						}else{
							$plinko_column_index = (count($settings_json->rows[$row_index]->prizes)) + $plinko_result;
						}
					}

					$last_row = $settings_json->rows[$row_index]->total;
					$center_row = floor(count($path_array[$last_row])/2);
					$center_prize = floor($total_prizes/2);
					$target_column = 0;
					if(!$settings_json->rows[$row_index]->even){
						$target_column = $center_row - ($center_prize - $plinko_column_index);
						$target_column--;
					}else{
						$target_column = $center_row - ($center_prize - $plinko_column_index);
						if($plinko_column_index < $center_prize){
							$target_column--;
						}
					}
					$target_column++;
				}

				$center_column = floor(($total_column - $settings_json->board->startPin)/2);
				$random_drop = [];
				$start_column = $center_column;
				for ($n = 0; $n < $settings_json->board->startPin; $n++) {
					array_push($random_drop,$start_column);
					$start_column++;
				}

				$drop_column;
				if($plinko_result != -1){
					$drop_distance = -1;
					for ($n = 0; $n < count($random_drop); $n++) {
						$check_distance = abs($random_drop[$n] - $target_column);
						if($drop_distance == -1){
							$drop_distance = $check_distance;
							$drop_column = $random_drop[$n];
						}
						
						if($drop_distance > $check_distance){
							$drop_distance = $check_distance;
							$drop_column = $random_drop[$n];
						}
					}
				}else{
					shuffle($random_drop);
					$drop_column = $random_drop[0];
				}

				$move_row = 0;
				$move_column = $drop_column;
				$distance_column = -1;
				$move_array = [];
				$move_set_array = [];

				for ($n = 0; $n < count($path_array); $n++) {
					$move_row = $n;
					$move_random = true;
					$move_in = true;

					if($n == 0){
						//first
						array_push($move_array,["row" => $move_row, "column" => $move_column, "random" => false]);
					}else{
						if($n % 2 == 0){
							//is even
							$move_in = false;
						}

						if($settings_json->enablePercentage){
							$move_num = count($path_array) - $n;
							$safe_distance = ($distance_column * 2) + 1;
							if($safe_distance >= $move_num){
								$move_random = false;
							}
						}

						if($move_random){
							if($move_in){
								if($move_column == 0){
									$move_column = 0;
								}else if($move_column == count($path_array[$n])){
									$move_column = $move_column-1;
								}else{
									if (rand(0, 1)) {
										$move_column = $move_column-1;
									}
								}
							}else{
								if (rand(0, 1)) {
									$move_column = $move_column+1;
								}
							}
						}else{
							if($move_in){
								if($move_column < $target_column){
									$move_column = $move_column;
								}else{
									$move_column = $move_column-1;
								}
							}else{
								if($move_column == $target_column){
									if($n != count($path_array)-1){
										if (rand(0, 1)) {
											$move_column = $move_column-1;
										}
									}
								}else if($move_column < $target_column){
									$move_column = $move_column+1;
								}else{
									$move_column = $move_column;
								}
							}
						}

						if($n < count($move_set_array)){
							$move_column = $move_set_array[$n];
						}

						if($n == count($path_array)-1){
							$plinko_result = $move_column;

							$last_row = $settings_json->rows[$row_index]->total;
							$center_row = floor(count($path_array[$last_row])/2);
							$center_prize = floor($total_prizes/2);
							if(!$settings_json->rows[$row_index]->even){
								if($plinko_result > $center_row){
									$plinko_result = $plinko_result - $center_row;
								}else{
									$plinko_result = $center_row - $plinko_result;
								}
							}else{
								if($plinko_result > $center_row){
									$plinko_result = ($plinko_result - $center_row) - 1;
								}else{
									$plinko_result = ($center_row - $plinko_result) - 1;
								}
								$plinko_result = $plinko_result < 0 ? 0 : $plinko_result;
							}
						}

						array_push($move_array,["row" => $move_row, "column" => $move_column, "random" => $move_random]);
					}
					
					if($settings_json->enablePercentage){
						$distance_column = abs($move_column - $target_column);
					}
				}

				//calculate
				$collect_point = 0;
				if($settings_json->gamePlayType){
					$member_chance--;

					if($plinko_result < count($settings_json->rows[$row_index]->prizes)){
						$collect_point = $settings_json->chancesPoint * $settings_json->rows[$row_index]->prizes[$plinko_result]->value[$risk_level];
						if($collect_point > $settings_json->chancesPoint){
							$collect_point = $collect_point - $settings_json->chancesPoint;
							$win_point += $collect_point;
						}
					}
				}else{
					$member_point -= $player_bet;

					if($plinko_result < count($settings_json->rows[$row_index]->prizes)){
						$collect_point = $player_bet * $settings_json->rows[$row_index]->prizes[$plinko_result]->value[$risk_level];
						if($collect_point > $player_bet){
							$collect_point = $collect_point - $player_bet;
							$win_point += $collect_point;
						}
					}
				}

				array_push($moves_array,$move_array);
			}

			if($win_point > 0){
				$member_point += $win_point;
			}
			//$debug_output = $member_point." , ".$win_point." , ".$plinko_result." , ".$move_column;
			$member_score = $member_point;

			$path_output = '';
			foreach ($moves_array as $path_value) {
				$path_single_ouput = '';
				foreach ($path_value as $value) {
					$random = $value['random'] == true ? "true" : "false";
					$path_single_ouput = $path_single_ouput.'{"r":'.$value['row'].', "c":'.$value['column'].', "random":'.$random.'}, ';
				}
				$path_single_ouput = rtrim($path_single_ouput, ", ");
				$path_output = $path_output.'['.$path_single_ouput.'],';
			}

			$path_output = rtrim($path_output, ", ");
			$result_output = '{"path":['.$path_output.']}';
			$game_log_data = '{"type":"server", "status":"drop", "current":{"member_point":'.$last_member_point.', "member_chance":'.$last_member_chance.', "member_score":'.$last_member_score.'}, "update":{"member_point":'.$member_point.', "member_chance":'.$member_chance.', "member_score":'.$member_score.'}, "bet":'.$player_bet.', "win":'.$win_point.'}';
			
		}
	}else if($gameType == "scratchandwin"){
		$setting_names = array("gameSettings","cardsSettings");
		$settings_json = '';
		$cards_json = '';

		//retrieve data
		if(!empty($_REQUEST['result_data'])){
			$card_index = mysqli_real_escape_string($conn, $_REQUEST['result_data']);
			$card_index = (int)$card_index;
			$card_index--;
		}else{
			$result_return = false;
			$result_valid_return = false;
		}

		//load settings
		foreach ($setting_names as $value) {
			$stmt = $conn->prepare("SELECT setting_name, setting_value FROM $game_settings WHERE game_type = '$gameType' AND setting_status = 1 AND setting_name = '$value'");
			$stmt->execute();
			$stmt->store_result();
			$num_of_rows = $stmt->num_rows;
			$stmt -> bind_result($setting_name, $setting_value);
			$settings = [];
			while ($stmt->fetch()) {
				$settings[] = array(
					'setting_name' => $setting_name,
					'setting_value' => $setting_value
				);
			}
			$stmt->free_result();
			$stmt->close();

			if($num_of_rows > 0){
				if($settings_json == ''){
					$settings_json = json_decode($settings[0]['setting_value'], false);
				}else if($cards_json == ''){

					$cards_json = json_decode($settings[0]['setting_value'], false);
				}
			}else{
				$result_return = false;
			}
		}

		if($result_return){
			//prepare prizes
			$matched_items = $cards_json[$card_index]->matchedItems;
			$bonus_max = $cards_json[$card_index]->bonusMax;
			$total_prizes = 0;
			$total_bonus = 0;
			$total_numbers = 0;

			foreach ($cards_json[$card_index]->items as $value) {
				if($value->type == 'prize'){
					$total_prizes++;
				}else if($value->type == 'bonus'){
					$total_bonus++;
				}else if($value->type == 'number'){
					$total_numbers++;
				}else if($value->type == 'prize,bonus'){
					$total_prizes++;
					$total_bonus++;
				}
			}

			$result_prizes = [];
			$result_bonus = [];
			$result_prize_index = -1;
			$result_win_numbers = [];
			$result_user_numbers = [];
			$result_bonus_slots = [];
			$result_symbols = [];
			$win_ratio = [0,0,0,1];

			//fillsymbols
			$symbols_count = 0;
			foreach ($cards_json[$card_index]->symbols as $value) {
				array_push($result_symbols,$symbols_count);
				$symbols_count++;
			}
			shuffle($result_symbols);

			//fill numbers
			if(count($cards_json[$card_index]->numbers) == 2){
				$store_numbers = [];
				$number_count = 0;
				$start_number = 0;
				$end_number = 0;
				foreach ($cards_json[$card_index]->numbers as $value) {
					if($number_count == 0){
						$start_number = $value;
					}else if($number_count == 1){
						$end_number = $value;
					}
					$number_count++;
				}

				for($n=$start_number; $n<=$end_number; $n++){
					array_push($store_numbers,$n);
				}
				shuffle($store_numbers);
				for($n=0; $n<$total_numbers; $n++){
					array_push($result_win_numbers,$store_numbers[$n]);
				}
				for($n=$total_numbers; $n<=count($store_numbers); $n++){
					if($n < ($total_numbers + $total_prizes)){
						array_push($result_user_numbers,$store_numbers[$n]);
					}
				}
			}

			//generate percentage
			if($settings_json->enablePercentage){
				$percentage_prize_array = [];
				$percentage_index = 0;
				$total_percent = 0;
				foreach ($cards_json[$card_index]->prizes as $value) {
					if(is_numeric($value->percent)){
						if($value->percent > 0){
							$total_percent += $value->percent;
							for ($i = 0; $i < $value->percent; $i++){
								array_push($percentage_prize_array,$percentage_index);
							}
						}
					}
					$percentage_index++;
				}

				$no_result_percent = 100 - $total_percent;
				for ($x = 0; $x < $no_result_percent; $x++) {
					array_push($percentage_prize_array,-1);
				}

				$percentage_bonus_array = [];
				$percentage_index = 0;
				$total_percent = 0;
				foreach ($cards_json[$card_index]->prizes as $value) {
					if(is_numeric($value->percent)){
						if($value->percent > 0){
							$total_percent += $value->percent;
							for ($i = 0; $i < $value->percent; $i++){
								array_push($percentage_bonus_array,$percentage_index);
							}
						}
					}
					$percentage_index++;
				}

				$no_result_percent = 100 - $total_percent;
				for ($x = 0; $x < $no_result_percent; $x++) {
					array_push($percentage_bonus_array,-1);
				}
				
				shuffle($percentage_prize_array);
				shuffle($percentage_bonus_array);
			}

			//fill prizes
			$is_win_number = count($result_win_numbers) > 0 ? true : false;
			$store_prizes = [];
			for($p=0; $p<count($cards_json[$card_index]->prizes); $p++){
				if($matched_items != 0){
					for($l=0; $l<$matched_items-1; $l++){
						array_push($store_prizes,$p);
					}
				}else{
					array_push($store_prizes,$p);
				}
			}

			shuffle($store_prizes);
			$result_prize_index = $store_prizes[0];
			for($p=0; $p<$total_prizes; $p++){
				array_push($result_prizes,$store_prizes[$p]);
			}

			//fill bonus
			$store_bonus = [];
			for($p=0; $p<count($cards_json[$card_index]->bonus); $p++){
				if($matched_items != 0){
					for($l=0; $l<$matched_items-1; $l++){
						array_push($store_bonus,$p);
					}
				}else{
					array_push($store_bonus,$p);
				}
			}
			
			shuffle($store_bonus);
			for($p=0; $p<$total_bonus; $p++){
				array_push($result_bonus,$store_bonus[$p]);
			}

			//fill bonus slots
			if($bonus_max > 0){
				$random_fill = rand(0,$bonus_max);
				for($n=0; $n<$total_bonus; $n++){
					if($n < $random_fill){
						array_push($result_bonus_slots,0);
					}else{
						array_push($result_bonus_slots,-1);
					}
				}
				shuffle($result_bonus_slots);
			}

			//insert win prizes
			if($settings_json->enablePercentage){
				//prizes percentage
				shuffle($percentage_prize_array);

				if($matched_items != 0){
					$percent_index = $percentage_prize_array[0];
					if($percent_index != -1){
						$result_prize_index = $percent_index;
						if(count($result_symbols) > 0){
							//replace symbols
							$percent_index = array_rand($result_symbols);
						}

						for($n=0; $n<$matched_items; $n++){
							$result_prizes[$n] = $percent_index;

							$total_matched = 0;
							for($l=0; $l<count($result_prizes); $l++){
								if($result_prizes[$l] == $percent_index){
									$total_matched++;
								}
							}
							if($total_matched == $matched_items){
								$n = $matched_items;
							}
						}
						shuffle($result_prizes);
					}
				}else{
					for($n=0; $n<$total_prizes; $n++){
						shuffle($percentage_prize_array);
						$percent_index = $percentage_prize_array[$n];
						if($percent_index != -1){
							if($is_win_number){
								$random_win_number = array_rand($result_win_numbers);
								$result_user_numbers[$n] = $result_win_numbers[$random_win_number];
								$result_prizes[$n] = $percent_index;
							}else{
								$result_prizes[$n] = $percent_index;
							}
						}
					}
				}

				//bonus percentage
				for($n=0; $n<$total_bonus; $n++){
					shuffle($percentage_bonus_array);
					$percent_index = $percentage_bonus_array[$n];
					if($percent_index != -1){
						$result_bonus[$n] = $percent_index;
					}
				}
			}else{
				//prizes random
				if($matched_items != 0){
					shuffle($win_ratio);
					if($win_ratio[0] == 1){
						$prize_index = array_rand($cards_json[$card_index]->prizes);
						for($n=0; $n<$matched_items; $n++){
							$result_prizes[$n] = $prize_index;

							$total_matched = 0;
							for($l=0; $l<count($result_prizes); $l++){
								if($result_prizes[$l] == $prize_index){
									$total_matched++;
								}
							}
							if($total_matched == $matched_items){
								$n = $matched_items;
							}
						}
					}
				}else{
					for($n=0; $n<$total_prizes; $n++){
						$prize_index = array_rand($cards_json[$card_index]->prizes);
						if($is_win_number){
							shuffle($win_ratio);
							if($win_ratio[0] == 1){
								$random_win_number = array_rand($result_win_numbers);
								$result_user_numbers[$n] = $result_win_numbers[$random_win_number];
								$result_prizes[$n] = $prize_index;
							}
						}else{
							$result_prizes[$n] = $prize_index;
						}
					}
				}
				shuffle($result_prizes);

				//bonus random
				for($n=0; $n<$total_bonus; $n++){
					$prize_index = array_rand($cards_json[$card_index]->bonus);
					if($prize_index != -1){
						$result_bonus[$n] = $prize_index;
					}
				}
				shuffle($result_bonus);
			}

			/*$result_prizes = [
				9,
					4,
					11,
					8,
					14,
					2,
					6,
					7,
					14,
					8,
					1,
					14,
					3,
					10,
					9
			];

			$result_bonus = [
						10,
						9,
						4,
						9,
						8,
						10,
						0,
						13,
						11,
						6,
						7,
						4,
						5,
						7,
						12
			];

			$result_win_numbers = [
						59,
						3,
						45,
						99,
						24,
						87,
						9,
						61
			];

			$result_user_numbers = [
						8,
						71,
						19,
						45,
						96,
						99,
						11,
						3,
						80,
						18,
						45,
						6,
						39,
						91,
						3
				];

			$result_bonus_slots = [
						-1,
						-1,
						-1,
						-1,
						-1,
						-1,
						-1,
						-1,
						-1,
						-1,
						-1,
						0,
						0,
						-1,
						-1
			];*/

			//match win points
			$win_point = 0;
			$count_prize = 0;
			$count_bonus = 0;
			$count_number = 0;
			$count_bonus_slot = 0;
			if($matched_items != 0){
				$match_arr = [];
				$target_prize_index = -1;
				for($n=0; $n<count($cards_json[$card_index]->items); $n++){
					$item_type = $cards_json[$card_index]->items[$n]->type;
					
					if($item_type == 'prize'){
						$item_index = $result_prizes[$count_prize];
						$count_prize++;

						$find_index = -1;
						for($m=0; $m<count($match_arr); $m++){
							if ($match_arr[$m]['index'] == $item_index) {
								$find_index = $m;
							}
						}
						if($find_index == -1){
							array_push($match_arr,["index" => $item_index, "arr" => [$n]]);
						}else{
							array_push($match_arr[$find_index]['arr'], $n);
						}
					}else if($item_type == 'display'){
						$target_prize_index = $result_prize_index;
					}
				}

				for($n=0; $n<count($match_arr); $n++){
					if(count($match_arr[$n]['arr']) >= $matched_items){				
						$win_point = $cards_json[$card_index]->prizes[$match_arr[$n]['index']]->value;
						if($target_prize_index != -1){
							$win_point = $cards_json[$card_index]->prizes[$target_prize_index]->value;
						}
					}
				}
			}else{
				for($n=0; $n<count($cards_json[$card_index]->items); $n++){
					$item_type = $cards_json[$card_index]->items[$n]->type;
					$item_number = -1;
					$item_bonus = false;
					$item_show_number = false;

					if(count($result_user_numbers) > 0){
						$item_show_number = true;
					}

					if($item_type == 'prize,bonus' || $item_type == 'prize'){
						if(count($result_bonus_slots) > 0){
							if($result_bonus_slots[$count_bonus_slot] == 0){
								$item_bonus = true;
							}
							$count_bonus_slot++;
						}
					}

					$prize_value = 0;
					if($is_win_number){
						$is_win = false;
						if($item_type == 'prize,bonus'){
							if($item_bonus){
								$item_index = $result_bonus[$count_prize];
								$count_prize++;
								$count_number++;
								
								if($cards_json[$card_index]->bonus[$item_index]->value > 0){
									$is_win = true;
									$win_point += $cards_json[$card_index]->bonus[$item_index]->value;
								}
							}else{
								if($item_show_number){
									$item_number = $result_user_numbers[$count_number];
								}
								$count_number++;

								$item_index = $result_prizes[$count_prize];
								$count_prize++;

								$arraykey = array_search($item_number, $result_win_numbers);
								if($arraykey !== false){
									if($cards_json[$card_index]->prizes[$item_index]->value > 0){
										$is_win = true;
										$win_point += $cards_json[$card_index]->prizes[$item_index]->value;
									}
								}
							}
						}else if($item_type == 'prize'){
							if($item_show_number){
								$item_number = $result_user_numbers[$count_number];
								$count_number++;
							}

							$item_index = $result_prizes[$count_prize];
							$count_prize++;

							$arraykey = array_search($item_number, $result_win_numbers);
							if($arraykey !== false){
								if($cards_json[$card_index]->prizes[$item_index]->value > 0){
									$is_win = true;
									$win_point += $cards_json[$card_index]->prizes[$item_index]->value;
								}
							}
						}else if($item_type == 'bonus'){
							$item_index = $result_bonus[$count_bonus];
							$count_bonus++;

							if($cards_json[$card_index]->bonus[$item_index]->value > 0){
								$is_win = true;
								$win_point += $cards_json[$card_index]->bonus[$item_index]->value;
							}
						}
					}else{
						if($item_type == 'prize'){
							$item_index = $result_prizes[$count_prize];
							$count_prize++;

							$prize_value = $cards_json[$card_index]->prizes[$item_index]->value;
						}else if($item_type == 'bonus'){
							$item_index = $result_bonus[$count_bonus];
							$count_bonus++;


							$prize_value = $cards_json[$card_index]->bonus[$item_index]->value;
						}

						if($prize_value > 0){
							$win_point += $prize_value;
						}
					}
				}
			}

			//calculate point
			$player_bet = $cards_json[$card_index]->price->value;
			$point_left = $member_point - $player_bet;
			if($point_left >= 0){
				$member_point -= $player_bet;
				$member_point += $win_point;

				//generate result
				$prizes_output = '';
				$bonus_output = '';
				$win_numbers_output = '';
				$user_numbers_output = '';
				$bonus_slots_output = '';
				$symbols_output = '';

				foreach ($result_prizes as $value) {
					$prizes_output = $prizes_output.(string)$value.", ";
				}
				$prizes_output = rtrim($prizes_output, ", ");

				foreach ($result_bonus as $value) {
					$bonus_output = $bonus_output.(string)$value.", ";
				}
				$bonus_output = rtrim($bonus_output, ", ");
				
				foreach ($result_win_numbers as $value) {
					$win_numbers_output = $win_numbers_output.(string)$value.", ";
				}
				$win_numbers_output = rtrim($win_numbers_output, ", ");

				foreach ($result_user_numbers as $value) {
					$user_numbers_output = $user_numbers_output.(string)$value.", ";
				}
				$user_numbers_output = rtrim($user_numbers_output, ", ");

				foreach ($result_bonus_slots as $value) {
					$bonus_slots_output = $bonus_slots_output.(string)$value.", ";
				}
				$bonus_slots_output = rtrim($bonus_slots_output, ", ");

				foreach ($result_symbols as $value) {
					$symbols_output = $symbols_output.(string)$value.", ";
				}
				$symbols_output = rtrim($symbols_output, ", ");

				$result_output = '{"prize_index":['.$result_prize_index.'], "prizes":['.$prizes_output.'], "bonus":['.$bonus_output.'], "win_numbers":['.$win_numbers_output.'], "user_numbers":['.$user_numbers_output.'], "bonus_slots":['.$bonus_slots_output.'], "symbols":['.$symbols_output.']}';
				$game_log_data = '{"type":"server", "status":"buy", "current":{"member_point":'.$last_member_point.', "member_chance":'.$last_member_chance.', "member_score":'.$last_member_score.'}, "update":{"member_point":'.$member_point.', "member_chance":'.$member_chance.', "member_score":'.$member_score.'}, "bet":'.$player_bet.', "win":'.$win_point.'}';
			}else{
				$result_valid_return = false;
			}

			//$debug_output = $player_bet." , ".$win_point;
		}
	}else if($gameType == "powerkeno"){
		$setting_names = array("gameSettings","prizeSettings");
		$settings_json = '';
		$prize_json = '';

		//retrieve data
		if(!empty($_REQUEST['result_data'])){
			$result_data = $_REQUEST['result_data'];
			$result_data = json_decode($result_data, false);
		}else{
			$result_return = false;
			$result_valid_return = false;
		}

		//load settings
		foreach ($setting_names as $value) {
			$stmt = $conn->prepare("SELECT setting_name, setting_value FROM $game_settings WHERE game_type = '$gameType' AND setting_status = 1 AND setting_name = '$value'");
			$stmt->execute();
			$stmt->store_result();
			$num_of_rows = $stmt->num_rows;
			$stmt -> bind_result($setting_name, $setting_value);
			$settings = [];
			while ($stmt->fetch()) {
				$settings[] = array(
					'setting_name' => $setting_name,
					'setting_value' => $setting_value
				);
			}
			$stmt->free_result();
			$stmt->close();

			if($num_of_rows > 0){
				if($settings_json == ''){
					$settings_json = json_decode($settings[0]['setting_value'], false);
				}else if($prize_json == ''){
					$prize_json = json_decode($settings[0]['setting_value'], false);
				}
			}else{
				$result_return = false;
			}
		}

		$total_play = count($result_data->numbers);
		$player_bet = $settings_json->betOptions[$result_data->bet];
		$prize_index;

		$numbers_array = [];
		for ($i = 1; $i <= 80; $i++){
			array_push($numbers_array,$i);
		}
		shuffle($numbers_array);
		
		if($result_return){
			if($settings_json->enablePercentage){
				//generate percent
				$percentage_array = [];
				$total_percent = 0;
				for ($i = 0; $i < count($prize_json); $i++){
					if($prize_json[$i]->play == $total_play){
						$prize_index = $i;
						for ($p = 0; $p < count($prize_json[$i]->paytable); $p++){
							$percent = $prize_json[$i]->paytable[$p]->percent;
							if(is_numeric($percent)){
								if($percent > 0){
									$total_percent += $percent;
									for ($x = 0; $x < $percent; $x++){
										array_push($percentage_array,$p);
									}
								}
							}
						}
					}
				}
				
				$no_result_percent = 100 - $total_percent;
				for ($x = 0; $x < $no_result_percent; $x++) {
					array_push($percentage_array,-1);
				}
				shuffle($percentage_array);


				//generate result
				$reveal_array = [];
				$select_array = [];
				foreach ($result_data->numbers as $value) {
					array_push($select_array,$value);
				}
				shuffle($select_array);

				$percent_index = $percentage_array[0];
				$number_index = 0;
				if($percent_index != -1){
					for ($p = 0; $p < $prize_json[$prize_index]->paytable[$percent_index]->hits; $p++){
						array_push($reveal_array,$select_array[$number_index]);
						$number_index++;
					}

					$total_left = $total_play - count($reveal_array);
					$number_index = 0;
					for ($i = 0; $i < $total_left; $i++){
						$arraykey = array_search($numbers_array[$number_index], $select_array);
						if($arraykey !== false) {
							
						}else{
							array_push($reveal_array,$numbers_array[$number_index]);
						}
						$number_index++;
					}
				}else{
					for ($i = 0; $i < count($numbers_array); $i++){
						$arraykey = array_search($numbers_array[$i], $result_data->numbers);
						if($arraykey !== false){
							
						}else{
							array_push($reveal_array,$numbers_array[$i]);
							if(count($reveal_array) == $total_play){
								$i = count($numbers_array);
							}
						}
					}
				}
			}else{
				$reveal_array = [];
				for ($i = 0; $i < $total_play; $i++){
					array_push($reveal_array,$numbers_array[$i]);
				}
			}

			//calculate
			$match_total = 0;
			for ($i = 0; $i < count($reveal_array); $i++){
				$arraykey = array_search($reveal_array[$i], $result_data->numbers);
				if($arraykey !== false){
					$match_total++;
				}
			}

			for ($i = 0; $i < count($prize_json); $i++){
				if($prize_json[$i]->play == $total_play){
					for ($p = 0; $p < count($prize_json[$i]->paytable); $p++){
						if($prize_json[$i]->paytable[$p]->hits == $match_total){
							$win_point = $prize_json[$i]->paytable[$p]->prize;
						}
					}
				}
			}
			
			$point_left = $member_point - $player_bet;
			if($point_left >= 0){
				$member_point -= $player_bet;
				$win_point = $win_point * $player_bet;
				$member_point += $win_point;
			}else{
				$result_valid_return = false;
			}

			$icon_output = '';
			foreach ($reveal_array as $value) {
				$icon_output = $icon_output.(string)$value.", ";
			}
			$icon_output = rtrim($icon_output, ", ");
			$result_output = '{"numbers":['.$icon_output.']}';
			$game_log_data = '{"type":"server", "status":"play", "current":{"member_point":'.$last_member_point.', "member_chance":'.$last_member_chance.', "member_score":'.$last_member_score.'}, "update":{"member_point":'.$member_point.', "member_chance":'.$member_chance.', "member_score":'.$member_score.'}, "win":'.$win_point.'}';
			
		}
	}else if($gameType == "horseracing"){
		$setting_names = array("gameSettings","horseSettings","betSettings");
		$settings_json = '';
		$horse_json = '';
		$bet_json = '';

		//retrieve data
		if(!empty($_REQUEST['result_data'])){
			$result_data = $_REQUEST['result_data'];
			$result_data = json_decode($result_data, false);
		}else{
			$result_return = false;
			$result_valid_return = false;
		}

		//load settings
		foreach ($setting_names as $value) {
			$stmt = $conn->prepare("SELECT setting_name, setting_value FROM $game_settings WHERE game_type = '$gameType' AND setting_status = 1 AND setting_name = '$value'");
			$stmt->execute();
			$stmt->store_result();
			$num_of_rows = $stmt->num_rows;
			$stmt -> bind_result($setting_name, $setting_value);
			$settings = [];
			while ($stmt->fetch()) {
				$settings[] = array(
					'setting_name' => $setting_name,
					'setting_value' => $setting_value
				);
			}
			$stmt->free_result();
			$stmt->close();

			if($num_of_rows > 0){
				if($settings_json == ''){
					$settings_json = json_decode($settings[0]['setting_value'], false);
				}else if($horse_json == ''){
					$horse_json = json_decode($settings[0]['setting_value'], false);
				}else if($bet_json == ''){
					$bet_json = json_decode($settings[0]['setting_value'], false);
				}
			}else{
				$result_return = false;
			}
		}

		$player_bet = $result_data->bets;

		$result_array = [];
		for ($i = 0; $i < count($horse_json); $i++){
			array_push($result_array,$i);
		}
		shuffle($result_array);
		
		if($result_return){
			if($settings_json->enablePercentage){
				//generate percent
				$percentage_array = [];
				for ($i = 0; $i < count($horse_json); $i++){
					$percent = $horse_json[$i]->percent;
					if(is_numeric($percent)){
						if($percent > 0){
							for ($x = 0; $x < $percent; $x++){
								array_push($percentage_array,$i);
							}
						}
					}
				}
				
				//generate result
				shuffle($percentage_array);
				$order_array = [];
				for ($i = 0; $i < count($horse_json); $i++){
					array_push($order_array,["index" => $i, "percent" => 0]);
				}

				for ($i = 0; $i < count($percentage_array); $i++){
					$horde_index = $percentage_array[$i];
					$order_array[$horde_index]['percent']++;
				}

				function sort_records(&$array,$index){
					return usort($array, function ($a, $b) use ($index) {
						if ( $a[$index] == $b[$index] )
							return 0;
						if ( $a[$index] > $b[$index] )
							return -1;
						return 1;
					});
				}
				sort_records($order_array, 'percent');

				$result_array = [];
				for ($i = 0; $i < count($order_array); $i++){
					array_push($result_array,$order_array[$i]['index']);
				}
			}

			//calculate
			$win_amount = 0;
			$bet_amount = 0;
			for ($i = 0; $i < count($player_bet); $i++){
				$bet_index = $player_bet[$i]->type;
				$bet_type = $bet_json[$bet_index]->type;
				$bet_amount += $player_bet[$i]->totalBet;

				if($bet_type == 'win'){
					if($result_array[0] == $player_bet[$i]->horse[0]){
						$win_amount += $horse_json[$player_bet[$i]->horse[0]]->odds[$bet_index] * $player_bet[$i]->totalBet;
					}
				}else if($bet_type == 'place'){
					if($result_array[0] == $player_bet[$i]->horse[0] || $result_array[1] == $player_bet[$i]->horse[0]){
						$win_amount += $horse_json[$player_bet[$i]->horse[0]]->odds[$bet_index] * $player_bet[$i]->totalBet;
					}
				}else if($bet_type == 'show'){
					if($result_array[0] == $player_bet[$i]->horse[0] || $result_array[1] == $player_bet[$i]->horse[0] || $result_array[2] == $player_bet[$i]->horse[0]){
						$win_amount += $horse_json[$player_bet[$i]->horse[0]]->odds[$bet_index] * $player_bet[$i]->totalBet;
					}
				}else if($bet_type == 'exacta'){
					if($result_array[0] == $player_bet[$i]->horse[0] && $result_array[1] == $player_bet[$i]->horse[1]){
						$win_amount += $bet_json[$bet_index]->payout;
					}
				}else if($bet_type == 'exactabox'){
					if($result_array[0] == $player_bet[$i]->horse[0] || $result_array[1] == $player_bet[$i]->horse[0]){
						if($result_array[0] == $player_bet[$i]->horse[1] || $result_array[1] == $player_bet[$i]->horse[1]){
							$win_amount += $bet_json[$bet_index]->payout;
						}
					}
				}else if($bet_type == 'trifecta'){
					if($result_array[0] == $player_bet[$i]->horse[0] && $result_array[1] == $player_bet[$i]->horse[1] && $result_array[2] == $player_bet[$i]->horse[2]){
						$win_amount += $bet_json[$bet_index]->payout;
					}
				}else if($bet_type == 'trifectabox'){
					if($result_array[0] == $player_bet[$i]->horse[0] || $result_array[1] == $player_bet[$i]->horse[0] || $result_array[2] == $player_bet[$i]->horse[0]){
						if($result_array[0] == $player_bet[$i]->horse[1] || $result_array[1] == $player_bet[$i]->horse[1] || $result_array[2] == $player_bet[$i]->horse[1]){
							if($result_array[0] == $player_bet[$i]->horse[2] || $result_array[1] == $player_bet[$i]->horse[2] || $result_array[2] == $player_bet[$i]->horse[2]){
								$win_amount += $bet_json[$bet_index]->payout;
							}
						}
					}
				}else if($bet_type == 'superfecta'){
					if($result_array[0] == $player_bet[$i]->horse[0] && $result_array[1] == $player_bet[$i]->horse[1] && $result_array[2] == $player_bet[$i]->horse[2] && $result_array[3] == $player_bet[$i]->horse[3]){
						$win_amount += $bet_json[$bet_index]->payout;
					}
				}else if($bet_type == 'superfectabox'){
					if($result_array[0] == $player_bet[$i]->horse[0] || $result_array[1] == $player_bet[$i]->horse[0] || $result_array[2] == $player_bet[$i]->horse[0] || $result_array[3] == $player_bet[$i]->horse[0]){
						if($result_array[0] == $player_bet[$i]->horse[1] || $result_array[1] == $player_bet[$i]->horse[1] || $result_array[2] == $player_bet[$i]->horse[1] || $result_array[3] == $player_bet[$i]->horse[1]){
							if($result_array[0] == $player_bet[$i]->horse[2] || $result_array[1] == $player_bet[$i]->horse[2] || $result_array[2] == $player_bet[$i]->horse[2] || $result_array[3] == $player_bet[$i]->horse[2]){
								if($result_array[0] == $player_bet[$i]->horse[3] || $result_array[1] == $player_bet[$i]->horse[3] || $result_array[2] == $player_bet[$i]->horse[3] || $result_array[3] == $player_bet[$i]->horse[3]){
									$win_amount += $bet_json[$bet_index]->payout;
								}
							}
						}
					}
				}
			}

			$win_point = round($win_amount);
			$point_left = $member_point - $bet_amount;
			if($point_left >= 0){
				$member_point -= $bet_amount;
				$member_point += round($win_point);
			}else{
				$result_valid_return = false;
			}

			$result_output = '';
			foreach ($result_array as $value) {
				$result_output = $result_output.(string)$value.", ";
			}
			$result_output = rtrim($result_output, ", ");
			$result_output = '{"numbers":['.$result_output.']}';
			$game_log_data = '{"type":"server", "status":"play", "current":{"member_point":'.$last_member_point.', "member_chance":'.$last_member_chance.', "member_score":'.$last_member_score.'}, "update":{"member_point":'.$member_point.', "member_chance":'.$member_chance.', "member_score":'.$member_score.'}, "win":'.$win_point.'}';
			
		}
	}else if($gameType == "luckyballs"){
		$setting_names = array("gameSettings","prizesSettings");
		$settings_json = '';
		$prizes_json = '';

		//retrieve data
		if(!empty($_REQUEST['result_data'])){
			$result_data = $_REQUEST['result_data'];
			$result_data = json_decode($result_data, false);
		}else{
			$result_return = false;
			$result_valid_return = false;
		}

		//load settings
		foreach ($setting_names as $value) {
			$stmt = $conn->prepare("SELECT setting_name, setting_value FROM $game_settings WHERE game_type = '$gameType' AND setting_status = 1 AND setting_name = '$value'");
			$stmt->execute();
			$stmt->store_result();
			$num_of_rows = $stmt->num_rows;
			$stmt -> bind_result($setting_name, $setting_value);
			$settings = [];
			while ($stmt->fetch()) {
				$settings[] = array(
					'setting_name' => $setting_name,
					'setting_value' => $setting_value
				);
			}
			$stmt->free_result();
			$stmt->close();

			if($num_of_rows > 0){
				if($settings_json == ''){
					$settings_json = json_decode($settings[0]['setting_value'], false);
				}else if($prizes_json == ''){
					$prizes_json = json_decode($settings[0]['setting_value'], false);
				}
			}else{
				$result_return = false;
			}
		}

		$player_bet = $result_data->bets;

		$numbers_array = [];
		for ($i = 1; $i < 48; $i++){
			array_push($numbers_array,$i);
		}
		shuffle($numbers_array);

		$result_array = [];
		for ($i = 0; $i < 35; $i++){
			array_push($result_array,$numbers_array[$i]);
		}
		shuffle($result_array);

		$bonus_temp_array = [];
		for ($i = 5; $i < count($result_array); $i++){
			array_push($bonus_temp_array,$result_array[$i]);
		}
		shuffle($bonus_temp_array);

		$bonus_array = [];
		for ($i = 0; $i < 2; $i++){
			array_push($bonus_array,$bonus_temp_array[$i]);
		}
		
		if($result_return){
			//results
			$total_odd = 0;
			$total_even = 0;
			$pre_ball_sum = 0;
			for ($i = 0; $i < count($result_array); $i++){
				if($result_array[$i] % 2 == 0){
					$total_even++;
				}else{
					$total_odd++;
				}

				if($i < 6){
					$pre_ball_sum += $result_array[$i];
				}
			}

			$first_ball_over_under = false;
			$pre_sum_over_under = false;
			$first_even_odd = false;
			$more_even_odd = false;

			$first_color = -1;
			$last_color = -1;
			
			if($result_array[0] > 24.5){
				$first_ball_over_under = true;
			}

			if($result_array[0] % 2 == 0){
				$first_even_odd = true;
			}

			if($total_odd < $total_even){
				$more_even_odd = true;
			}

			if($pre_ball_sum > 122.5){
				$pre_sum_over_under = true;
			}

			$ball_colors = [
				[1,9,17,25,33,41],
				[2,10,18,26,34,42],
				[3,11,19,27,35,43],
				[4,12,20,28,36,44],
				[5,13,21,29,37,45],
				[6,14,22,30,38,46],
				[7,15,23,31,39,47],
				[8,16,24,32,40,48],
			];

			for ($i = 0; $i < count($ball_colors); $i++){
				$arraykey = array_search($result_array[0], $ball_colors[$i]);
				if($arraykey !== false){
					$first_color = $i;
				}

				$arraykey = array_search($result_array[count($result_array)-1], $ball_colors[$i]);
				if($arraykey !== false){
					$last_color = $i;
				}
			}

			//calculate
			$win_amount = 0;
			$bet_amount = 0;
			for ($i = 0; $i < count($player_bet); $i++){
				$bet_type = $player_bet[$i]->type;
				$bet_special_type = $player_bet[$i]->special;
				$bet_amount += $player_bet[$i]->bet;

				if($bet_type == 0){
					$bonus_multiply = 1;
					$matched = 0;
					
					for ($s = 0; $s < count($player_bet[$i]->numbers); $s++){
						$arraykey = array_search($player_bet[$i]->numbers[$s], $result_array);
						if($arraykey !== false){
							$matched++;
						}

						$arraykey = array_search($player_bet[$i]->numbers[$s], $bonus_array);
						if($arraykey !== false){
							$bonus_multiply++;
						}
					}

					$win_rate = $prizes_json->totalWinRate[$matched-6];
					$last_index = -1;

					for ($s = count($result_array)-1; $s >= 0; $s--){
						$arraykey = array_search($result_array[$s], $player_bet[$i]->numbers);
						if($arraykey !== false){
							$last_index = $s;
							$s = -1;
						}
					}

					$win_prize = $prizes_json->numbers[$last_index-5];
					if($win_prize > 0 && $matched >= 6){
						$win_amount += ($player_bet[$i]->bet * ($win_rate * ($win_prize * $bonus_multiply)));
					}
				}else if($bet_type == 1){
					$win_rate = 0;
					$bet_side = $player_bet[$i]->side;

					if($bet_special_type == 0){
						if($bet_side == $first_ball_over_under){
							$side_index = $bet_side == true ? 1 : 0;
							$win_rate = $prizes_json->specials[$bet_special_type][$side_index];
						}
					}else if($bet_special_type == 1){
						if($bet_side == $pre_sum_over_under){
							$side_index = $bet_side == true ? 1 : 0;
							$win_rate = $prizes_json->specials[$bet_special_type][$side_index];
						}
					}else if($bet_special_type == 2){
						$arraykey = array_search($first_color, $player_bet[$i]->colors);
						if($arraykey !== false){
							$color_index = count($player_bet[$i]->colors)-1;
							$color_index = $color_index == 3 ? 2 : $color_index;
							$win_rate = $prizes_json->specials[$bet_special_type][$color_index];
						}
					}else if($bet_special_type == 3){
						$arraykey = array_search($last_color, $player_bet[$i]->colors);
						if($arraykey !== false){
							$color_index = count($player_bet[$i]->colors)-1;
							$color_index = $color_index == 3 ? 2 : $color_index;
							$win_rate = $prizes_json->specials[$bet_special_type][$color_index];
						}
					}else if($bet_special_type == 4){
						if($bet_side == $first_even_odd){
							$side_index = $bet_side == true ? 1 : 0;
							$win_rate = $prizes_json->specials[$bet_special_type][$side_index];
						}
					}else if($bet_special_type == 5){
						if($bet_side == $more_even_odd){
							$side_index = $bet_side == true ? 1 : 0;
							$win_rate = $prizes_json->specials[$bet_special_type][$side_index];
						}
					}

					if($win_rate > 0){
						$win_amount = ($player_bet[$i]->bet * $win_rate);
					}
				}
			}

			$win_point = round($win_amount);
			$point_left = $member_point - $bet_amount;
			if($point_left >= 0){
				$member_point -= $bet_amount;
				$member_point += round($win_point);
			}else{
				$result_valid_return = false;
			}

			$result_output = '';
			foreach ($result_array as $value) {
				$result_output = $result_output.(string)$value.", ";
			}
			$result_bonus_output = '';
			foreach ($bonus_array as $value) {
				$result_bonus_output = $result_bonus_output.(string)$value.", ";
			}
			$result_output = rtrim($result_output, ", ");
			$result_bonus_output = rtrim($result_bonus_output, ", ");
			$result_output = '{"numbers":['.$result_output.'], "bonus":['.$result_bonus_output.']}';
			$game_log_data = '{"type":"server", "status":"play", "current":{"member_point":'.$last_member_point.', "member_chance":'.$last_member_chance.', "member_score":'.$last_member_score.'}, "update":{"member_point":'.$member_point.', "member_chance":'.$member_chance.', "member_score":'.$member_score.'}, "win":'.$win_point.'}';
			
		}
	}

	if($result_return && $result_valid_return){
		if($testMode){
			echo '{"status":true, "token":"'.$_SESSION['Token'].'", "result":'.$result_output.', "member_point":'.$member_point.', "member_chance":'.$member_chance.', "member_score":'.$member_score.', "win":'.$win_point.', "debug":true, "message":"'.$lang['server-points-updated'].'"}';
		}else{
			if(updateMemberPoints($member_point, $member_chance, $member_score, $_SESSION['Member_ID'], $gameType)){
				createGameLogs($gameType, $_SESSION['Member_ID'], $game_log_data);

				$_SESSION['Token'] = getToken(30);
				echo '{"status":true, "token":"'.$_SESSION['Token'].'", "result":'.$result_output.', "member_point":'.$member_point.', "member_chance":'.$member_chance.', "member_score":'.$member_score.', "win":'.$win_point.', "debug":"'.$debug_output.'", "message":"'.$lang['server-points-updated'].'"}';
			}else{
				echo '{"status":false, "message":"'.$lang['server-no-record'].'"}';
			}
		}
	}else{
		if(!$result_valid_return){
			echo '{"status":false, "message":"'.$lang['server-invalid-result'].'"}';
		}else{
			echo '{"status":false, "message":"'.$lang['server-no-result'].'"}';
		}
	}
}else{
	echo '{"status":false, "message":"'.$lang['server-error'].'"}';	
}

// Close connection
mysqli_close($conn);