<?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['amount']) && isset($shonupost['bid']) && isset($shonupost['language']) && isset($shonupost['pwd']) && isset($shonupost['random']) && isset($shonupost['signature']) && isset($shonupost['timestamp']) && isset($shonupost['type'])) {
			$amount = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['amount']));
			$bid = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['bid']));
			$language = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['language']));			
			$pwd = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['pwd']));			
			$random = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['random']));
			$signature = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['signature']));
			$type = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['type']));
			
			// Recreate signature string (kept same as original)
			$shonustr = '{"amount":'.$amount.',"bid":"'.$bid.'","language":'.$language.',"pwd":"'.$pwd.'","random":"'.$random.'","type":'.$type.'}';
			$shonusign = strtoupper(md5($shonustr));
			
			if ($shonusign) {
				// Authorization & JWT
				$bearer = explode(" ", isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : '');
				$author = isset($bearer[1]) ? $bearer[1] : (isset($bearer[0]) ? $bearer[0] : '');
				$is_jwt_valid = is_jwt_valid($author);
				$data_auth = json_decode($is_jwt_valid, true);
				if ($data_auth['status'] === 'Success') {
					$shonuid = intval($data_auth['payload']['id']);
					
					// fetch stored password for user
				    $user_query = "SELECT password FROM shonu_subjects WHERE id = ?";
					if ($stmt = mysqli_prepare($conn, $user_query)) {
					    mysqli_stmt_bind_param($stmt, "i", $shonuid);
					    mysqli_stmt_execute($stmt);
					    $user_result = mysqli_stmt_get_result($stmt);
					    $user_arr = mysqli_fetch_array($user_result);
					    mysqli_stmt_close($stmt);
					} else {
					    $user_arr = [];
					}

					// password check
				    if (!isset($user_arr['password']) || md5($pwd) != $user_arr['password']) {
				        $res['code'] = -9;
						$res['msg'] = 'Wrong password Entered';
						$res['msgCode'] = 0;
						http_response_code(200);
						echo json_encode($res);
						mysqli_close($conn);
    				    exit;
				    }

					// DAILY LIMIT: how many withdraws today?
	                $samasye_1 = "SELECT shonu FROM hintegedukolli WHERE balakedara = ? AND DATE(dinankavannuracisi) = DATE(?)";
					if ($stmt = mysqli_prepare($conn, $samasye_1)) {
					    mysqli_stmt_bind_param($stmt, "is", $shonuid, $shnunc);
					    mysqli_stmt_execute($stmt);
					    $samasyephalitansa_1 = mysqli_stmt_get_result($stmt);
					    $shelly = $samasyephalitansa_1 ? mysqli_num_rows($samasyephalitansa_1) : 0;
					    mysqli_stmt_close($stmt);
					} else {
					    // fallback
					    $samasyephalitansa_1 = $conn->query("SELECT shonu FROM hintegedukolli WHERE balakedara = '$shonuid' AND DATE(dinankavannuracisi) = DATE('".$shnunc."')");
					    $shelly = $samasyephalitansa_1 ? mysqli_num_rows($samasyephalitansa_1) : 0;
					}
                    
                    $shelly_1 = 3 - $shelly;
                    
                    if ($shelly_1 <= 0) {
						$res['code'] = -9;
						$res['msg'] = 'No more withdraw request available today';
						$res['msgCode'] = 0;
						http_response_code(200);
						echo json_encode($res);
						mysqli_close($conn);
						exit;
                    }

                    // ******** NEW: check if user has any EXISTING pending withdrawal (sthiti = 0)
                    $pending_check_sql = "SELECT COUNT(*) AS cnt FROM hintegedukolli WHERE balakedara = ? AND sthiti = 0";
                    $has_pending = 0;
                    if ($stmt = mysqli_prepare($conn, $pending_check_sql)) {
                        mysqli_stmt_bind_param($stmt, "i", $shonuid);
                        mysqli_stmt_execute($stmt);
                        $res_pending = mysqli_stmt_get_result($stmt);
                        if ($res_pending && $rowp = mysqli_fetch_assoc($res_pending)) {
                            $has_pending = intval($rowp['cnt']);
                        }
                        mysqli_stmt_close($stmt);
                    } else {
                        // on DB failure, be conservative and prevent new request
                        error_log("Failed to prepare pending_check_sql: " . mysqli_error($conn));
                        $has_pending = 1;
                    }

                    if ($has_pending > 0) {
                        // user has at least one pending request -> do not allow new add
                        $res['code'] = -9;
						$res['msg'] = 'Your previous withdrawal request in on pending.Please wait for the existing withdrawal';
						$res['msgCode'] = 0;
						http_response_code(200);
						echo json_encode($res);
						exit;
                    }
                    // ******** END NEW LOGIC

					// Check if user is a demo user
					$checkDemoQuery = "SELECT 1 FROM demo WHERE balakedara = ?";
					$isDemoUser = false;
					if ($stmt = mysqli_prepare($conn, $checkDemoQuery)) {
						mysqli_stmt_bind_param($stmt, "i", $shonuid);
						mysqli_stmt_execute($stmt);
						$r = mysqli_stmt_get_result($stmt);
						$isDemoUser = ($r && mysqli_num_rows($r) > 0);
						mysqli_stmt_close($stmt);
					} else {
						// fallback
						$isDemoUser = mysqli_num_rows($conn->query("SELECT 1 FROM demo WHERE balakedara = '$shonuid'")) > 0;
					}

					// fetch balance
					$balquery = "SELECT motta FROM shonu_kaichila WHERE balakedara = ?";
					$balarr = null;
					if ($stmt = mysqli_prepare($conn, $balquery)) {
						mysqli_stmt_bind_param($stmt, "i", $shonuid);
						mysqli_stmt_execute($stmt);
						$resbal = mysqli_stmt_get_result($stmt);
						$balarr = $resbal ? mysqli_fetch_array($resbal) : null;
						mysqli_stmt_close($stmt);
					} else {
						$resbal = $conn->query("SELECT motta FROM shonu_kaichila WHERE balakedara = '$shonuid'");
						$balarr = $resbal ? mysqli_fetch_array($resbal) : null;
					}

					// Validate amount range and balance
					if ($amount >= 110 && $amount <= 50000 ) {
					    if ($balarr !== null && $amount <= $balarr['motta']) {
					        // deduct balance and insert withdrawal request inside transaction to avoid races
					        mysqli_begin_transaction($conn);
					        $mottanutan = $balarr['motta'] - $amount;

					        $upd = "UPDATE shonu_kaichila SET motta = ? WHERE balakedara = ?";
					        $ok_upd = false;
					        if ($ustmt = mysqli_prepare($conn, $upd)) {
					            mysqli_stmt_bind_param($ustmt, "di", $mottanutan, $shonuid);
					            $ok_upd = mysqli_stmt_execute($ustmt);
					            if (!$ok_upd) {
					                error_log("Balance update failed: " . mysqli_stmt_error($ustmt));
					            }
					            mysqli_stmt_close($ustmt);
					        } else {
					            error_log("Prepare failed (balance update): " . mysqli_error($conn));
					        }

					        if ($ok_upd) {
					            $date = date("Ymd");
    							$time = time();
    							$serial = 'W' . $date . $time . rand(1000, 9999);
    							$sthiti = $isDemoUser ? 1 : 0; // preserve your earlier logic

    							$ins_ok = false;
    						
    							
    							$ins = "INSERT INTO hintegedukolli (balakedara, motta, dharavahi, khateshonu, dinankavannuracisi, madari, tike, sthiti) 
                                        VALUES ('$shonuid', '$amount', '$serial', '$bid', '$shnunc', '$type', 'Applied', '$sthiti')";
                                
                                // Execute the query
                                $result = mysqli_query($conn, $ins);
                                
                                // Check if the query was successful
                                if ($result) {
                                    $ins_ok = true;
                                    // Insert was successful
                                    // echo "Insert successful!";
                                } else {
                                    // Handle error if the query failed
                                    error_log("Insert failed: " . mysqli_error($conn));
                                }


    							if ($ins_ok) {
    							    mysqli_commit($conn);
    							    $res['data'] = [
    							        'shonuid' => $shonuid,
    							        'serial' => $serial,
    							        'amount' => $amount,
    							        'type' => $type,
    							        'time' => $shnunc
    							    ];
    							    $res['code'] = 0;
    							    $res['msg'] = 'Succeed';
    							    $res['msgCode'] = 0;
    							    http_response_code(200);
    							} else {
    							    mysqli_rollback($conn);
    							    $res['code'] = 1;
    							    $res['msg'] = 'Database insertion error';
    							    $res['msgCode'] = 101;
    							    http_response_code(500);
    							}
					        } else {
					            mysqli_rollback($conn);
    							$res['code'] = 1;
    							$res['msg'] = 'Failed to update balance';
    							$res['msgCode'] = 101;
    							http_response_code(500);
					        }
					       
					    } else {
    						$res['code'] = 1;
    						$res['msg'] = 'Insufficient balance';
    						$res['msgCode'] = 142;
    						$res['debug'] = $balarr ? $balarr['motta'] : null;
    						http_response_code(200);
    					}
						
					} else {
						$res['code'] = 1;
						$res['msg'] = 'invalid amount range';
						$res['msgCode'] = 142;
						http_response_code(200);
					}
				} else {
					$res['code'] = 4;
					$res['msg'] = 'No operation permission';
					$res['msgCode'] = 2;
					http_response_code(401);
				}
			} else {
				$res['code'] = 5;
				$res['msg'] = 'Wrong signature';
				$res['msgCode'] = 3;
				http_response_code(200);
			}
		} else {
			$res['code'] = 7;
			$res['msg'] = 'Param is Invalid';
			$res['msgCode'] = 6;
			http_response_code(200);
		}
	} else {
		http_response_code(405);
		echo json_encode($res);
		exit;
	}
	
	echo json_encode($res);
	mysqli_close($conn);
?>
