<?php 
include("conn.php");
if(isset($_POST['app'])){
    
    $uid = $_POST['uid'];
    $deposit = $_POST['amount'];
	$depositdup = $deposit;
	
	$sid = $_POST['sid'];
	
	$ref_num = $_POST['ref_num'];

    date_default_timezone_set('Asia/Kolkata');
    $today = date("F j, Y, g:i a"); 
	$tday = date("Y-m-d H:i");
	
	$dt = $_POST['date'];//added
	$timestamp = strtotime($dt);
	$dt2 = date("Y-m-d H:i", $timestamp);
	
	//Find referer
	$self = mysqli_query($conn , "SELECT code FROM shonu_subjects WHERE id = '".$uid."'");
	$selfArray = mysqli_fetch_array($self);
	$ref = mysqli_query($conn , "SELECT id FROM shonu_subjects WHERE owncode = '".$selfArray['code']."'");
	$refArray = mysqli_fetch_array($ref);
	$refid = $refArray['id'];

	/* ══════════════════════════════════════════════════════════════
	   AGENT BALANCE PRE-CHECK — deposit approve করার আগেই check হয়
	   Referrer যদি active Agent হয় এবং তার balance এই deposit-এর
	   জন্য যথেষ্ট না হয়, পুরো deposit-ই block হয়ে যাবে (approve হবে না)
	   ══════════════════════════════════════════════════════════════ */
	$depositAmtF   = floatval($deposit);
	$isActiveAgent = false;
	$agentHasEnough = true;

	$agentCheckQ = mysqli_query($conn, "SELECT userid FROM tb_agent WHERE userid = '".$refid."' AND status = '1'");
	if ($agentCheckQ && mysqli_num_rows($agentCheckQ) > 0) {
		$isActiveAgent = true;
		$agentBalRow = mysqli_fetch_assoc(mysqli_query($conn,
			"SELECT CAST(motta AS DECIMAL(15,2)) as bal FROM shonu_kaichila WHERE balakedara = '".$refid."'"
		));
		$agentBal = $agentBalRow ? floatval($agentBalRow['bal']) : 0;
		$agentHasEnough = ($agentBal >= $depositAmtF);

		if (!$agentHasEnough) {
			mysqli_query($conn,
				"INSERT INTO agent_motta_log (agent_userid, to_user, amount, type, remark)
				 VALUES ('".$refid."', '".$uid."', '$depositAmtF', 'deposit_blocked', 'Deposit blocked - agent balance ('.$agentBal.') is less than deposit amount')"
			);
		}
	}

	if ($isActiveAgent && !$agentHasEnough) {
		// Agent-এর balance যথেষ্ট না — deposit approve না করেই থামিয়ে দাও
		$agentMobRow = mysqli_fetch_assoc(mysqli_query($conn,
			"SELECT mobile FROM shonu_subjects WHERE id = '".$refid."'"
		));
		$agentMobile = $agentMobRow ? $agentMobRow['mobile'] : 'অজানা';
		echo "3~Agent balance অপর্যাপ্ত। আপনার Agent-এর সাথে যোগাযোগ করুন — Agent ID: $refid, Mobile: $agentMobile";
		exit;
	}
	/* ══════════════════════════════════════════════════════════════ */

	/* ══════════════════════════════════════════════════════════════
	   SYSTEM COIN CHECK — Deposit চূড়ান্তভাবে Approve হওয়ার আগে,
	   System Coin (nirvahaka_shonu-এর সবচেয়ে প্রথম Row) আবার একবার
	   Verify করা হচ্ছে। শূন্য/কম হলে বা যথেষ্ট না হলে Approve আটকে যাবে।
	   ══════════════════════════════════════════════════════════════ */
	$systemCoinRow = mysqli_fetch_assoc(mysqli_query($conn,
		"SELECT unohs, CAST(motta AS DECIMAL(15,2)) as bal FROM nirvahaka_shonu ORDER BY unohs ASC LIMIT 1"
	));
	$systemCoinUnohs = $systemCoinRow ? $systemCoinRow['unohs'] : null;
	$systemCoin = $systemCoinRow ? floatval($systemCoinRow['bal']) : 0;

	if ($systemCoinUnohs === null || $systemCoin <= 0 || $depositAmtF > $systemCoin) {
		echo "3~Insufficient System Balance. Owner থেকে কয়েন নেন।";
		exit;
	}
	/* ══════════════════════════════════════════════════════════════ */
	
	if($depositdup>='500' && $depositdup<'1000'){
		$refbn = 0;
	}
	else if($depositdup>='1000' && $depositdup<'3000'){
		$refbn = 0;
	}
	else if($depositdup>='3000' && $depositdup<'4000'){
		$refbn = 0;
	}
	else if($depositdup>='4000' && $depositdup<'5000'){
		$refbn = 0;
	}
	else if($depositdup>='5000' && $depositdup<'10000'){
		$refbn = 0;
	}
	else if($depositdup>='10000' && $depositdup<'50000'){
		$refbn = 0;
	}
	else if($depositdup>='50000' && $depositdup<'100000'){
		$refbn = 0;
	}
	else if($depositdup>='100000'){
		$refbn = 0;
	}
	else{
		$refbn = 0;
	}
	
	$refbnthr = 0;
	$refwal = mysqli_query($conn , "SELECT motta FROM shonu_kaichila WHERE balakedara = '".$refid."'");
	$refwalA = mysqli_fetch_array($refwal);
	$refwalB = $refwalA['motta'];
	$refwalF = intval($refwalB) + intval($refbn);
	$refwalFthr = intval($refwalB) + intval($refbnthr);
	
	//Find 1st Rech
	$up2 = mysqli_query($conn , "SELECT shonu FROM thevani WHERE balakedara = '".$uid."' && sthiti = '1'");
	$up2row = mysqli_num_rows($up2);
	
  	//Bonus
  	$rechqueryaa = mysqli_query($conn, "SELECT rechargebonus FROM parametredepaiement");
    $rechqueryarrayaa = mysqli_fetch_array($rechqueryaa);
    $rechargebonus = $rechqueryarrayaa['rechargebonus'];
  	$bn = '0';
  	if($up2row == 0){
		//$bn = ($rechargebonus*$depositdup)/100;
		$bn = '0';
		} else {$bn = '0';}
  
	
    $up = mysqli_query($conn , "SELECT motta FROM shonu_kaichila WHERE balakedara = '".$uid."'");
    $rup = mysqli_fetch_array($up);
         
    $addmoney = intval($rup['motta']) + intval($deposit) + intval($bn);

     $wal = mysqli_query($conn, "UPDATE shonu_kaichila SET motta = '".$addmoney."' WHERE balakedara = '".$uid."'");
    
    if($wal){
        $succes = mysqli_query($conn, "UPDATE thevani SET sthiti = '1' WHERE balakedara = '".$uid."' && motta = '$deposit' && dinankavannuracisi = '".$dt."' && shonu = '".$sid."'");//dt added

		// ✅ নতুন যোগ — Withdraw Ban থাকলে, এই Deposit-টা "জমা" হিসেবে
		// গোনা হচ্ছে, আর প্রয়োজনীয় পরিমাণ পূরণ হলে Ban স্বয়ংক্রিয়ভাবে
		// তুলে দেওয়া হচ্ছে।
		$banRow = mysqli_fetch_assoc(mysqli_query($conn,
			"SELECT withdraw_banned, required_deposit_amount, deposited_since_ban FROM shonu_subjects WHERE id = '".$uid."'"
		));
		if ($banRow && intval($banRow['withdraw_banned']) === 1) {
			$newDeposited = floatval($banRow['deposited_since_ban']) + $depositAmtF;
			$required = floatval($banRow['required_deposit_amount']);
			if ($newDeposited >= $required) {
				mysqli_query($conn, "
					UPDATE shonu_subjects
					SET withdraw_banned = 0, deposited_since_ban = 0, required_deposit_amount = 0
					WHERE id = '".$uid."'
				");
			} else {
				mysqli_query($conn, "
					UPDATE shonu_subjects
					SET deposited_since_ban = '$newDeposited'
					WHERE id = '".$uid."'
				");
			}
		}
				
		if($up2row == 0){
			$refwll = mysqli_query($conn, "UPDATE shonu_kaichila SET motta = '".$refwalF."' WHERE balakedara = '".$refid."'");
		}
		else if($up2row== 2){
			$refwll = mysqli_query($conn, "UPDATE shonu_kaichila SET motta = '".$refwalFthr."' WHERE balakedara = '".$refid."'");
		}              				
		
		/* ══════════════════════════════════════════════════════════
		   AGENT COIN DEDUCTION — এতক্ষণে আমরা জানি agent-এর balance
		   যথেষ্ট ছিল (উপরেই check হয়ে গেছে), তাই নিশ্চিন্তে কাটছি
		   ══════════════════════════════════════════════════════════ */
		if ($isActiveAgent) {
			mysqli_query($conn,
				"UPDATE shonu_kaichila
				 SET motta = CAST(CAST(motta AS DECIMAL(15,2)) - $depositAmtF AS CHAR)
				 WHERE balakedara = '".$refid."' AND CAST(motta AS DECIMAL(15,2)) >= $depositAmtF"
			);
			mysqli_query($conn,
				"INSERT INTO agent_motta_log (agent_userid, to_user, amount, type, remark)
				 VALUES ('".$refid."', '".$uid."', '$depositAmtF', 'deposit_deduct', 'User deposit approved - auto deducted from agent')"
			);
		}
		/* ══════════════════════════════════════════════════════════ */

		/* ══════════════════════════════════════════════════════════
		   SYSTEM COIN DEDUCTION — Deposit সফলভাবে Approve হয়ে গেছে,
		   তাই System Coin থেকে এই Amount Minus হচ্ছে।
		   ══════════════════════════════════════════════════════════ */
		mysqli_query($conn,
			"UPDATE nirvahaka_shonu
			 SET motta = CAST(CAST(motta AS DECIMAL(15,2)) - $depositAmtF AS CHAR)
			 WHERE unohs = '".$systemCoinUnohs."' AND CAST(motta AS DECIMAL(15,2)) >= $depositAmtF"
		);
		/* ══════════════════════════════════════════════════════════ */
		
		echo "1~".$sid;
	}else{
        echo "2"; 
    }
}

?>
<?php 
if(isset($_POST['rej'])){
	
	$sid = $_POST['sid'];
	$ref_num = $_POST['ref_num'];
	$dt = $_POST['date'];//added
	$timestamp = strtotime($dt);
	$dt2 = date("Y-m-d H:i", $timestamp);
	
	date_default_timezone_set('Asia/Kolkata');
	$tdayy = date("Y-m-d H:i");
    
    $uid = $_POST['uid'];
    $deposit = $_POST['amount'];
    
    $reject = mysqli_query($conn, "UPDATE thevani SET sthiti = '2' WHERE balakedara = '".$uid."' && motta = '$deposit' && dinankavannuracisi = '".$dt."' && shonu = '".$sid."'");//dt added
	
	if($reject){
		echo "1~".$sid;
	}
	else{
		echo"2";
	}
}
?>
