<?php 
	include('conn.php');
	
	if(isset($_POST['type'])){
		$id=$_POST['id'];
        $remark=$_POST['remark'];
		$today=date( 'Y-m-d H:i:s' );
		
		$finduid=mysqli_query($conn,"select * from `hintegedukolli` where `shonu`='".$id."'");
		$finduidArray = mysqli_fetch_array($finduid);
		$userid = $finduidArray['balakedara'];
		$serial = $finduidArray['dharavahi'];
		$amount = $finduidArray['motta'];
		$bid = $finduidArray['khateshonu'];
		
		$sql_d = "SELECT * FROM tbl_pg WHERE status = '1'";		
		$run_d = mysqli_query($conn, $sql_d);
		$rund_f = mysqli_fetch_array($run_d);
		$gateway = $rund_f['value'];

		/* ══════════════════════════════════════════════════════════
		   REMOVED — Withdraw approve হলে Agent-এর coin আর বাড়বে না।
		   Agent commission শুধু GGR (bet - win) থেকে আসবে, withdraw
		   থেকে কখনো না। আগের credit_agent_on_withdraw() লজিক এবং
		   Agent/referrer lookup ইচ্ছাকৃতভাবে সরিয়ে দেওয়া হয়েছে।
		   ══════════════════════════════════════════════════════════ */

		/* ══════════════════════════════════════════════════════════
		   SYSTEM COIN CREDIT — Withdraw Approve হলে System Coin
		   (nirvahaka_shonu-এর সবচেয়ে প্রথম Row)-এ এই Amount Plus হবে।
		   ══════════════════════════════════════════════════════════ */
		function credit_system_coin_on_withdraw($conn, $amount) {
			mysqli_query($conn,
				"UPDATE nirvahaka_shonu
				 SET motta = CAST(CAST(motta AS DECIMAL(15,2)) + ".floatval($amount)." AS CHAR)
				 WHERE unohs = (SELECT unohs FROM (SELECT unohs FROM nirvahaka_shonu ORDER BY unohs ASC LIMIT 1) AS temp_syscoin)"
			);
		}
		/* ══════════════════════════════════════════════════════════ */
		
		if($_POST['type']=='accept'){
			$withdrawCompleted = false;
			if($gateway == 'indianpay'){
				$date = date("Ymd");
				$time = time();
				//$serial = 'W' . $date . $time . rand(1000,9999);
				
				$inamt = $amount;
				
				$samasye = "SELECT khatehesaru, khatesankhye, kod, phalanubhavi
				  FROM khate WHERE byabaharkarta = $userid
				  AND shonu = $bid";
				$samasyephalitansa = $conn->query($samasye);
				$row = mysqli_fetch_array($samasyephalitansa);								
				
				$url = "https://indianpay.co.in/admin/single_transaction";
				
				$salt = '';
	
				$merchant_id = 'INDIANPAY10045';
				$merchant_token = 'KFDZW5BHD2y8kzj8cW3t6yFV3jAX3iNS';
				$account_no = $row['khatesankhye'];
				$ifsccode = $row['kod'];
				$amount = $amount;
				$bankname = $row['khatehesaru'];
				$remark = 'remark';
				$orderid = $serial;
				$name = $row['phalanubhavi'];
				
				$findmob=mysqli_query($conn,"select mobile from `shonu_subjects` where `id`='".$userid."'");
				$findmobArray = mysqli_fetch_array($findmob);
				$moble = $findmobArray['mobile'];				
				$contact = $moble;
				
				$email = 'withgateway@cv111.site';
				
				$data_enc = array(
					'merchant_id' => $merchant_id,
					'merchant_token' => $merchant_token,
					'account_no' => $account_no,
					'ifsccode' => $ifsccode,
					'amount' => $amount,
					'bankname' => $bankname,
					'remark' => $remark,
					'orderid' => $orderid,
					'name' => $name,
					'contact' => $contact,
					'email' => $email
				);
				
				$jsonData_enc = json_encode($data_enc);
				$encoded = base64_encode($jsonData_enc);
				
				$data = array(
					'salt' => $encoded,
					'merchant_id' => $merchant_id,
					'merchant_token' => $merchant_token,
					'account_no' => $account_no,
					'ifsccode' => $ifsccode,
					'amount' => $amount,
					'bankname' => $bankname,
					'remark' => $remark,
					'orderid' => $orderid,
					'name' => $name,
					'contact' => $contact,
					'email' => $email
				);
				
				$jsonData = json_encode($data);
				
				$ch = curl_init($url);
	
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_POST, true);
				/* ✅ FIX — এখানে আগে কোনো Timeout ছিল না, তাই এই External
				   API (indianpay.co.in) Dead/Slow হলে curl_exec() চিরকাল
				   আটকে থাকতে পারতো, ফলে নিচের Fallback Code-ও কখনো চলার
				   সুযোগ পেত না। */
				curl_setopt($ch, CURLOPT_TIMEOUT, 10);
				curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
				curl_setopt($ch, CURLOPT_HTTPHEADER, [
					'Content-Type: application/json',
					'Content-Length: ' . strlen($jsonData)
				]);
				curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
				
				$response = curl_exec($ch);
				$curlErr = curl_error($ch);
				curl_close($ch);

				$un = json_decode($response, true);

				if (!$curlErr && isset($un['status']) && $un['status'] == 200) {
					// IndianPay API সফলভাবে সাড়া দিয়েছে
					$sqlA = mysqli_query($conn,"Update `hintegedukolli` set sthiti = '1',tike = 'Completed',dinankavannuracisi = '".$today."' where `shonu`='".$id."' ");
					credit_system_coin_on_withdraw($conn, $inamt);
					$withdrawCompleted = true;
				} else {
					/* ══════════════════════════════════════════════════════
					   FIX — IndianPay-এর External API Dead/Unreachable হলে
					   আগে এখানে কিছুই হতো না (Accept আটকে থাকতো)। এখন Admin
					   Accept চাপলে ধরে নেওয়া হচ্ছে Payment ইতিমধ্যে পাঠানো
					   হয়েছে (Manual-ভাবে), তাই Request Complete হবে এবং
					   System Coin ঠিকভাবে বাড়বে — শুধু Remark-এ API Fail
					   হওয়ার তথ্য রাখা হচ্ছে, ভবিষ্যতে Audit করার জন্য।
					   ══════════════════════════════════════════════════════ */
					$apiFailNote = mysqli_real_escape_string($conn, 'IndianPay API response failed/unreachable - completed manually by admin');
					$sqlA = mysqli_query($conn,"Update `hintegedukolli` set sthiti = '1',tike = 'Completed',remarks = '".$apiFailNote."',dinankavannuracisi = '".$today."' where `shonu`='".$id."' ");
					credit_system_coin_on_withdraw($conn, $inamt);
					$withdrawCompleted = true;
				}
			}			
			else if($gateway == 'manual'){
				$sqlA = mysqli_query($conn,"Update `hintegedukolli` set sthiti = '1',tike = 'Completed',remarks = '".$remark."',dinankavannuracisi = '".$today."' where `shonu`='".$id."' ");
				credit_system_coin_on_withdraw($conn, $amount);
				$withdrawCompleted = true;
			}
			else{
				/* ══════════════════════════════════════════════════════════
				   FALLBACK — 'indianpay' এবং 'manual' ছাড়া অন্য যেকোনো
				   Active Gateway-এর জন্য (নাম যাই হোক না কেন)। এতদিন এই
				   Case-এ কিছুই Update হতো না, তাই System Coin-ও বাড়তো না।
				   এখন 'manual'-এর মতোই ব্যবহার করা হচ্ছে — Withdraw
				   Complete হবে এবং System Coin ঠিকভাবে Plus হবে।
				   ══════════════════════════════════════════════════════════ */
				$sqlA = mysqli_query($conn,"Update `hintegedukolli` set sthiti = '1',tike = 'Completed',remarks = '".$remark."',dinankavannuracisi = '".$today."' where `shonu`='".$id."' ");
				credit_system_coin_on_withdraw($conn, $amount);
				$withdrawCompleted = true;
			}
			//$sqlA = mysqli_query($conn,"Update `hintegedukolli` set sthiti = '1',remarks = 'Completed',tike = 'Completed',dinankavannuracisi = '".$today."' where `shonu`='".$id."' ");
			if ($withdrawCompleted) {
				echo 1;
			} else {
				// ✅ আগে এখানে সবসময় 1 (Success) দেখাতো, Payment আসলে
				// সফল হোক বা না হোক। এখন সত্যিকারের ব্যর্থতা হলে Frontend
				// বুঝতে পারবে, আর Withdraw ভুলভাবে "Completed" দেখাবে না।
				echo "0~Payment Gateway Response ব্যর্থ হয়েছে, Withdraw Complete হয়নি।";
			}
		}
		else if($_POST['type']=='reject'){
			$sqlA = mysqli_query($conn, "UPDATE `hintegedukolli` 
                             SET sthiti = '2', 
                                 tike = 'Rejected', 
                                 dinankavannuracisi = '".$today."', 
                                 remarks = '".$remark."' 
                             WHERE `shonu`='".$id."'");

$sqlwallet = mysqli_query($conn, "UPDATE `shonu_kaichila` 
                                  SET `motta` = ROUND((motta + '$amount'), 2) 
                                  WHERE `balakedara`= '$userid'");
			echo 2;
		}
	}
?>