<?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);
	
	function replaceWithAsterisks($inputString) {
		if (strlen($inputString) < 10) {
			return $inputString;
		}
		$before = substr($inputString, 0, 6);
		$toReplace = substr($inputString, 6, 4);
		$after = substr($inputString, 10);
		$replaced = str_repeat('*', strlen($toReplace));
		$resultString = $before . $replaced . $after;
		return $resultString;
	}
	
	
	if ($_SERVER['REQUEST_METHOD'] != 'GET') {
		if (isset($shonupost['language']) && isset($shonupost['random']) && isset($shonupost['signature']) && isset($shonupost['timestamp']) && isset($shonupost['withdrawid'])) {
			$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']));
			$withdrawid = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['withdrawid']));
			$shonustr = '{"language":'.$language.',"random":"'.$random.'","withdrawid":'.$withdrawid.'}';
			$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){
						$shonuid = $data_auth['payload']['id'];
						
						// ----------------- REPLACED BLOCK: improved bank type lookup -----------------
						if($withdrawid == 1){
							$samasye = "SELECT phalanubhavi
							  FROM khate WHERE byabaharkarta = $shonuid AND khatehesaru != 'TRC'
							  ORDER BY shonu DESC LIMIT 1";
							$samasyephalitansa = $conn->query($samasye);
							$samasyephalitansa_dhadi = mysqli_num_rows($samasyephalitansa);	
							if($samasyephalitansa_dhadi >= 1){
								$samasyephalitansa_sreni = mysqli_fetch_array($samasyephalitansa);						
								$data['lastBandCarkName'] = $samasyephalitansa_sreni['phalanubhavi'];
								
								$samasye = "SELECT shonu, khatehesaru, khatesankhye, kod, duravani
								  FROM khate WHERE byabaharkarta = $shonuid AND khatehesaru != 'TRC'
								  ORDER BY shonu DESC";
								$samasyephalitansa = $conn->query($samasye);
								$i = 0;
								while($row = mysqli_fetch_array($samasyephalitansa)){
									$data['withdrawalslist'][$i]['bid'] = $row['shonu'];
									$data['withdrawalslist'][$i]['bankName'] = $row['khatehesaru'];
									$data['withdrawalslist'][$i]['beneficiaryName'] = '';
									
									$data['withdrawalslist'][$i]['accountNo'] = replaceWithAsterisks($row['khatesankhye']);
									$data['withdrawalslist'][$i]['ifsCode'] = $row['kod'];
									$data['withdrawalslist'][$i]['withType'] = 1;
									$data['withdrawalslist'][$i]['mobileNo'] = replaceWithAsterisks($row['duravani']);
									$data['withdrawalslist'][$i]['bankProvince'] = '';
									$data['withdrawalslist'][$i]['bankCity'] = '';
									$data['withdrawalslist'][$i]['bankAddress'] = '';
									$i++;
								}
							}
							else{
								$data['lastBandCarkName'] = null;
								$data['withdrawalslist'] = [];
							}
						}
						// ----------------- END REPLACED BLOCK -----------------
						elseif($withdrawid == 3){
							$samasye = "SELECT *
							  FROM bankcard WHERE userid = '$shonuid' AND type = '3'
							  ORDER BY id DESC LIMIT 1 ";
							$samasyephalitansa = $conn->query($samasye);
							$samasyephalitansa_dhadi = mysqli_num_rows($samasyephalitansa);	
							if($samasyephalitansa_dhadi >= 1){
								$samasyephalitansa_sreni = mysqli_fetch_array($samasyephalitansa);						
								$data['lastBandCarkName'] = $samasyephalitansa_sreni['phalanubhavi'];
								
								$samasye = "SELECT *
								 FROM bankcard WHERE userid = $shonuid AND type = '3'
							     ORDER BY id DESC LIMIT 1";
								$samasyephalitansa = $conn->query($samasye);
								$i = 0;
								while($row = mysqli_fetch_array($samasyephalitansa)){
									$data['withdrawalslist'][$i]['bid'] =(int)$row['id'];
									$data['withdrawalslist'][$i]['bankName'] = "USDT";
									$data['withdrawalslist'][$i]['beneficiaryName'] =replaceWithAsterisks($row['account']);
									
									$data['withdrawalslist'][$i]['accountNo'] = replaceWithAsterisks($row['account']);
									$data['withdrawalslist'][$i]['ifsCode'] = replaceWithAsterisks($row['account']);
									$data['withdrawalslist'][$i]['withType'] = 1;
									$data['withdrawalslist'][$i]['mobileNo'] = replaceWithAsterisks($row['account']);
									$data['withdrawalslist'][$i]['bankProvince'] = '';
									$data['withdrawalslist'][$i]['bankCity'] = '';
									$data['withdrawalslist'][$i]['bankAddress'] = '';
									$i++;
								}
							}
							else{
								$data['lastBandCarkName'] = null;
								$data['withdrawalslist'] = [];
							}
						}
						
$samasye_1 = "SELECT shonu
              FROM hintegedukolli 
              WHERE balakedara = '".$shonuid."' 
              AND DATE(dinankavannuracisi) = date('".$shnunc."')";
              
$samasyephalitansa_1 = $conn->query($samasye_1);
$shelly = mysqli_num_rows($samasyephalitansa_1);
if ($withdrawid == 3) {
    $shelly_1 = 5 - $shelly;
} elseif ($withdrawid == 4) {
    $shelly_1 = 3 - $shelly;
}

$minRechargeQuery = "SELECT min_withdrawal FROM web_setting LIMIT 1";
$minRechargeResult = $conn->query($minRechargeQuery);

if ($minRechargeResult && $minRechargeResult->num_rows > 0) { 
    $row = $minRechargeResult->fetch_assoc(); 
    $amount = $row['min_withdrawal']; 
} else { 
    $amount = 500; // Default value if no data found 
}




$userid = $data_auth['payload']['id'];

$balquery = "SELECT * FROM shonu_kaichila WHERE balakedara = " . (int)$data_auth['payload']['id'] . " LIMIT 1";
$balresult = $conn->query($balquery);
$balarr = mysqli_fetch_array($balresult);
$walletBalance = isset($balarr['motta']) ? (float)$balarr['motta'] : 0;

// Need to bet /Turnover
$needtobetx = isset($balarr['mottta']) ? (float)$balarr['mottta'] : 0;



// USDT rate from DB

$uRate = 300;
// $rateQuery = "SELECT rate FROM tbl_pg WHERE value = 'usdt' AND status = 1 LIMIT 1";
// $rateResult = $conn->query($rateQuery);
// if ($rateResult && $rateResult->num_rows > 0) {
//     $rateRow = $rateResult->fetch_assoc();
//     $uRate = (float)$rateRow['rate'];
// } else {
//     $uRate = 300; // fallback default
// }


// Fetch user summary
$userid = (int)$data_auth['payload']['id'];
$summaryRes = mysqli_query($conn, "SELECT * FROM user_withdraw_summary WHERE user_id = '$userid'");
$summary = mysqli_fetch_assoc($summaryRes);

$minPriceToUse = ($withdrawid == 3) ? 3000 : (float)$amount;
$maxPriceToUse = ($withdrawid == 3) ? 1000000 : 50000;
$manualEnabled = false;
if ($summary && isset($summary['manual_override'])) {
    $manualEnabled = (bool)$summary['manual_override'];
}

$canwithdraw_amount = 0;
if($needtobetx==0 || $needtobetx =='0'){
    $canwithdraw_amount = $walletBalance;
}

if ($manualEnabled) {
    $data["withdrawalsrule"] = [
        "withdrawCount" => $shelly_1,
        "withdrawRemainingCount" => $shelly_1,
        // "withdrawRemainingCount" => (int)$summary['withdraw_remaining_times'],
        // "startTime" => (string)($summary['withdraw_start_time'] ?? "00:00"),
        // "endTime" => (string)($summary['withdraw_end_time'] ?? "23:59"),
        "startTime" => "00:00",
        "endTime" => "23:59",
        "fee" => 0,
        "minPrice" => $minPriceToUse,
        "maxPrice" => $maxPriceToUse,
        "amount" => $walletBalance,
        "amountofCode" => (float)$needtobetx,                          
        "canWithdrawAmount" => $canwithdraw_amount, 
        "c2cUnitAmount" => 0,
        "uRate" => $uRate,
        "uGold" => 0,
        "needBet" => (float)$needtobetx,
        "mode" => "manual",
        "manualUpdatedAt" => $summary['manual_updated_at'] ?? null
    ];
} else {
    $defaultRemaining = isset($shelly_1) ? (int)$shelly_1 : 3;
    $data["withdrawalsrule"] = [
        "withdrawCount" => $shelly_1,
        "withdrawRemainingCount" => $shelly_1,
        "startTime" => "00:00",
        "endTime" => "23:59",
        "fee" => 0,
        "minPrice" => $minPriceToUse,
        "maxPrice" => $maxPriceToUse,
        "amount" => $walletBalance,
        "amountofCode" => (float)$needtobetx,
        "canWithdrawAmount" => $canwithdraw_amount,
        "c2cUnitAmount" => 0,
        "uRate" => $uRate,
        "uGold" => 0,
        // needBet still returned (from shonu_kaichila.mottta) so client can decide UI or messaging
        "needBet" => (float)$needtobetx,
        "mode" => "auto",
        "note" => "Automatic rules applied. No manual override enabled for this user."
    ];
}


// Also include direct balance if needed
$data['amount'] = $walletBalance;

						
						$res['data'] = $data;
						$res['code'] = 0;
						$res['msg'] = 'Succeed';
						$res['msgCode'] = 0;
						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 {		
		http_response_code(405);
		echo json_encode($res);
	}
?>
