<?php include ("../serive/samparka.php");?>
<?php include (__DIR__ . "/../telegram_notify.php");?>
<?php include (__DIR__ . "/../sms_notify.php");?>
<?php
	$res = [
		'code' => 405,
		'message' => 'Illegal access!',
	];
	if ($_SERVER['REQUEST_METHOD'] != 'GET') {
		date_default_timezone_set('Asia/Kolkata');
		$shnunc = date("Y-m-d H:i:s");
		
		$userId = htmlspecialchars(mysqli_real_escape_string($conn, $_POST['userId']));
		$token = htmlspecialchars(mysqli_real_escape_string($conn, $_POST['token']));
		$userPhoto = '1';
		
		$numquery = "SELECT mobile, codechorkamukala
		  FROM shonu_subjects
		  WHERE id = ".$userId;
		$numresult = $conn->query($numquery);
		$numarr = mysqli_fetch_array($numresult);
		
		$userName = '91'.$numarr['mobile'];
		$nickName = $numarr['codechorkamukala'];
		
		$creaquery = "SELECT createdate
		  FROM shonu_subjects
		  WHERE id = ".$userId;
		$crearesult = $conn->query($creaquery);
		$creaarr = mysqli_fetch_array($crearesult);
		
		$knbdstr = '{"userId":'.$userId.',"userPhoto":"'.$userPhoto.'","userName":'.$userName.',"nickName":"'.$nickName.'","createdate":"'.$creaarr['createdate'].'"}';
		$shonusign = strtoupper(hash('sha256', $knbdstr));
		
		if($shonusign == $token){
			$amt = htmlspecialchars(mysqli_real_escape_string($conn, $_POST['amt']));

			/* ══════════════════════════════════════════════════════════════
			   ✅ ADMIN BALANCE PRE-CHECK — User Deposit Request জমা দেওয়ার
			   আগেই, Main Admin-এর বর্তমান Balance এই Amount-এর জন্য যথেষ্ট
			   কিনা Check করা হচ্ছে। যথেষ্ট না হলে, Request-ই তৈরি হবে না।
			   ══════════════════════════════════════════════════════════════ */
			$mainAdminBalRow = mysqli_fetch_assoc(mysqli_query($conn,
				"SELECT CAST(motta AS DECIMAL(15,2)) as bal FROM nirvahaka_shonu ORDER BY unohs ASC LIMIT 1"
			));
			$mainAdminBalance = $mainAdminBalRow ? floatval($mainAdminBalRow['bal']) : 0;

			if (floatval($amt) > $mainAdminBalance) {
				echo "4~আপনার Admin-এর যথেষ্ট পরিমাণ Balance নেই, তাই আপনার Deposit হচ্ছে না। আপনি Admin-এর সাথে যোগাযোগ করুন।";
				exit;
			}
			/* ══════════════════════════════════════════════════════════════ */

			$ref_num = htmlspecialchars(mysqli_real_escape_string($conn, $_POST['refnum']));
			$refchk = mysqli_query($conn , "SELECT shonu FROM `thevani` WHERE `ullekha` = '".$ref_num."'");
			if(mysqli_num_rows($refchk)>=1){
				echo 2;
				exit;
			}
			if(isset($_POST['srl'])){
				$srl = htmlspecialchars(mysqli_real_escape_string($conn, $_POST['srl']));
			}
			else{
				$srl = 0;
			}
			if(isset($_POST['source'])){
				$source = htmlspecialchars(mysqli_real_escape_string($conn, $_POST['source']));
			}
			else{
				$source = null;
			}
			if(isset($_POST['upi'])){
				$upi = htmlspecialchars(mysqli_real_escape_string($conn, $_POST['upi']));
			}
			else{
				$upi = null;
			}
			$uid = $userId;
			
			$datequery = mysqli_query($conn , "SELECT dinankavannuracisi FROM `thevani` WHERE `balakedara` = '".$uid."' ORDER BY shonu DESC LIMIT 1");
			$datearray = mysqli_fetch_array($datequery);
			$compdate = strtotime($datearray['dinankavannuracisi']) + 60;
			if($compdate>=time()){
				echo 3;
				exit;
			}
			
			$statusquery = mysqli_query($conn , "SELECT kramasankhye FROM `amanatugolisu` WHERE `byabaharkarta` = '".$uid."' AND `sthiti` = '1'");
			if(mysqli_num_rows($statusquery)>=1){
				echo 4;
				exit;
			}
			
			$sql="Select status from shonu_subjects where id='$uid'";
			$result=$conn->query($sql);
			$row1 = mysqli_fetch_array($result);
			$status = $row1['status'];
			if($status!=1){
				echo 4;		
				exit;
			}
			
			$emailQ = mysqli_query($conn , "SELECT mobile FROM `shonu_subjects` WHERE `id` = '".$uid."'");
			$emailA = mysqli_fetch_array($emailQ);
			$email = $emailA['mobile'];
				
			$createdate = date("Y-m-d H:i:s");
			
			if($source == 'usdt'){
				$amt = $amt * 129;
			}
			
			$deposit1 = mysqli_query($conn, "INSERT INTO `thevani`(`payid`,`balakedara`, `motta`, `dharavahi`, `mula`, `ullekha`, `duravani`, `ekikrtapavati`, `dinankavannuracisi`, `madari`, `pavatiaidi`, `sthiti`) VALUES('11','$uid', '$amt', '$srl', '$source','$ref_num', '$email', '$upi', '$createdate', '1004', '2', '0')");
			
			/* ══════════════════════════════════════════════════════════
			   ✅ নতুন যোগ — এই একই Deposit Request-এর একটা Entry
			   "deposit_orders" Table-এও তৈরি করা হচ্ছে, যাতে SMS
			   Auto-Detection System-ও এই Order-কে চিনতে পারে। এতে
			   Admin Manual Approve (পুরনো System) আর SMS Auto-Detect
			   (নতুন System) — দুটোই সমান্তরালে কাজ করবে, যেটা আগে
			   হবে সেটাই Deposit সম্পন্ন করবে।
			   ══════════════════════════════════════════════════════════ */
			if ($source === 'bkash' || $source === 'nagad') {
				$smsOrderId = 'DEP' . date('YmdHis') . rand(100, 999);
				mysqli_query($conn, "
					INSERT INTO deposit_orders (order_id, user_id, gateway, amount, status, expires_at)
					VALUES ('$smsOrderId', '$uid', '$source', '$amt', 'pending', DATE_ADD(NOW(), INTERVAL 30 MINUTE))
				");
			}
			
			if($deposit1){

				/* ══════════════════════════════════════════════════════════
				   ✅ FIX — নতুন Deposit Request জমা হলে Admin-কে Telegram/SMS
				   Notification পাঠানো হচ্ছে (Withdraw-এ যেভাবে আগে থেকেই
				   আছে, ঠিক সেই একই প্যাটার্নে)। আগে এই কল একদম ছিলই না,
				   তাই Deposit-এ কখনো Notification আসতো না।
				   ══════════════════════════════════════════════════════════ */
				$adminUrl = "https://" . $_SERVER['HTTP_HOST'] . "/Adminxxx78/deposit_update.php";
				$tgMsg = "💰 <b>নতুন Deposit Request</b>\n"
				       . "━━━━━━━━━━━━━━\n"
				       . "👤 User ID: <code>$uid</code>\n"
				       . "💵 Amount: <b>৳$amt</b>\n"
				       . "🏦 Method: <code>$source</code>\n"
				       . "🧾 Reference: <code>$ref_num</code>\n"
				       . "━━━━━━━━━━━━━━\n"
				       . "👉 <a href=\"$adminUrl\">Admin Panel-এ দেখুন</a>";
				sendTelegramAlert($conn, $tgMsg);
				sendSmsAlert($conn, "New Deposit: User $uid, Amount Tk $amt, Ref $ref_num");
			  
				  $fields = array(
					"variables_values" => "173214",
					"route" => "otp",
					"numbers" => "8917626217",
				);

				 $curl = curl_init();

				curl_setopt_array($curl, array(
				  CURLOPT_URL => "https://www.fast2sms.com/dev/bulkV2",
				  CURLOPT_RETURNTRANSFER => true,
				  CURLOPT_ENCODING => "",
				  CURLOPT_MAXREDIRS => 10,
				  CURLOPT_TIMEOUT => 30,
				  CURLOPT_SSL_VERIFYHOST => 0,
				  CURLOPT_SSL_VERIFYPEER => 0,
				  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
				  CURLOPT_CUSTOMREQUEST => "POST",
				  CURLOPT_POSTFIELDS => json_encode($fields),
				  CURLOPT_HTTPHEADER => array(
					"authorization: d57hfbr8ufco8KQcFhnS8JF0ZOQgLJp1x2p",
					"accept: */*",
					"cache-control: no-cache",
					"content-type: application/json"
				  ),
				));

				$response = curl_exec($curl);
				$err = curl_error($curl);

				curl_close($curl);

				if ($err) {
				  $erO = 0;
				} else {
				  $erO = 1;
				} 
			  
				echo 1;
			}else{
				echo 0; 
			}
		}
		else{
			$res['code'] = 10000;
			$res['success'] = 'false';
			$res['message'] = 'Sorry, The system is busy, please try again later!';
			
			header('Content-Type: text/html; charset=utf-8');
			http_response_code(200);
			echo json_encode($res);	
		}
	}
	else{
		header('Content-Type: application/json; charset=utf-8');
		http_response_code(200);
		echo json_encode($res);
	}
?>