<?php 
	include "../../conn.php";
	include "../../functions2.php";
	
	header('Content-Type: application/json; charset=utf-8');
	header('Strict-Transport-Security: max-age=31536000');
	header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
	header('Access-Control-Allow-Credentials: true');
	$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
	header('Access-Control-Allow-Origin: ' . $origin);
	header('vary: Origin');
	
	date_default_timezone_set("Asia/Kolkata");
	$shnunc = date("Y-m-d H:i:s");
	$res = [
		'code' => 11,
		'msg' => 'Method not allowed',
		'msgCode' => 12,
		'serviceNowTime' => $shnunc,
	];
	$shonubody = file_get_contents("php://input");
	$shonupost = json_decode($shonubody, true);
	
	if ($_SERVER['REQUEST_METHOD'] != 'GET') {
		if (isset($shonupost['language']) && isset($shonupost['random']) && isset($shonupost['signature']) && isset($shonupost['timestamp'])) {
			$language = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['language']));
			$random = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['random']));
			$signature = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['signature']));
			$shonustr = '{"language":'.$language.',"random":"'.$random.'"}';
			$shonusign = strtoupper(md5($shonustr));
			if($shonusign == $signature){
				$bearer = explode(" ", $_SERVER['HTTP_AUTHORIZATION']);
				$author = $bearer[1];				
				$is_jwt_valid = is_jwt_valid($author);
				$data_auth = json_decode($is_jwt_valid, 1);
				if($data_auth['status'] === 'Success') {
					$sesquery = "SELECT akshinak FROM shonu_subjects WHERE akshinak = '$author'";
					$sesresult = $conn->query($sesquery);
					$sesnum = mysqli_num_rows($sesresult);
					if($sesnum == 1){
					    $userId = $data_auth['payload']['id'];
						
						// Check if user exists in turntable table, if not create entry
						$checkTurntableQuery = "SELECT id FROM shonu_turntable WHERE user_id = ".$userId;
						$checkTurntableResult = $conn->query($checkTurntableQuery);
						
						if(mysqli_num_rows($checkTurntableResult) == 0) {
							$insertTurntableQuery = "INSERT INTO shonu_turntable (user_id, invited_wheel_amount, total_spins) VALUES ($userId, 0.00, 0)";
							$conn->query($insertTurntableQuery);
						}
						
						// Check daily spin limit
						$dailyLimitQuery = "SELECT value FROM tbl_config WHERE name = 'daily_spin_limit'";
						$dailyLimitResult = $conn->query($dailyLimitQuery);
						$dailyLimit = 10; // Default
						if($dailyLimitResult && mysqli_num_rows($dailyLimitResult) > 0) {
							$limitRow = mysqli_fetch_array($dailyLimitResult);
							$dailyLimit = (int)$limitRow['value'];
						}
						
						// Get today's spin count
						$today = date('Y-m-d');
						$todaySpinsQuery = "SELECT COUNT(*) as today_spins FROM shonu_turntable_spins 
										   WHERE user_id = $userId AND DATE(spin_time) = '$today'";
						$todaySpinsResult = $conn->query($todaySpinsQuery);
						$todaySpinsRow = mysqli_fetch_array($todaySpinsResult);
						$todaySpinsCount = $todaySpinsRow['today_spins'];
						
						if($todaySpinsCount >= $dailyLimit) {
							// Daily limit reached
							$res['code'] = 8;
							$res['msg'] = 'Daily spin limit reached';
							$res['msgCode'] = 9;
							http_response_code(200);
							echo json_encode($res);
							exit();
						}
						
						// Check if this is user's first spin ever
						$firstSpinQuery = "SELECT COUNT(*) as total_spins FROM shonu_turntable_spins WHERE user_id = $userId";
						$firstSpinResult = $conn->query($firstSpinQuery);
						$firstSpinRow = mysqli_fetch_array($firstSpinResult);
						$isFirstInvitedWheel = ($firstSpinRow['total_spins'] == 0);
						
						// Prize configuration based on original JavaScript probabilities
						// Small amounts with higher probability of winning small prizes
						$prizes = [
							['amount' => 0.02, 'probability' => 0.35, 'isWin' => true],
							['amount' => 0.05, 'probability' => 0.25, 'isWin' => true],
							['amount' => 0.10, 'probability' => 0.15, 'isWin' => true],
							['amount' => 0.20, 'probability' => 0.10, 'isWin' => true],
							['amount' => 0.50, 'probability' => 0.08, 'isWin' => true],
							['amount' => 1.00, 'probability' => 0.05, 'isWin' => true],
							['amount' => 2.00, 'probability' => 0.02, 'isWin' => true],
							['amount' => 0.00, 'probability' => 0.00, 'isWin' => false] // No win
						];
						
						// Determine prize based on probability (JavaScript logic)
						$random = mt_rand() / mt_getrandmax(); // 0 to 1
						$cumulativeProbability = 0;
						$selectedPrize = null;
						
						foreach ($prizes as $prize) {
							$cumulativeProbability += $prize['probability'];
							if ($random <= $cumulativeProbability) {
								$selectedPrize = $prize;
								break;
							}
						}
						
						if($selectedPrize === null) {
							// Fallback to no win
							$selectedPrize = ['amount' => 0.00, 'isWin' => false];
						}
						
						$prizeAmount = $selectedPrize['amount'];
						$isWin = $selectedPrize['isWin'];
						
						// Get user details for history
						$userQuery = "SELECT codechorkamukala FROM shonu_subjects WHERE id = $userId";
						$userResult = $conn->query($userQuery);
						$userRow = mysqli_fetch_array($userResult);
						$userName = $userRow['codechorkamukala'] ?? 'User';
						
						// Only record and update balances if user actually won
						if($isWin && $prizeAmount > 0) {
							// Record the spin
							$spinTime = date('Y-m-d H:i:s');
							$insertSpinQuery = "INSERT INTO shonu_turntable_spins (user_id, prize_amount, spin_time, user_name) 
											   VALUES ($userId, $prizeAmount, '$spinTime', '$userName')";
							$conn->query($insertSpinQuery);
							
							// Update user's turntable data
							$updateTurntableQuery = "UPDATE shonu_turntable 
													SET invited_wheel_amount = invited_wheel_amount + $prizeAmount, 
														total_spins = total_spins + 1,
														updated_at = NOW()
													WHERE user_id = $userId";
							$conn->query($updateTurntableQuery);
							
							// Update user's main balance in shonu_kaichila
							$updateBalanceQuery = "UPDATE shonu_kaichila 
												  SET motta = motta + $prizeAmount,
													  updated_at = NOW()
												  WHERE balakedara = $userId";
							$conn->query($updateBalanceQuery);
						} else {
							// Record spin with 0 amount for history
							$spinTime = date('Y-m-d H:i:s');
							$insertSpinQuery = "INSERT INTO shonu_turntable_spins (user_id, prize_amount, spin_time, user_name) 
											   VALUES ($userId, 0.00, '$spinTime', '$userName')";
							$conn->query($insertSpinQuery);
							
							// Still update spin count
							$updateTurntableQuery = "UPDATE shonu_turntable 
													SET total_spins = total_spins + 1,
														updated_at = NOW()
													WHERE user_id = $userId";
							$conn->query($updateTurntableQuery);
						}
						
						// Prepare first invited wheel data if it's first spin
						$firstInvitedWheelDatas = null;
						if($isFirstInvitedWheel && $isWin) {
							// For first spin, create some sample gift data
							$firstInvitedWheelDatas = [
								['amount' => $prizeAmount, 'isSelected' => true],
								['amount' => 0.50, 'isSelected' => false],
								['amount' => 0.25, 'isSelected' => false],
								['amount' => 0.10, 'isSelected' => false]
							];
						}
						
						// Prepare response data according to original format
						$data['isFirstInvitedWheel'] = $isFirstInvitedWheel;
						$data['prizeAmount'] = (float)$prizeAmount;
						$data['isWin'] = $isWin;
						$data['firstInvitedWheelDatas'] = $firstInvitedWheelDatas;
						
						$res['data'] = $data;
						$res['code'] = 0;
						$res['msg'] = 'Succeed';
						$res['msgCode'] = 0;
						$res['serviceNowTime'] = $shnunc;
						http_response_code(200);
						echo json_encode($res);					
					}
					else{
						$res['code'] = 4;
						$res['msg'] = 'No operation permission';
						$res['msgCode'] = 2;
						http_response_code(401);
						echo json_encode($res);
					}					
				}
				else{					
					$res['code'] = 4;
					$res['msg'] = 'No operation permission';
					$res['msgCode'] = 2;
					http_response_code(401);
					echo json_encode($res);					
				}
			}
			else{
				$res['code'] = 5;
				$res['msg'] = 'Wrong signature';
				$res['msgCode'] = 3;
				http_response_code(200);
				echo json_encode($res);				
			}
		}
		else{
			$res['code'] = 7;
			$res['msg'] = 'Param is Invalid';
			$res['msgCode'] = 6;
			http_response_code(200);
			echo json_encode($res);			
		}		
	}
	else{
		$res['code'] = 11;
		$res['msg'] = 'Method not allowed';
		$res['msgCode'] = 12;
		http_response_code(405);
		echo json_encode($res);		
	}
?>