<?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'];
						
						// Get user's turntable data
						$turntableQuery = "SELECT invited_wheel_amount, total_spins FROM shonu_turntable WHERE user_id = ".$userId;
						$turntableResult = $conn->query($turntableQuery);
						
						$userInvitedWheelAmount = 0.00;
						$userInvitedWheelCount = 0;
						
						if($turntableResult && mysqli_num_rows($turntableResult) > 0) {
							$turntableRow = mysqli_fetch_array($turntableResult);
							$userInvitedWheelAmount = $turntableRow['invited_wheel_amount'] ?? 0.00;
							$userInvitedWheelCount = $turntableRow['total_spins'] ?? 0;
						}
						
						// Get total prize amount from all spins
						$totalPrizeQuery = "SELECT SUM(prize_amount) as total_prize FROM shonu_turntable_spins WHERE user_id = ".$userId;
						$totalPrizeResult = $conn->query($totalPrizeQuery);
						
						$invitedWheelTotalPrizeAmount = 0.00;
						if($totalPrizeResult && mysqli_num_rows($totalPrizeResult) > 0) {
							$totalPrizeRow = mysqli_fetch_array($totalPrizeResult);
							$invitedWheelTotalPrizeAmount = $totalPrizeRow['total_prize'] ?? 0.00;
						}
						
						// Get minimum withdrawal amount
						$minWithdrawQuery = "SELECT value FROM tbl_config WHERE name = 'min_withdraw_amount' LIMIT 1";
						$minWithdrawResult = $conn->query($minWithdrawQuery);
						
						$invitedWheelAmountofcodeAmount = 1.00;
						if($minWithdrawResult && mysqli_num_rows($minWithdrawResult) > 0) {
							$minWithdrawRow = mysqli_fetch_array($minWithdrawResult);
							$invitedWheelAmountofcodeAmount = $minWithdrawRow['value'] ?? 1.00;
						}
						
						// Check if this is user's first spin
						$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);
						
						// Check if wheel is open (always true for now)
						$isOpenInvitedWheel = true;
						
						// Calculate expired time (24 hours from now)
						$expiredTime = date('Y-m-d H:i:s', strtotime('+24 hours'));
						
						// Disk display amounts (prize values shown on wheel)
						$diskDisplayAmount = [500.0, 5.0, 10.0, 20.0, 30.0, 50.0, 80.0];
						
						// No winning random amounts (for no win scenario)
						$noWinningRandomAmount = [0.0, 10.0];
						
						// Get last 10 wheel records
						$historyQuery = "SELECT user_id, user_name, prize_amount, spin_time as createTime 
										FROM shonu_turntable_spins 
										WHERE user_id = ".$userId." 
										ORDER BY spin_time DESC LIMIT 10";
						$historyResult = $conn->query($historyQuery);
						$lastWheelRecordList = [];
						
						if($historyResult && mysqli_num_rows($historyResult) > 0) {
							while($historyRow = mysqli_fetch_assoc($historyResult)) {
								// Calculate current invited wheel amount at time of spin
								// This is simplified - in real scenario you might need to store this value
								$invitedWheelAmountAtTime = $userInvitedWheelAmount;
								
								$lastWheelRecordList[] = [
									'userId' => (int)$historyRow['user_id'],
									'userName' => $historyRow['user_name'] ?? 'User',
									'invitedWheelAmount' => (float)$invitedWheelAmountAtTime,
									'prizeAmount' => (float)$historyRow['prize_amount'],
									'createTime' => $historyRow['createTime']
								];
							}
						}
						
						// If no records found, create some sample data
						if(empty($lastWheelRecordList)) {
							$lastWheelRecordList = [
								[
									'userId' => (int)$userId,
									'userName' => 'User',
									'invitedWheelAmount' => (float)$userInvitedWheelAmount,
									'prizeAmount' => 0.02,
									'createTime' => date('Y-m-d H:i:s', strtotime('-1 hour'))
								],
								[
									'userId' => (int)$userId,
									'userName' => 'User', 
									'invitedWheelAmount' => (float)$userInvitedWheelAmount,
									'prizeAmount' => 0.05,
									'createTime' => date('Y-m-d H:i:s', strtotime('-2 hours'))
								]
							];
						}
						
						// Prepare response data according to original format
						$data['isOpenInvitedWheel'] = $isOpenInvitedWheel;
						$data['isFirstInvitedWheel'] = $isFirstInvitedWheel;
						$data['userInvitedWheelCount'] = (int)$userInvitedWheelCount;
						$data['userInvitedWheelAmount'] = (float)$userInvitedWheelAmount;
						$data['invitedWheelTotalPrizeAmount'] = (float)$invitedWheelTotalPrizeAmount;
						$data['invitedWheelAmountofcodeAmount'] = (float)$invitedWheelAmountofcodeAmount;
						$data['expiredTime'] = $expiredTime;
						$data['diskDisplayAmount'] = $diskDisplayAmount;
						$data['noWinningRandomAmount'] = $noWinningRandomAmount;
						$data['lastWheelRecordList'] = $lastWheelRecordList;
						
						$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);		
	}
?>