Ticker

6/recent/ticker-posts

Header Ads Widget

JustMarkets

 package com.search2learn.s2l

import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import android.app.ProgressDialog
import kotlin.Pair
import androidx.activity.OnBackPressedCallback
import com.search2learn.s2l.TokenBalance
import com.search2learn.s2l.Balance


import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import androidx.core.app.ActivityCompat
import com.google.firebase.messaging.FirebaseMessaging
import android.widget.ImageButton
import com.google.firebase.firestore.SetOptions
import com.google.firebase.FirebaseApp
import com.google.firebase.FirebaseOptions
import com.google.auth.oauth2.GoogleCredentials
import com.google.firebase.FirebaseOptions.Builder
import java.io.InputStream
import com.google.firebase.messaging.RemoteMessage

import kotlinx.coroutines.tasks.await
import com.google.firebase.firestore.ktx.firestore

import kotlinx.coroutines.withContext



import android.widget.ProgressBar

import androidx.lifecycle.lifecycleScope





import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume

import android.widget.*

















import android.content.pm.PackageManager

import android.Manifest

import android.os.Build

import androidx.core.content.ContextCompat



import androidx.core.app.NotificationManagerCompat
import androidx.core.app.NotificationCompat

import android.app.NotificationChannel
import android.app.NotificationManager
import android.media.RingtoneManager

import android.media.AudioAttributes
import android.graphics.Color
import android.app.Notification
import kotlinx.coroutines.withContext
import kotlinx.parcelize.Parcelize
import com.google.firebase.firestore.FieldValue
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
import java.util.Collections
import com.google.firebase.Timestamp
import org.web3j.abi.TypeReference
import com.google.firebase.firestore.ktx.firestore
import kotlinx.coroutines.tasks.await
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

import org.web3j.crypto.*
import kotlin.Result
import kotlin.Result.Companion.failure
import kotlin.Result.Companion.success

import org.p2p.solanaj.core.*
import org.p2p.solanaj.programs.*
import org.p2p.solanaj.rpc.*
import org.p2p.solanaj.rpc.types.*

import okhttp3.OkHttpClient
import kotlin.time.Duration.Companion.seconds
import kotlin.time.DurationUnit
import kotlin.time.toDuration
import com.search2learn.s2l.TokenContract
import com.search2learn.s2l.TokenInfo
import com.search2learn.s2l.TokenType

import org.bitcoinj.core.Base58
import org.p2p.solanaj.core.PublicKey
import org.p2p.solanaj.core.Account
import org.p2p.solanaj.core.TransactionInstruction
import org.p2p.solanaj.core.AccountMeta
import org.p2p.solanaj.core.*
import org.p2p.solanaj.programs.*
import org.p2p.solanaj.rpc.*
import org.p2p.solanaj.rpc.types.*
import android.widget.Toast
import kotlinx.coroutines.*

import org.p2p.solanaj.programs.TokenProgram
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.withContext
import javax.crypto.SecretKey
import com.search2learn.s2l.WalletManager
import com.search2learn.s2l.TokenManager
import kotlinx.coroutines.launch
import android.util.Base64
import javax.crypto.Cipher
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.SecretKeySpec
import java.net.URL
import kotlinx.coroutines.tasks.await
import com.search2learn.s2l.Web3Utils
import com.search2learn.s2l.SolanaUtils
import com.search2learn.s2l.TronUtils
import com.search2learn.s2l.Web3TokenUtils
import com.search2learn.s2l.WalletManager.MultiChainWallet
import android.text.TextWatcher
import android.text.Editable
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume

import android.widget.*

import androidx.lifecycle.lifecycleScope


import kotlinx.coroutines.withContext
import android.widget.TextView
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import kotlinx.coroutines.launch
import android.widget.Button
import org.web3j.protocol.core.methods.response.TransactionReceipt
import android.widget.EditText
import kotlin.coroutines.suspendCoroutine
import kotlin.coroutines.resume
import kotlin.random.Random
import com.search2learn.s2l.Web3Utils.getTokenBalance
import com.search2learn.s2l.Web3Utils.getWeb3j
import org.web3j.protocol.core.methods.request.Transaction
import org.web3j.abi.datatypes.Function
import org.json.JSONObject

import org.web3j.protocol.core.DefaultBlockParameterName
import kotlinx.coroutines.CoroutineScope
import org.web3j.abi.datatypes.generated.Uint256
import org.web3j.abi.FunctionEncoder
import org.web3j.abi.datatypes.Address
import java.io.IOException
import org.web3j.protocol.Web3j
import android.content.Context
import android.view.View
import org.web3j.crypto.Credentials
import org.web3j.crypto.RawTransaction
import org.web3j.crypto.TransactionEncoder
import org.web3j.utils.Numeric
import java.math.BigInteger
import com.search2learn.s2l.Web3Utils.getNonce
import org.web3j.utils.Convert
import org.web3j.protocol.http.HttpService
import com.google.firebase.auth.FirebaseAuth
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import android.util.Log
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import java.math.BigDecimal
import java.math.RoundingMode
import com.google.firebase.firestore.FirebaseFirestore
import com.search2learn.s2l.Web3Utils.getGasPrice

import kotlinx.coroutines.withContext

class DashboardActivity : AppCompatActivity() {
private lateinit var web3j: Web3j
private val web3: Web3j by lazy {
Web3j.build(HttpService("https://bsc-mainnet.infura.io/v3/c88ab0a11eb040438cff2f7bef79feec"))
}


// العناصر الجديدة من التصميم المحسن
private lateinit var btnProfile: ImageView
private lateinit var btnDeposit: Button
private lateinit var btnReadMoreNews: Button


private lateinit var btnLogout: Button
private lateinit var btnNewDeposit: Button // يجب أن يكون موجوداً في قائمة المتغيرات
private lateinit var btnaff: ImageButton // تعريف المتغير
private val web3jClients = mutableMapOf<String, Web3j>()
private lateinit var tvTotalBalanceUSD: TextView
private lateinit var tvBNBPrice: TextView
private lateinit var tvS2LPrice: TextView
private lateinit var balanceBNBTextView: TextView
private lateinit var balanceS2LTextView: TextView
private lateinit var depositAddressTextView: EditText
private lateinit var btnCopyAddress: Button
private lateinit var btnWithdraw: Button
private lateinit var logoutButton: ImageButton
private lateinit var btnTransactions: ImageButton
private lateinit var btnSupport: Button
private lateinit var btnNewCoins: Button
private lateinit var btnTrade: Button
private var userBalance: BigDecimal = BigDecimal.ZERO
private val updateInterval = 5000L // تحديث كل 5 ثواني
private lateinit var tvBalanceBNB: TextView
private lateinit var tvBalanceS2L: TextView
private var lastNotificationTime: Long = 0
private var amount: BigDecimal = BigDecimal.ZERO // أضف هذا
private var coin: String = "" // أضف هذا المتغير هنا
private lateinit var btaddcoin: ImageButton

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_dashboard)


setupBackPressHandler()

// التحقق من تسجيل الدخول
if (!isUserLoggedIn()) {
redirectToLogin()
return
}

// التحقق من تسجيل الدخول
val currentUser = FirebaseAuth.getInstance().currentUser
val preferences = getSharedPreferences("MyPrefs", MODE_PRIVATE)
val isLoggedIn = preferences.getBoolean("isLoggedIn", false) && currentUser != null

if (!isLoggedIn) {
startActivity(Intent(this, LoginActivity::class.java))
finish()
return
}

val btn = findViewById<Button>(R.id.btnReadMoreNews)
btn.setOnClickListener {
val intent = Intent(this, DiscoverActivity::class.java)
startActivity(intent)
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left) // اختياري
}




// الحصول على التوكن
FirebaseMessaging.getInstance().token.addOnSuccessListener { token ->
val user = FirebaseAuth.getInstance().currentUser
if (user != null) {
saveTokenToFirestore(user.uid, token)
} else {
Log.w("DashboardActivity", "المستخدم غير مسجل الدخول، لم يتم حفظ التوكن")
}
}

lifecycleScope.launch {
val usdtBalance = Web3Utils.getTokenBalance(
contractAddress = "0x55d398326f99059fF775485246999027B3197955",
walletAddress = "0x1349d46745095d105120324b0074de0b6b842ae9",
decimals = 18
)
Log.d("USDT-Test", "رصيد USDT هو: $usdtBalance")
}



// تهيئة WalletManager
WalletManager.setContext(this)


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
!= PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.POST_NOTIFICATIONS),
1001
)
}
}



initializeWallet()

tvBalanceBNB = findViewById(R.id.tvBalanceBNB)
tvBalanceS2L = findViewById(R.id.tvBalanceS2L)
tvTotalBalanceUSD = findViewById(R.id.tvTotalBalanceUSD)

btnaff = findViewById(R.id.btnaff)

// ربط العناصر بالواجهة الجديدة
initViews()

// تهيئة Web3j
web3j = Web3j.build(HttpService("https://bsc-mainnet.infura.io/v3/c88ab0a11eb040438cff2f7bef79feec"))

// تحميل بيانات المحفظة
loadWalletData()


// بدء التحديث التلقائي للأسعار والرصيد
startPriceUpdate()
startBalanceUpdate()

// إعداد معالجات الأحداث
setupClickListeners()
}




private fun initViews() {



// العناصر الجديدة من التصميم المحسن

btnReadMoreNews = findViewById(R.id.btnReadMoreNews)

// العناصر العلوية
logoutButton = findViewById(R.id.btnLogout)
btnTransactions = findViewById(R.id.btnTransactions)
btnNewDeposit = findViewById(R.id.btnNewDeposit) // هذا السطر مفقود!
btaddcoin = findViewById(R.id.btaddcoin) // تأكد من أن المعرف صحيح

// بطاقات العملات
tvTotalBalanceUSD = findViewById(R.id.tvTotalBalanceUSD)
balanceBNBTextView = findViewById(R.id.tvBalanceBNB)
balanceS2LTextView = findViewById(R.id.tvBalanceS2L)
tvBNBPrice = findViewById(R.id.tvBNBPrice)
tvS2LPrice = findViewById(R.id.tvS2LPrice)



// أزرار الإيداع والسحب
depositAddressTextView = findViewById(R.id.etDepositAddress)
btnCopyAddress = findViewById(R.id.btnCopyAddress)
btnWithdraw = findViewById(R.id.btnWithdraw)

// أزرار القائمة السفلية
btnNewCoins = findViewById(R.id.btn_new_coins)
btnTrade = findViewById(R.id.btn_trade)
btnSupport = findViewById(R.id.btnSupport)
}

private fun setupClickListeners() {
// زر تسجيل الخروج
logoutButton.setOnClickListener {
showLogoutDialog()
}

btaddcoin.setOnClickListener {
startActivity(Intent(this, AddCoinActivity::class.java))
}

btnaff.setOnClickListener {
val intent = Intent(this, ReferralActivity::class.java)
startActivity(intent)
}

btnNewDeposit.setOnClickListener {
val user = FirebaseAuth.getInstance().currentUser
if (user == null) {
Toast.makeText(this, "Please login first", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}

fetchWalletAddress { walletAddress ->
if (walletAddress.isNullOrEmpty()) {
Toast.makeText(this, "Wallet address not found", Toast.LENGTH_SHORT).show()
} else {
showEnhancedDepositDialog(walletAddress)
}
}
}


// زر المعاملات
btnTransactions.setOnClickListener {
startActivity(Intent(this, TransactionsActivity::class.java))
}

// زر نسخ العنوان
btnCopyAddress.setOnClickListener {
val address = depositAddressTextView.text.toString()
if (address.startsWith("0x")) {
copyToClipboard(address)
} else {
Toast.makeText(this, "Invalid address", Toast.LENGTH_SHORT).show()
}
}

// زر السحب
// في دالة setupClickListeners()
btnWithdraw.setOnClickListener {
val user = FirebaseAuth.getInstance().currentUser ?: run {
Toast.makeText(this, "Please login first", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}

fetchWalletAddress { walletAddress ->
if (walletAddress.isNullOrEmpty()) {
Toast.makeText(this, "Wallet address not found", Toast.LENGTH_SHORT).show()
} else {
showEnhancedWithdrawDialog(walletAddress)
}
}
}



// زر العملات الجديدة
btnNewCoins.setOnClickListener {
startActivity(Intent(this, NewCoinsActivity::class.java))
}

// زر التداول
btnTrade.setOnClickListener {
startActivity(Intent(this, SwapActivity::class.java))
}

// زر الدعم
btnSupport.setOnClickListener {
startActivity(Intent(this, SupportActivity::class.java))
}
}




private fun recreateWallet() {
val user = FirebaseAuth.getInstance().currentUser ?: return

FirebaseFirestore.getInstance()
.collection("walletsnew")
.document(user.uid)
.delete()
.addOnSuccessListener {
initializeWallet()
}
.addOnFailureListener {
showWalletErrorDialog("Failed to reset wallet. Please reinstall app.")
}
}

private fun showWalletErrorDialog(message: String, onRetry: (() -> Unit)? = null) {
AlertDialog.Builder(this)
.setTitle("Wallet Error")
.setMessage(message)
.setPositiveButton("OK", null)
.apply {
if (onRetry != null) {
setNegativeButton("Retry") { _, _ -> onRetry() }
}
}
.show()
}








private fun loadWalletData() {
val user = FirebaseAuth.getInstance().currentUser ?: run {
Toast.makeText(this, "Please login first", Toast.LENGTH_SHORT).show()
return
}

WalletManager.getOrCreateWallet { wallet ->
runOnUiThread {
if (wallet != null && WalletManager.MultiChainWallet.isValidBscAddress(wallet.bscAddress)) {
depositAddressTextView.setText(wallet.bscAddress)

lifecycleScope.launch {
updateBalances(wallet)
}

// بدء مراقبة الإيداعات لهذا العنوان
listenForDeposits(wallet.bscAddress)
}
}
}
}



private fun showWalletCreationDialog() {
AlertDialog.Builder(this)
.setTitle("Create Wallet")
.setMessage("No wallet found. Create a new multi-chain wallet?")
.setPositiveButton("Create") { _, _ ->
WalletManager.getOrCreateWallet { wallet ->
if (wallet != null) {
Toast.makeText(
this@DashboardActivity,
"Wallet created successfully!",
Toast.LENGTH_SHORT
).show()
loadWalletData()
}
}
}
.setNegativeButton("Cancel", null)
.show()
}


private suspend fun updateBalances(wallet: WalletManager.MultiChainWallet) {
try {
val tokenPrices = fetchTokenPrices()
var totalBalanceUSD = BigDecimal.ZERO

// تحديث جميع العملات
allTokens.forEach { token ->
val balance = when {
token.isNative -> {
Web3Utils.getBalance(wallet.bscAddress) ?: BigDecimal.ZERO
}
token.tokenType == TokenType.EVM -> {
token.contracts["BSC"]?.let { contract ->
Web3Utils.getTokenBalance(contract.address, wallet.bscAddress, contract.decimals)
?: BigDecimal.ZERO
} ?: BigDecimal.ZERO
}
token.tokenType == TokenType.SOLANA -> {
SolanaUtils.getTokenBalance(
wallet.solanaAddress,
token.contracts["SOLANA"]?.address ?: ""
) ?: BigDecimal.ZERO
}
else -> BigDecimal.ZERO
}

val price = tokenPrices[token.symbol] ?: BigDecimal.ZERO
val value = balance * price
totalBalanceUSD += value

// تحديث واجهة المستخدم للعملات الرئيسية
when (token.symbol) {
"BNB" -> withContext(Dispatchers.Main) {
balanceBNBTextView.text = "${"%.6f".format(balance)} BNB"
tvBNBPrice.text = "$${"%.4f".format(price)}"
}
"S2L" -> withContext(Dispatchers.Main) {
balanceS2LTextView.text = "${balance.setScale(2, RoundingMode.HALF_UP)} S2L"
tvS2LPrice.text = "$${"%.6f".format(price)}"
}
// يمكنك إضافة عملات أخرى هنا إذا كنت تريد عرضها
}
}

// عرض الرصيد الإجمالي
withContext(Dispatchers.Main) {
tvTotalBalanceUSD.text = "$${"%.2f".format(totalBalanceUSD)}"
}

} catch (e: Exception) {
Log.e("Balance", "Error updating balances", e)
withContext(Dispatchers.Main) {
Toast.makeText(this@DashboardActivity, "Error updating balances", Toast.LENGTH_SHORT).show()
}
}
}







// دالة مساعدة لجلب سعر BNB
private fun getCurrentBNBPrice(): BigDecimal {
return try {
tvBNBPrice.text.toString()
.replace("[^\\d.]".toRegex(), "")
.toBigDecimal()
} catch (e: Exception) {
Log.e("Price", "Using default BNB price", e)
BigDecimal("350.0") // قيمة افتراضية
}
}

// دالة مساعدة لجلب سعر S2L (يمكن تطويرها لتصلك من API)
private fun getCurrentS2LPrice(): BigDecimal {
return BigDecimal("0.00003") // ثابت مؤقت
}





private fun showEnhancedDepositDialog(walletAddress: String) {
val coins = allTokens.map { token ->
val mainNetwork = token.contracts.keys.firstOrNull() ?: "Unknown Network"
"${token.symbol} ($mainNetwork)"
}

AlertDialog.Builder(this)
.setTitle("Select Deposit Option")
.setItems(coins.toTypedArray()) { _, which ->
val selectedToken = allTokens[which]
val selectedCoin = selectedToken.symbol

// إذا كان عندو أكثر من شبكة، نخليه يختار
if (selectedToken.contracts.size > 1) {
showNetworkSelectionForDeposit(selectedCoin, walletAddress)
} else {
val selectedNetwork = selectedToken.contracts.keys.first()
showCoinDepositInstructions(selectedCoin, selectedNetwork, walletAddress)
}
}
.setNegativeButton("Cancel", null)
.show()
}


// في DashboardActivity.kt
private fun showNetworkSelectionForDeposit(coin: String, walletAddress: String) {
// ابحث عن العملة من قائمة allTokens الحقيقية
val tokenInfo = allTokens.find { it.symbol.equals(coin, ignoreCase = true) }

if (tokenInfo == null) {
Toast.makeText(this, "العملة غير موجودة", Toast.LENGTH_SHORT).show()
return
}

val networks = tokenInfo.contracts.keys.toList()

if (networks.isEmpty()) {
Toast.makeText(this, "لا توجد شبكة مدعومة لهذه العملة", Toast.LENGTH_SHORT).show()
return
}

AlertDialog.Builder(this)
.setTitle("اختر الشبكة لـ $coin")
.setItems(networks.toTypedArray()) { _, which ->
val selectedNetwork = networks[which]
showCoinDepositInstructions(coin, selectedNetwork, walletAddress)
}
.setNegativeButton("إلغاء", null)
.show()
}




private fun showCoinDepositInstructions(coin: String, network: String, walletAddress: String) {
val minDeposit = when (coin) {
"BNB" -> "0.01 BNB"
"S2L" -> "100 S2L"
"USDT" -> "5 USDT"
else -> "0.01"
}

val message = """
Please send only $coin ($network) to this address:

$walletAddress

Network: $network
Minimum deposit: $minDeposit

⚠️ Warning: Sending other assets may result in permanent loss!
""".trimIndent()

AlertDialog.Builder(this)
.setTitle("Deposit $coin")
.setMessage(message)
.setPositiveButton("Copy Address") { _, _ ->
copyToClipboard(walletAddress)
// تسجيل طلب الإيداع في Firestore
logDepositTransaction(coin, walletAddress)
Toast.makeText(this, "Address copied! Send $coin to this address", Toast.LENGTH_SHORT).show()
}
.setNegativeButton("Close", null)
.show()
}

private fun logDepositTransaction(coin: String, walletAddress: String) {
val userId = FirebaseAuth.getInstance().currentUser?.uid ?: return

val transactionData = hashMapOf(
"type" to "deposit",
"tokenSymbol" to coin,
"toAddress" to walletAddress,
"status" to "pending",
"timestamp" to FieldValue.serverTimestamp(),
"amount" to 0.0, // سيتم تحديثه لاحقًا
"notes" to "Waiting for deposit confirmation",
"confirmed" to false // حقل جديد لتتبع حالة التأكيد
)

FirebaseFirestore.getInstance()
.collection("walletsnew")
.document(userId)
.collection("transactions")
.add(transactionData)
.addOnSuccessListener { docRef ->
Log.d("Deposit", "Deposit request logged with ID: ${docRef.id}")
// بدء مراقبة الرصيد لاكتشاف الإيداع
startDepositMonitoring(coin, walletAddress, docRef.id)
}
.addOnFailureListener { e ->
Log.e("Deposit", "Error logging deposit request", e)
}
}


private fun startDepositMonitoring(coin: String, walletAddress: String, transactionId: String) {
val balanceField = when (coin) {
"BNB" -> "bnbBalance"
"S2L" -> "s2lBalance"
else -> return
}

val db = FirebaseFirestore.getInstance()
val userId = FirebaseAuth.getInstance().currentUser?.uid ?: return

// Listener لتتبع تغيرات الرصيد
db.collection("walletsnew")
.document(userId)
.addSnapshotListener { snapshot, error ->
if (error != null) {
Log.e("Deposit", "Listen failed", error)
return@addSnapshotListener
}

val currentBalance = snapshot?.getDouble(balanceField) ?: 0.0
val previousBalance = snapshot?.getDouble("previous_$balanceField") ?: 0.0

if (currentBalance > previousBalance) {
// تم اكتشاف زيادة في الرصيد - تحديث المعاملة
val depositAmount = currentBalance - previousBalance
updateDepositTransaction(transactionId, depositAmount, walletAddress)

// تحديث الرصيد السابق
db.collection("walletsnew")
.document(userId)
.update("previous_$balanceField", currentBalance)
}
}
}



private fun updateDepositTransaction(transactionId: String, amount: Double, walletAddress: String) {
val userId = FirebaseAuth.getInstance().currentUser?.uid ?: return

val updates = hashMapOf<String, Any>(
"amount" to amount,
"status" to "completed",
"confirmed" to true,
"timestamp" to FieldValue.serverTimestamp(),
"notes" to "Deposit confirmed"
)

FirebaseFirestore.getInstance()
.collection("walletsnew")
.document(userId)
.collection("transactions")
.document(transactionId)
.update(updates)
.addOnSuccessListener {
showDepositSuccessNotification(amount.toBigDecimal(), "BNB") // أو العملة المناسبة
}
}





private fun listenForDeposits(walletAddress: String) {
val userId = FirebaseAuth.getInstance().currentUser?.uid ?: return

FirebaseFirestore.getInstance()
.collection("walletsnew")
.document(userId)
.collection("transactions")
.whereEqualTo("toAddress", walletAddress)
.whereEqualTo("status", "pending")
.addSnapshotListener { snapshots, error ->
if (error != null) {
Log.e("Deposit", "Listen failed", error)
return@addSnapshotListener
}

snapshots?.forEach { doc ->
// هنا يمكنك التحقق من سلسلة الكتل لاكتشاف الإيداع الفعلي
// ثم تحديث حالة المعاملة
updateDepositStatus(doc.id, walletAddress)
}
}
}

private fun updateDepositStatus(transactionId: String, walletAddress: String) {
// هنا يمكنك استخدام Web3j للتحقق من الرصيد
// عند اكتشاف الإيداع، قم بتحديث المعاملة

val updates = hashMapOf<String, Any>(
"status" to "completed",
"timestamp" to FieldValue.serverTimestamp()
)

FirebaseFirestore.getInstance()
.collection("walletsnew")
.document(FirebaseAuth.getInstance().currentUser?.uid ?: return)
.collection("transactions")
.document(transactionId)
.update(updates)
.addOnSuccessListener {
showDepositSuccessNotification(amount, coin)
}
}


private fun updateDepositStatus(transactionId: String, walletAddress: String, amount: BigDecimal, coin: String) {
val updates = hashMapOf<String, Any>(
"status" to "completed",
"timestamp" to FieldValue.serverTimestamp(),
"amount" to amount
)

FirebaseFirestore.getInstance()
.collection("walletsnew")
.document(FirebaseAuth.getInstance().currentUser?.uid ?: return)
.collection("transactions")
.document(transactionId)
.update(updates)
.addOnSuccessListener {
showDepositSuccessNotification(amount, coin)
}
}



















private fun startPriceUpdate() {
CoroutineScope(Dispatchers.Main).launch {
while (true) {
fetchPrices()
delay(updateInterval)
}
}
}

private fun fetchPrices() {
CoroutineScope(Dispatchers.IO).launch {
try {
val response = URL("https://api.binance.com/api/v3/ticker/price?symbol=BNBUSDT").readText()
val jsonObject = JSONObject(response)
val bnbPrice = jsonObject.getString("price").toDouble()

withContext(Dispatchers.Main) {
tvBNBPrice.text = "$${"%.2f".format(bnbPrice)}"
}
} catch (e: Exception) {
Log.e("FetchPrices", "Error fetching BNB price", e)
}
}
}


private fun fetchTotalBalance() {
CoroutineScope(Dispatchers.IO).launch {
try {
val walletAddress = depositAddressTextView.text.toString()
if (walletAddress.isEmpty()) {
Log.e("WalletError", "Wallet address is empty!")
return@launch
}

var totalUsd = BigDecimal.ZERO

for (token in allTokens) {
val contract = token.contracts["BSC"] ?: continue
val balance = Web3Utils.getTokenBalance(
contractAddress = contract.address,
walletAddress = walletAddress,
decimals = contract.decimals
)

if (balance > BigDecimal.ZERO) {
val price = getPriceForToken(token.symbol)
val usdValue = balance.multiply(price)
Log.d("S2L_DEBUG", "${token.symbol} = $balance * $price = $usdValue")
totalUsd = totalUsd.add(usdValue)
}
}

withContext(Dispatchers.Main) {
tvTotalBalanceUSD.text = "$${"%.2f".format(totalUsd)}"
}

} catch (e: Exception) {
Log.e("Balance", "Error calculating total balance", e)
}
}
}
private fun getPriceForToken(symbol: String): BigDecimal {
return when (symbol) {
"S2L" -> BigDecimal("0.00003")
"BNB" -> tvBNBPrice.text.toString().replace("$", "").toBigDecimalOrNull() ?: BigDecimal.ZERO
"USDT" -> BigDecimal.ONE
else -> BigDecimal.ZERO // مؤقتًا، يمكنك لاحقًا ربط CoinGecko لكل رمز
}
}


// 3. الدالة الجديدة:
private fun setupBackPressHandler() {
onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
// بدلاً من الرجوع، ننقل التطبيق إلى الخلفية
moveTaskToBack(true)

// أو يمكنك استخدام هذا للخروج من التطبيق:
// finishAffinity()

// أو عرض تأكيد الخروج:
/*
AlertDialog.Builder(this@DashboardActivity)
.setTitle("تأكيد الخروج")
.setMessage("هل تريد الخروج من التطبيق؟")
.setPositiveButton("نعم") { _, _ -> finishAffinity() }
.setNegativeButton("لا", null)
.show()
*/
}
})
}




private suspend fun fetchTotalBalanceUSD(walletAddress: String): BigDecimal {
return withContext(Dispatchers.IO) {
var totalUsd = BigDecimal.ZERO

for (token in allTokens) {
for ((network, contract) in token.contracts) {
try {
val balance = getTokenBalance(token, walletAddress, network)

val price = token.coingeckoId?.let {
getPriceForToken(it)
} ?: BigDecimal.ZERO

val tokenUsdValue = balance.multiply(price)
totalUsd += tokenUsdValue

Log.d("TotalBalance", "${token.symbol} ($network): $balance × $price = $tokenUsdValue")
} catch (e: Exception) {
Log.e("TotalBalance", " Error for ${token.symbol} on $network", e)
}
}
}

totalUsd
}
}




private suspend fun getUnifiedTokenBalance(token: TokenInfo, walletAddress: String): BigDecimal {
var totalBalance = BigDecimal.ZERO
token.contracts.forEach { (network, contract) ->
val balance = when (network) {
"BSC" -> getTokenBalance(contract.address, walletAddress, contract.decimals)
"ETH" -> getEthTokenBalance(contract.address, walletAddress, contract.decimals)
else -> BigDecimal.ZERO
}
totalBalance += balance
}
return totalBalance
}


private suspend fun getEthTokenBalance(contractAddress: String, walletAddress: String, decimals: Int): BigDecimal {
// تنفيذ جلب الرصيد من شبكة Ethereum
// يمكنك استخدام Web3j مع RPC مختلف لـ ETH
return BigDecimal.ZERO // مؤقت
}




private fun startBalanceUpdate() {
lifecycleScope.launch(Dispatchers.IO) {
while (true) {
try {
val address = depositAddressTextView.text.toString()
if (address.startsWith("0x")) {
// استخدام suspendCancellableCoroutine للتعامل مع callback-based API
val wallet = suspendCancellableCoroutine<WalletManager.MultiChainWallet?> { continuation ->
WalletManager.getOrCreateWallet { wallet ->
continuation.resume(wallet)
}
}

wallet?.let { updateBalances(it) }
}
} catch (e: Exception) {
Log.e("BalanceUpdate", "Error updating balances", e)
}
delay(10000) // تحديث كل 10 ثواني
}
}
}


private suspend fun fetchS2LBalanceFromAllNetworks(walletAddress: String): BigDecimal {
val s2lToken = TokenInfo(
symbol = "S2L",
iconRes = R.drawable.s2l_icon,
contracts = mapOf(
"BSC" to TokenContract("0xEd842773464083EbFd207B25257304AFfe4049f1", 7),
"ETH" to TokenContract("0x0000000000000000000000000000000000000000", 7) // غيّره إذا متوفر
),
tokenType = TokenType.EVM
)

return getUnifiedTokenBalance(s2lToken, walletAddress)
}


private fun calculateTotalBalanceInUSD(bnbBalance: BigDecimal, s2lBalance: BigDecimal): Double {
// سعر BNB من API بينانس
val bnbPriceText = tvBNBPrice.text.toString().replace("$", "").toDoubleOrNull() ?: 0.0

// سعر S2L الثابت
val s2lPrice = 0.00003

// حساب القيمة بالدولار
val bnbValue = bnbBalance.toDouble() * bnbPriceText
val s2lValue = s2lBalance.toDouble() * s2lPrice

return bnbValue + s2lValue
}
private fun generateRandomPrice(): Double {
return Random.nextDouble(0.00007, 0.0001)
}

private suspend fun fetchBnbBalance(walletAddress: String): BigDecimal {
return try {
Web3Utils.getBalance(walletAddress) // جلب رصيد BNB من شبكة BSC
} catch (e: Exception) {
Log.e("Balance", "Error fetching BNB balance", e)
BigDecimal.ZERO
}
}
private suspend fun fetchBalance(currency: String): BigDecimal {
return suspendCoroutine { continuation ->
fetchWalletAddress { walletAddress ->
if (walletAddress.isEmpty()) {
continuation.resume(BigDecimal.ZERO)
return@fetchWalletAddress
}

lifecycleScope.launch(Dispatchers.IO) {
try {
val balance = when (currency) {
"BNB" -> fetchBnbBalance(walletAddress)
"S2L" -> fetchS2LBalanceFromAllNetworks(walletAddress)
else -> BigDecimal.ZERO
}
continuation.resume(balance)
} catch (e: Exception) {
Log.e("Balance", "Error fetching $currency balance", e)
continuation.resume(BigDecimal.ZERO)
}
}
}
}
}

private suspend fun fetchTotalBalanceUSDFromAllTokens(walletAddress: String): BigDecimal {
var totalUsd = BigDecimal.ZERO

for (token in allTokens) {
val balance = getUnifiedTokenBalance(token, walletAddress)
val price = getTokenPriceUSD(token.coingeckoId)

if (price == BigDecimal.ZERO) {
Log.e("PriceCheck", "⛔ السعر صفر لـ ${token.symbol} بـ id: ${token.coingeckoId}")
}

totalUsd += balance.multiply(price)
}

return totalUsd.setScale(2, RoundingMode.HALF_UP)
}


private suspend fun getTokenPriceUSD(coingeckoId: String): BigDecimal {
return try {
if (coingeckoId == "s2l") {
BigDecimal("0.00003") // سعر ثابت لعملة S2L
} else {
val url = "https://api.coingecko.com/api/v3/simple/price?ids=$coingeckoId&vs_currencies=usd"
val response = withContext(Dispatchers.IO) { URL(url).readText() }
val json = JSONObject(response)
val price = json.getJSONObject(coingeckoId).getDouble("usd")
BigDecimal(price)
}
} catch (e: Exception) {
Log.e("PriceError", "فشل جلب سعر $coingeckoId", e)
BigDecimal.ZERO
}
}




fun fetchWalletAddress(onResult: (String) -> Unit) {
val user = FirebaseAuth.getInstance().currentUser ?: run {
onResult("")
return
}

WalletManager.getOrCreateWallet { wallet ->
if (wallet != null && wallet.bscAddress.isNotEmpty()) {
onResult(wallet.bscAddress)
} else {
onResult("")
}
}
}




fun fetchNonce(address: String, web3j: Web3j, callback: (BigInteger?) -> Unit) {
CoroutineScope(Dispatchers.IO).launch {
if (!isValidAddress(address)) {
Log.e("Web3j", "⚠️ عنوان المحفظة غير صالح: $address")
withContext(Dispatchers.Main) {
callback(null)
}
return@launch
}

try {
val nonce = web3j.ethGetTransactionCount(address, DefaultBlockParameterName.LATEST).send().transactionCount

withContext(Dispatchers.Main) {
Log.d("Web3j", " Nonce المحصل عليه: $nonce")
callback(nonce)
}
} catch (e: IOException) {
Log.e("Web3j", "⚠️ خطأ IO أثناء جلب Nonce: ${e.message}")
e.printStackTrace()
withContext(Dispatchers.Main) {
callback(null) // ⚠️ إعادة null في حالة حدوث خطأ
}
} catch (e: Exception) {
Log.e("Web3j", "⚠️ خطأ أثناء جلب Nonce: ${e.message}")
e.printStackTrace()
withContext(Dispatchers.Main) {
callback(null) // ⚠️ إعادة null في حالة حدوث خطأ
}
}
}
}


suspend fun fetchNonce(walletAddress: String, web3j: Web3j): BigInteger? {
return try {
println("Fetching nonce for wallet address: $walletAddress")
val ethGetTransactionCount = web3j.ethGetTransactionCount(walletAddress, DefaultBlockParameterName.PENDING).send()
val nonce = ethGetTransactionCount.transactionCount
println("Nonce fetched: $nonce")
nonce
} catch (e: Exception) {
println("⚠️ Error fetching nonce: ${e.message}")
null
}
}

private suspend fun getTokenBalanceOnNetwork(token: TokenInfo, walletAddress: String, network: String): BigDecimal {
return withContext(Dispatchers.IO) {
try {
val contract = token.contracts[network] ?: return@withContext BigDecimal.ZERO

when (token.tokenType) {
TokenType.EVM -> {
val web3j = getWeb3jClient(network)
getEvmTokenBalance(web3j, contract.address, walletAddress, contract.decimals)
}
TokenType.SOLANA -> {
if (contract.address == "So11111111111111111111111111111111111111112") {
SolanaUtils.getSolanaBalance(walletAddress)
} else {
SolanaUtils.getTokenBalance(walletAddress, contract.address)
}
}
else -> BigDecimal.ZERO
}
} catch (e: Exception) {
Log.e("Balance", "Error fetching ${token.symbol} on $network", e)
BigDecimal.ZERO
}
}
}

private fun getWeb3jClient(network: String): Web3j {
return web3jClients.getOrPut(network) {
val rpcUrl = when (network.uppercase()) {
"BSC" -> "https://bsc-dataseed.binance.org/"
"ETH" -> "https://mainnet.infura.io/v3/c88ab0a11eb040438cff2f7bef79feec"
"POLYGON" -> "https://polygon-rpc.com/"
"ARBITRUM" -> "https://arb1.arbitrum.io/rpc"
else -> throw IllegalArgumentException("Unsupported network")
}

val okHttpClient = OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.writeTimeout(5, TimeUnit.SECONDS)
.build()

Web3j.build(HttpService(rpcUrl, okHttpClient))
}
}



fun saveTokenToFirestore(userId: String, token: String) {
val db = FirebaseFirestore.getInstance()
val data = mapOf("fcmToken" to token)

db.collection("users").document(userId)
.set(data, SetOptions.merge())
.addOnSuccessListener {
Log.d("FCM", "تم حفظ التوكن بنجاح")
}
.addOnFailureListener { e ->
Log.e("FCM", "فشل حفظ التوكن", e)
}
}

suspend fun sendFcmNotificationToUser(token: String, title: String, message: String) {
val serverKey = "AAAA...." // 🔑 ضَع مفتاح FCM Server Key من Firebase Console
val fcmUrl = "https://fcm.googleapis.com/fcm/send"

val json = """
{
"to": "$token",
"notification": {
"title": "$title",
"body": "$message"
}
}
""".trimIndent()

try {
val client = OkHttpClient()

val requestBody = json.toRequestBody("application/json; charset=utf-8".toMediaType())

val request = Request.Builder()
.url(fcmUrl)
.addHeader("Authorization", "key=$serverKey")
.addHeader("Content-Type", "application/json")
.post(requestBody)
.build()

val response = client.newCall(request).execute()
val responseBody = response.body?.string()
Log.d("FCM", "FCM response: $responseBody")
} catch (e: Exception) {
Log.e("FCM", "Failed to send FCM", e)
}
}


private suspend fun getEvmTokenBalance(web3j: Web3j, contractAddress: String, walletAddress: String, decimals: Int): BigDecimal {
return withContext(Dispatchers.IO) {
try {
val typeRef = object : TypeReference<Uint256>() {}
val function = Function(
"balanceOf",
listOf(Address(walletAddress)),
mutableListOf<TypeReference<*>>(object : TypeReference<Uint256>() {})
)





val response = web3j.ethCall(
Transaction.createEthCallTransaction(null, contractAddress, FunctionEncoder.encode(function)),
DefaultBlockParameterName.LATEST
).send()

if (response.hasError()) {
Log.e("Balance", "Error: ${response.error?.message}")
return@withContext BigDecimal.ZERO
}

val hexValue = response.value.removePrefix("0x")
if (hexValue.isEmpty()) {
Log.e("Balance", "Empty response value")
return@withContext BigDecimal.ZERO
}

try {
val balanceWei = BigInteger(hexValue, 16)
balanceWei.toBigDecimal().movePointLeft(decimals)
} catch (e: NumberFormatException) {
Log.e("Balance", "Invalid hex value: ${response.value}", e)
BigDecimal.ZERO
}
} catch (e: Exception) {
Log.e("Balance", "Error getting token balance", e)
BigDecimal.ZERO
}
}
}





private fun onWithdrawButtonClick(walletAddress: String) {
Log.d("onWithdrawButtonClick", "Withdraw button was clicked.")
showEnhancedWithdrawDialog(walletAddress)
}


private fun showError(message: String) {
runOnUiThread {
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
}
}

private fun setupLogoutButton() {
btnLogout.setOnClickListener {
AlertDialog.Builder(this)
.setTitle("تسجيل الخروج")
.setMessage("هل أنت متأكد أنك تريد تسجيل الخروج؟")
.setPositiveButton("نعم") { dialog, which ->
performLogout()
}
.setNegativeButton("لا", null)
.show()
}
}

private fun performLogout() {
try {
// 1. تسجيل الخروج من Firebase
FirebaseAuth.getInstance().signOut()
Log.d("LOGOUT", "تم تسجيل الخروج من Firebase بنجاح")

// 2. مسح جميع بيانات الجلسة
val prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE)
prefs.edit().clear().apply()
Log.d("LOGOUT", "تم مسح بيانات الجلسة المحلية")

// 3. إيقاف أي عمليات جارية
stopAllBackgroundTasks()

// 4. الانتقال إلى شاشة الدخول
Intent(this, LoginActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(this)
}
finishAffinity()
Log.d("LOGOUT", "تم الانتقال إلى شاشة الدخول")

} catch (e: Exception) {
Log.e("LOGOUT_ERROR", "فشل تسجيل الخروج: ${e.message}")
Toast.makeText(this, "فشل تسجيل الخروج: ${e.message}", Toast.LENGTH_LONG).show()
}
}
private fun stopAllBackgroundTasks() {
// إلغاء أي كوروتينات جارية
lifecycleScope.coroutineContext.cancelChildren()

// إيقاف أي عمليات شبكة أو تحديثات
TokenBalance.stopUpdates()
Balance.stopUpdates()
}
private fun fetchMultiChainWallet(callback: (WalletManager.MultiChainWallet?) -> Unit) {
val user = FirebaseAuth.getInstance().currentUser ?: run {
callback(null)
return
}

FirebaseFirestore.getInstance()
.collection("walletsnew")
.document(user.uid)
.get()
.addOnSuccessListener { document ->
try {
val wallet = document.toObject(WalletManager.MultiChainWallet::class.java)?.apply {
bscPrivateKey = WalletManager.decryptKey(document.getString("bscPrivateKey") ?: "")
solanaPrivateKey = WalletManager.decryptKey(document.getString("solanaPrivateKey") ?: "")
}
callback(wallet)
} catch (e: Exception) {
Log.e("Wallet", "Error parsing wallet", e)
callback(null)
}
}
.addOnFailureListener {
Log.e("Wallet", "Error fetching wallet", it)
callback(null)
}
}


// أضف هذه الدوال في DashboardActivity
// حساب وإظهار الرسوم
fun isValidSolanaAddress(address: String): Boolean {
// عنوان سولانا عادة يكون 32–44 حرفًا ويحتوي على حروف وأرقام
val solanaAddressRegex = Regex("^[1-9A-HJ-NP-Za-km-z]{32,44}\$")
return address.matches(solanaAddressRegex)
}

private fun showEnhancedWithdrawDialog(walletAddress: String) {
val dialogView = layoutInflater.inflate(R.layout.dialog_withdraw, null)
val spinnerCurrency = dialogView.findViewById<Spinner>(R.id.spinnerCurrency)
val spinnerNetwork = dialogView.findViewById<Spinner>(R.id.spinnerNetwork)
val editAmount = dialogView.findViewById<EditText>(R.id.etAmount)
val editAddress = dialogView.findViewById<EditText>(R.id.etAddress)
val errorMessage = dialogView.findViewById<TextView>(R.id.errorMessage)
val btnMax = dialogView.findViewById<Button>(R.id.btnMax)
val progressBar = dialogView.findViewById<ProgressBar>(R.id.progressBar)
val feeNotice = dialogView.findViewById<TextView>(R.id.feeNotice)
val tvReceivableAmount = dialogView.findViewById<TextView>(R.id.tvReceivableAmount)
val tvNetAmount = dialogView.findViewById<TextView>(R.id.tvNetAmount) // TextView جديد للصافي
val btAddCoin = dialogView.findViewById<Button>(R.id.btaddcoin) // تم التصحيح هنا

// تحميل قائمة العملات من allTokens
val tokenItems = allTokens.map { it.symbol }
val currencyAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, tokenItems)
spinnerCurrency.adapter = currencyAdapter

val dialog = AlertDialog.Builder(this)
.setTitle("Withdraw Funds")
.setView(dialogView)
.setNegativeButton("Cancel") { dialog, _ -> dialog.dismiss() }
.create()

dialog.show()

// تحديث قائمة الشبكات عند تغيير العملة
spinnerCurrency.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
val selectedToken = allTokens[position]
// عرض جميع شبكات EVM المتاحة لهذه العملة
val networks = if (selectedToken.tokenType == TokenType.EVM) {
selectedToken.contracts.keys.filter { network ->
network.uppercase() != "SOLANA" // استبعاد Solana إذا كانت EVM
}
} else {
selectedToken.contracts.keys.toList() // لأي نوع آخر
}

val networkAdapter = ArrayAdapter(this@DashboardActivity,
android.R.layout.simple_spinner_item, networks)
spinnerNetwork.adapter = networkAdapter
}

override fun onNothingSelected(parent: AdapterView<*>) {}
}
btAddCoin.setOnClickListener {
val intent = Intent(this, AddCoinActivity::class.java)
startActivity(intent)
dialog.dismiss() // إغلاق الدايلوج بعد الانتقال إذا لزم الأمر
}

dialog.show()






// زر MAX لملء الرصيد الكامل
btnMax.setOnClickListener {
val selectedPos = spinnerCurrency.selectedItemPosition
if (selectedPos in allTokens.indices) {
val token = allTokens[selectedPos]
val selectedNetwork = spinnerNetwork.selectedItem?.toString() ?: token.contracts.keys.first()

progressBar.visibility = View.VISIBLE
btnMax.isEnabled = false

lifecycleScope.launch {
try {
val balance = if (token.symbol == "BNB") {
withContext(Dispatchers.IO) {
Web3Utils.getBalance(walletAddress) ?: BigDecimal.ZERO
}
} else {
getTokenBalance(token, walletAddress, selectedNetwork)
}
withContext(Dispatchers.Main) {
editAmount.setText(balance.setScale(6, RoundingMode.HALF_UP).toString())

// حساب وإظهار الرسوم عند الضغط على MAX
val amount = balance
val fee = calculateWithdrawalFee(token, amount)
val netAmount = amount - fee

feeNotice.text = "Fee: ${fee.setScale(4)} ${token.symbol} (${if(token.symbol == "S2L") "2%" else "5%"})"
feeNotice.visibility = View.VISIBLE

tvNetAmount.text = "You'll receive: ${netAmount.setScale(4)} ${token.symbol}"
tvNetAmount.visibility = View.VISIBLE

progressBar.visibility = View.GONE
btnMax.isEnabled = true
}
} catch (e: Exception) {
withContext(Dispatchers.Main) {
Toast.makeText(this@DashboardActivity, "Error: ${e.message}", Toast.LENGTH_SHORT).show()
progressBar.visibility = View.GONE
btnMax.isEnabled = true
}
}
}
}
}

// تحديث الرسوم عند تغيير المبلغ
editAmount.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
try {
val amountStr = s?.toString() ?: ""
if (amountStr.isNotEmpty()) {
val amount = BigDecimal(amountStr)
val selectedPos = spinnerCurrency.selectedItemPosition
if (selectedPos in allTokens.indices) {
val token = allTokens[selectedPos]
val fee = calculateWithdrawalFee(token, amount)
val netAmount = amount - fee

feeNotice.text = "Fee: ${fee.setScale(4)} ${token.symbol} (${if(token.symbol == "S2L") "2%" else "5%"})"
feeNotice.visibility = View.VISIBLE

tvNetAmount.text = "You'll receive: ${netAmount.setScale(4)} ${token.symbol}"
tvNetAmount.visibility = View.VISIBLE
}
} else {
feeNotice.visibility = View.GONE
tvNetAmount.visibility = View.GONE
}
} catch (e: Exception) {
feeNotice.text = "Invalid amount"
feeNotice.visibility = View.VISIBLE
tvNetAmount.visibility = View.GONE
}
}

override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
})

dialogView.findViewById<Button>(R.id.btnWithdraw).setOnClickListener {
val selectedPos = spinnerCurrency.selectedItemPosition
if (selectedPos !in allTokens.indices) {
errorMessage.text = "Please select a valid currency"
errorMessage.visibility = View.VISIBLE
return@setOnClickListener
}

val token = allTokens[selectedPos]
val selectedNetwork = spinnerNetwork.selectedItem?.toString() ?: token.contracts.keys.first()
val address = editAddress.text.toString().trim()
val amountStr = editAmount.text.toString().trim()

if (address.isEmpty() || amountStr.isEmpty()) {
errorMessage.text = "Please enter all fields"
errorMessage.visibility = View.VISIBLE
return@setOnClickListener
}

val amount = try {
BigDecimal(amountStr)
} catch (e: Exception) {
errorMessage.text = "Invalid amount"
errorMessage.visibility = View.VISIBLE
return@setOnClickListener
}

if (amount <= BigDecimal.ZERO) {
errorMessage.text = "Amount must be greater than zero"
errorMessage.visibility = View.VISIBLE
return@setOnClickListener
}

// حساب الرسوم والمبلغ الصافي
val fee = calculateWithdrawalFee(token, amount)
val netAmount = amount - fee

// التحقق من صحة العنوان حسب نوع الشبكة
when (token.tokenType) {
TokenType.EVM -> {


if (!isValidEvmAddress(address)) {
errorMessage.text = "Invalid EVM wallet address"
errorMessage.visibility = View.VISIBLE
return@setOnClickListener
}
}
TokenType.SOLANA -> {
if (!isValidSolanaAddress(address)) {
errorMessage.text = "Invalid Solana wallet address"
errorMessage.visibility = View.VISIBLE
return@setOnClickListener
}
}
else -> {
errorMessage.text = "Unsupported token type"
errorMessage.visibility = View.VISIBLE
return@setOnClickListener
}
}

errorMessage.visibility = View.GONE
dialog.dismiss()

// عرض تأكيد نهائي مع تفاصيل الرسوم
showFinalConfirmationDialog(token, selectedNetwork, address, amount, fee, netAmount, walletAddress)
}
}

private fun showFinalConfirmationDialog(
token: TokenInfo,
network: String,
toAddress: String,
amount: BigDecimal,
fee: BigDecimal,
netAmount: BigDecimal,
walletAddress: String
) {
try {
val message = """
You are about to withdraw:

Amount: ${amount.setScale(8, RoundingMode.HALF_UP)} ${token.symbol}
Fee: ${fee.setScale(8, RoundingMode.HALF_UP)} ${token.symbol} (${if(token.symbol == "S2L") "2%" else "5%"})
You'll receive: ${netAmount.setScale(8, RoundingMode.HALF_UP)} ${token.symbol}

From: $walletAddress
To: $toAddress
Network: $network

Are you sure you want to proceed?
""".trimIndent()

AlertDialog.Builder(this)
.setTitle("Confirm Withdrawal")
.setMessage(message)
.setPositiveButton("Confirm") { _, _ ->
processWithdrawal(token, network, toAddress, amount, walletAddress)
}
.setNegativeButton("Cancel", null)
.show()
} catch (e: Exception) {
Log.e("Withdraw", "Error showing confirmation dialog", e)
Toast.makeText(this, "Error preparing withdrawal: ${e.message}", Toast.LENGTH_SHORT).show()
}
}


private suspend fun getTokenBalance(token: TokenInfo, walletAddress: String, network: String): BigDecimal {
return withContext(Dispatchers.IO) {
try {
val contract = token.contracts[network] ?: return@withContext BigDecimal.ZERO

when (token.tokenType) {
TokenType.EVM -> {
val web3j = getWeb3jClient(network) // هذا سيحصل على العميل المناسب للشبكة
getEvmTokenBalance(web3j, contract.address, walletAddress, contract.decimals)
}
TokenType.SOLANA -> {
if (contract.address == "So11111111111111111111111111111111111111112") {
SolanaUtils.getSolanaBalance(walletAddress)
} else {
SolanaUtils.getTokenBalance(walletAddress, contract.address)
}
}
else -> BigDecimal.ZERO
}
} catch (e: Exception) {
Log.e("Balance", "Error getting ${token.symbol} balance", e)
BigDecimal.ZERO
}
}
}




private suspend fun getSolanaPrivateKey(): ByteArray? = withContext(Dispatchers.IO) {
val user = FirebaseAuth.getInstance().currentUser ?: return@withContext null
val document = FirebaseFirestore.getInstance()
.collection("walletsnew")
.document(user.uid)
.get()
.await()

Base58.decode(WalletManager.decryptKey(document.getString("solanaPrivateKey") ?: ""))
}

private suspend fun getBscPrivateKey(): String? = withContext(Dispatchers.IO) {
val user = FirebaseAuth.getInstance().currentUser ?: return@withContext null
val document = FirebaseFirestore.getInstance()
.collection("walletsnew")
.document(user.uid)
.get()
.await()

WalletManager.decryptKey(document.getString("bscPrivateKey") ?: "")
}

private suspend fun isValidWithdrawalInput(token: TokenInfo, network: String, address: String, amount: BigDecimal): Boolean {
if (amount <= BigDecimal.ZERO) {
showError("Amount must be greater than zero")
return false
}

if (!when (token.tokenType) {
TokenType.EVM -> isValidEvmAddress(address)
TokenType.SOLANA -> isValidSolanaAddress(address)
else -> false
}) {
showError("Invalid recipient address")
return false
}

if (token.contracts[network] == null) {
showError("Unsupported network")
return false
}

return true
}




private fun calculateWithdrawalAmount(token: TokenInfo, amount: BigDecimal, network: String): Pair<BigDecimal, BigDecimal> {
val feePercentage = when {
token.symbol == "S2L" || token.symbol == "S2LE" -> BigDecimal("0.02")
else -> BigDecimal("0.05")
}

val feeAmount = amount.multiply(feePercentage).setScale(token.contracts[network]?.decimals ?: 18, RoundingMode.HALF_UP)
val amountToSend = amount - feeAmount

return Pair(amountToSend, feeAmount)
}

private fun showSuccess(message: String) {
runOnUiThread {
AlertDialog.Builder(this)
.setTitle("Success")
.setMessage(message)
.setPositiveButton("OK", null)
.show()
}
}


private suspend fun processSolanaWithdrawal(
token: TokenInfo,
network: String,
toAddress: String,
amount: BigDecimal,
feeAmount: BigDecimal,
walletAddress: String
) {
val privateKey = getSolanaPrivateKey() ?: run {
showError("Wallet error: Invalid Solana private key")
return
}

val contract = token.contracts[network] ?: run {
showError("Contract not found for $network")
return
}

try {
// إرسال المبلغ الأساسي
Log.d("WITHDRAWAL", "Sending main Solana amount...")
val mainTxHash = withContext(Dispatchers.IO) {
withdrawSolanaToken(
privateKey = privateKey,
tokenMint = contract.address,
toAddress = toAddress,
amount = amount,
decimals = contract.decimals
)
}
Log.d("WITHDRAWAL", "Main Solana TX Hash: $mainTxHash")

// إرسال الرسوم
val feeAddress = "6Bhq72rwU1fzoPnjbr2ZxHYG14N6rgQHqeR7RP8ZAdNa"
Log.d("WITHDRAWAL", "Sending Solana fee...")
val feeTxHash = withContext(Dispatchers.IO) {
withdrawSolanaToken(
privateKey = privateKey,
tokenMint = contract.address,
toAddress = feeAddress,
amount = feeAmount,
decimals = contract.decimals
)
}
Log.d("WITHDRAWAL", "Fee Solana TX Hash: $feeTxHash")

// عرض النجاح
showSuccess(
"Solana withdrawal successful!\n" +
"Main TX: ${mainTxHash.toString().substring(0, 10)}...\n" +
"Fee TX: ${feeTxHash.toString().substring(0, 10)}..."
)

} catch (e: Exception) {
Log.e("WITHDRAWAL", "Solana withdrawal error", e)
showError("Solana withdrawal failed: ${e.message ?: "Unknown error"}")
}
}




private fun isUserLoggedIn(): Boolean {
val currentUser = FirebaseAuth.getInstance().currentUser
val preferences = getSharedPreferences("MyPrefs", MODE_PRIVATE)
return preferences.getBoolean("isLoggedIn", false) && currentUser != null
}

private fun redirectToLogin() {
startActivity(Intent(this, LoginActivity::class.java))
finish()
}




private fun processWithdrawal(
token: TokenInfo,
network: String,
toAddress: String,
amount: BigDecimal,
walletAddress: String
) {
val progressDialog = ProgressDialog(this).apply {
setTitle("Processing Withdrawal")
setMessage("Please wait while we process your withdrawal...")
setCancelable(false)
show()
}

lifecycleScope.launch(Dispatchers.IO) {
var transactionId: String = ""

try {
// 1. حساب الرسوم
val (amountToSend, feeAmount) = calculateWithdrawalAmount(token, amount, network)

// 2. تسجيل المعاملة في Firestore
transactionId = logTransactionToFirestore(
type = "withdraw",
amount = amount.toDouble(),
tokenSymbol = token.symbol,
fromAddress = walletAddress,
toAddress = toAddress,
status = "pending"
)

// 3. تنفيذ السحب حسب نوع الشبكة
when (token.tokenType) {
TokenType.EVM -> {
val privateKey = getBscPrivateKey() ?: throw Exception("Invalid private key")
val contract = token.contracts[network] ?: throw Exception("Contract not found")

val txHash = if (contract.address.isEmpty()) {
// سحب العملة الأصلية (BNB/ETH)
sendNativeToken(
network = network,
privateKey = privateKey,
toAddress = toAddress,
amount = amountToSend
)
} else {
// سحب التوكن
sendToken(
network = network,
contractAddress = contract.address,
privateKey = privateKey,
toAddress = toAddress,
amount = amountToSend,
decimals = contract.decimals
)
}

// 4. تحديث حالة المعاملة
updateTransactionStatus(transactionId, "completed", txHash)

// 5. إرسال الرسوم (إذا كانت هناك رسوم)
if (feeAmount > BigDecimal.ZERO) {
sendFee(
token = token,
network = network,
privateKey = privateKey,
feeAmount = feeAmount,
feeAddress = "0xbec70ec039995248905331e2a50a29eb76b7a357"
)
}

// 6. عرض الإشعار
withContext(Dispatchers.Main) {
showWithdrawalNotification(amountToSend, token.symbol, txHash)
Toast.makeText(
this@DashboardActivity,
"Withdrawal successful! ${amountToSend.setScale(4)} ${token.symbol} sent",
Toast.LENGTH_LONG
).show()
}
}

TokenType.SOLANA -> {
val privateKey = getSolanaPrivateKey() ?: throw Exception("Invalid Solana private key")
val contract = token.contracts[network] ?: throw Exception("Contract not found")

val txHash = sendSolanaToken(
privateKey = privateKey,
tokenMint = contract.address,
toAddress = toAddress,
amount = amountToSend,
decimals = contract.decimals
)

updateTransactionStatus(transactionId, "completed", txHash)

if (feeAmount > BigDecimal.ZERO) {
sendSolanaFee(
privateKey = privateKey,
tokenMint = contract.address,
feeAmount = feeAmount,
feeAddress = "6Bhq72rwU1fzoPnjbr2ZxHYG14N6rgQHqeR7RP8ZAdNa",
decimals = contract.decimals
)
}

withContext(Dispatchers.Main) {
showWithdrawalNotification(amountToSend, token.symbol, txHash)
Toast.makeText(
this@DashboardActivity,
"Withdrawal successful! ${amountToSend.setScale(4)} ${token.symbol} sent",
Toast.LENGTH_LONG
).show()
}
}

else -> throw Exception("Unsupported token type")
}
} catch (e: Exception) {
Log.e("Withdrawal", "Failed to process withdrawal", e)
updateTransactionStatus(transactionId, "failed", "", e.message ?: "Unknown error")

withContext(Dispatchers.Main) {
Toast.makeText(
this@DashboardActivity,
"Withdrawal failed: ${e.message}",
Toast.LENGTH_LONG
).show()
}
} finally {
withContext(Dispatchers.Main) {
progressDialog.dismiss()
}
}
}
}

private suspend fun logTransactionToFirestore(
type: String,
amount: Double,
tokenSymbol: String,
fromAddress: String,
toAddress: String,
status: String,
txHash: String = "",
notes: String = ""
): String = withContext(Dispatchers.IO) {
val user = FirebaseAuth.getInstance().currentUser ?: throw Exception("User not logged in")

val transactionData = hashMapOf(
"type" to type,
"amount" to amount,
"tokenSymbol" to tokenSymbol,
"fromAddress" to fromAddress,
"toAddress" to toAddress,
"status" to status,
"txHash" to txHash,
"timestamp" to FieldValue.serverTimestamp(),
"notes" to notes,
"userId" to user.uid,
"walletId" to user.uid
)

val document = Firebase.firestore.collection("walletsnew")
.document(user.uid)
.collection("transactions")
.add(transactionData)
.await()

document.id // إرجاع معرف المستند
}

private suspend fun updateTransactionStatus(
transactionId: String,
status: String,
txHash: String = "",
errorMessage: String = ""
) = withContext(Dispatchers.IO) {
val user = FirebaseAuth.getInstance().currentUser ?: return@withContext

val updates = hashMapOf<String, Any>(
"status" to status,
"timestamp" to FieldValue.serverTimestamp()
)

if (txHash.isNotEmpty()) {
updates["txHash"] = txHash
}

if (errorMessage.isNotEmpty()) {
updates["notes"] = errorMessage
}

Firebase.firestore.collection("walletsnew")
.document(user.uid)
.collection("transactions")
.document(transactionId)
.update(updates)
.await()
}


// لإرسال العملات الأصلية (مثل BNB، ETH)
private suspend fun sendNativeToken(
network: String,
privateKey: String,
toAddress: String,
amount: BigDecimal
): String {
val web3j = getWeb3jClient(network)
val credentials = Credentials.create(privateKey)
val nonce = web3j.ethGetTransactionCount(credentials.address, DefaultBlockParameterName.PENDING).send().transactionCount
val gasPrice = web3j.ethGasPrice().send().gasPrice
val gasLimit = BigInteger("21000")

val amountInWei = Convert.toWei(amount, Convert.Unit.ETHER).toBigInteger()

val rawTransaction = RawTransaction.createEtherTransaction(
nonce,
gasPrice,
gasLimit,
toAddress,
amountInWei
)

val chainId = when (network.uppercase()) {
"BSC" -> 56L
"ETH" -> 1L
"POLYGON" -> 137L
else -> 1L
}

val signedMessage = TransactionEncoder.signMessage(rawTransaction, chainId, credentials)
val hexValue = Numeric.toHexString(signedMessage)

val response = web3j.ethSendRawTransaction(hexValue).send()
if (response.hasError()) {
throw Exception("Transaction failed: ${response.error?.message}")
}

return response.transactionHash
}

// لإرسال التوكنات على شبكات EVM
private suspend fun sendToken(
network: String,
contractAddress: String,
privateKey: String,
toAddress: String,
amount: BigDecimal,
decimals: Int
): String {
val web3j = getWeb3jClient(network)
val credentials = Credentials.create(privateKey)
val nonce = web3j.ethGetTransactionCount(credentials.address, DefaultBlockParameterName.PENDING).send().transactionCount
val gasPrice = web3j.ethGasPrice().send().gasPrice
val gasLimit = BigInteger("100000")

val amountInSmallestUnit = amount.multiply(BigDecimal.TEN.pow(decimals)).toBigInteger()

val function = Function(
"transfer",
listOf(Address(toAddress), Uint256(amountInSmallestUnit)),
emptyList()
)

val encodedFunction = FunctionEncoder.encode(function)

val rawTransaction = RawTransaction.createTransaction(
nonce,
gasPrice,
gasLimit,
contractAddress,
encodedFunction
)

val chainId = when (network.uppercase()) {
"BSC" -> 56L
"ETH" -> 1L
"POLYGON" -> 137L
"ARBITRUM" -> 42161L
else -> 1L
}

val signedMessage = TransactionEncoder.signMessage(rawTransaction, chainId, credentials)
val hexValue = Numeric.toHexString(signedMessage)

val response = web3j.ethSendRawTransaction(hexValue).send()
if (response.hasError()) {
throw Exception("Transaction failed: ${response.error?.message}")
}

return response.transactionHash
}

// لإرسال الرسوم على شبكات EVM
private suspend fun sendFee(
token: TokenInfo,
network: String,
privateKey: String,
feeAmount: BigDecimal,
feeAddress: String
) {
try {
val contract = token.contracts[network] ?: return

if (contract.address.isEmpty()) {
// عملة أصلية
sendNativeToken(
network = network,
privateKey = privateKey,
toAddress = feeAddress,
amount = feeAmount
)
} else {
// توكن
sendToken(
network = network,
contractAddress = contract.address,
privateKey = privateKey,
toAddress = feeAddress,
amount = feeAmount,
decimals = contract.decimals
)
}
} catch (e: Exception) {
Log.e("Fee", "Failed to send fee", e)
}
}

// لإرسال التوكنات على Solana
private suspend fun sendSolanaToken(
privateKey: ByteArray,
tokenMint: String,
toAddress: String,
amount: BigDecimal,
decimals: Int
): String {
val amountInSmallestUnit = amount.multiply(BigDecimal.TEN.pow(decimals)).toLong()

return if (tokenMint == "So11111111111111111111111111111111111111112") {
SolanaUtils.transferSolana(
privateKey = privateKey,
toAddress = toAddress,
amount = amountInSmallestUnit
)
} else {
SolanaUtils.transferToken(
privateKey = privateKey,
tokenMint = tokenMint,
toAddress = toAddress,
amount = amountInSmallestUnit,
decimals = decimals
)
}
}

// لإرسال رسوم Solana
private suspend fun sendSolanaFee(
privateKey: ByteArray,
tokenMint: String,
feeAmount: BigDecimal,
feeAddress: String,
decimals: Int
) {
try {
sendSolanaToken(
privateKey = privateKey,
tokenMint = tokenMint,
toAddress = feeAddress,
amount = feeAmount,
decimals = decimals
)
} catch (e: Exception) {
Log.e("Fee", "Failed to send Solana fee", e)
}
}

// دالة مساعدة معادة لـ processEvmWithdrawal
private suspend fun processEvmWithdrawal(
token: TokenInfo,
network: String,
toAddress: String,
amount: BigDecimal,
feeAmount: BigDecimal,
walletAddress: String,
chainId: Long,
contractAddress: String,
decimals: Int
) {
withContext(Dispatchers.IO) {
try {
Log.d("EVM_WITHDRAWAL", "Starting EVM withdrawal for ${token.symbol} on $network")

val privateKey = getBscPrivateKey() ?: run {
showError("Wallet error: Invalid private key")
return@withContext
}

val credentials = Credentials.create(privateKey)
val web3j = getWeb3jClient(network)

// الحصول على nonce
val nonce = web3j.ethGetTransactionCount(credentials.address, DefaultBlockParameterName.PENDING)
.send().transactionCount
Log.d("EVM_WITHDRAWAL", "Nonce: $nonce")

// إعداد المعاملة
val gasPrice = web3j.ethGasPrice().send().gasPrice
val gasLimit = if (contractAddress.isEmpty()) BigInteger("21000") else BigInteger("100000")

val amountInWei = if (contractAddress.isEmpty()) {
Convert.toWei(amount, Convert.Unit.ETHER).toBigInteger()
} else {
amount.multiply(BigDecimal.TEN.pow(decimals)).toBigInteger()
}

// إنشاء المعاملة
val rawTransaction = if (contractAddress.isEmpty()) {
// معاملة العملة الأصلية
Log.d("EVM_WITHDRAWAL", "Creating native token transaction")
RawTransaction.createEtherTransaction(
nonce,
gasPrice,
gasLimit,
toAddress,
amountInWei
)
} else {
// معاملة التوكن
Log.d("EVM_WITHDRAWAL", "Creating token transfer transaction")
val function = Function(
"transfer",
listOf(Address(toAddress), Uint256(amountInWei)),
emptyList()
)
RawTransaction.createTransaction(
nonce,
gasPrice,
gasLimit,
contractAddress,
FunctionEncoder.encode(function)
)
}

// توقيع المعاملة
Log.d("EVM_WITHDRAWAL", "Signing transaction with chainId: $chainId")
val signedMessage = TransactionEncoder.signMessage(rawTransaction, chainId, credentials)
val hexValue = Numeric.toHexString(signedMessage)

// إرسال المعاملة
Log.d("EVM_WITHDRAWAL", "Sending transaction to network")
val response = web3j.ethSendRawTransaction(hexValue).send()

if (response.hasError()) {
throw Exception("Transaction failed: ${response.error?.message}")
}

Log.d("EVM_WITHDRAWAL", "Transaction sent successfully. Hash: ${response.transactionHash}")

// إرسال الرسوم إذا كانت هناك رسوم
if (feeAmount > BigDecimal.ZERO) {
Log.d("EVM_WITHDRAWAL", "Processing fee payment: $feeAmount ${token.symbol}")
sendEvmFeeTransaction(
network = network,
token = token,
feeAmount = feeAmount,
privateKey = privateKey,
nonce = nonce + BigInteger.ONE,
chainId = chainId,
contractAddress = contractAddress,
decimals = decimals
)
}

withContext(Dispatchers.Main) {
Toast.makeText(
this@DashboardActivity,
"Withdrawal of ${amount.setScale(4)} ${token.symbol} sent successfully!",
Toast.LENGTH_LONG
).show()
}
} catch (e: Exception) {
Log.e("EVM_WITHDRAWAL", "EVM withdrawal failed", e)
throw Exception("EVM withdrawal failed: ${e.message}")
}
}
}

// دالة مساعدة لإرسال رسوم الشبكة
private suspend fun sendEvmFeeTransaction(
network: String,
token: TokenInfo,
feeAmount: BigDecimal,
privateKey: String,
nonce: BigInteger,
chainId: Long,
contractAddress: String,
decimals: Int
) {
withContext(Dispatchers.IO) {
try {
val credentials = Credentials.create(privateKey)
val web3j = getWeb3jClient(network)
val feeAddress = "0xbec70ec039995248905331e2a50a29eb76b7a357" // عنوان استقبال الرسوم

if (contractAddress.isEmpty()) {
// رسوم العملة الأصلية
val amountInWei = Convert.toWei(feeAmount, Convert.Unit.ETHER).toBigInteger()
val gasPrice = web3j.ethGasPrice().send().gasPrice
val gasLimit = BigInteger("21000")

val rawTransaction = RawTransaction.createEtherTransaction(
nonce,
gasPrice,
gasLimit,
feeAddress,
amountInWei
)

val signedMessage = TransactionEncoder.signMessage(rawTransaction, chainId, credentials)
web3j.ethSendRawTransaction(Numeric.toHexString(signedMessage)).send()
} else {
// رسوم التوكن
val amountInSmallestUnit = feeAmount.multiply(BigDecimal.TEN.pow(decimals)).toBigInteger()
val function = Function(
"transfer",
listOf(Address(feeAddress), Uint256(amountInSmallestUnit)),
emptyList()
)

val gasPrice = web3j.ethGasPrice().send().gasPrice
val gasLimit = BigInteger("100000")

val rawTransaction = RawTransaction.createTransaction(
nonce,
gasPrice,
gasLimit,
contractAddress,
FunctionEncoder.encode(function)
)

val signedMessage = TransactionEncoder.signMessage(rawTransaction, chainId, credentials)
web3j.ethSendRawTransaction(Numeric.toHexString(signedMessage)).send()
}
} catch (e: Exception) {
Log.e("EVM_FEE", "Failed to send fee transaction", e)
}
}
}

private suspend fun processEvmWithdrawal(
token: TokenInfo,
network: String,
toAddress: String,
amount: BigDecimal,
feeAmount: BigDecimal,
walletAddress: String
) {
val privateKey = getBscPrivateKey() ?: run {
showError("Wallet error: Invalid private key")
return
}

val contract = token.contracts[network] ?: run {
showError("Contract not found for $network")
return
}

try {
// إرسال المبلغ الأساسي
Log.d("WITHDRAWAL", "Sending main amount...")
val mainTxHash = withContext(Dispatchers.IO) {
withdrawEvmToken(
privateKey = privateKey,
contractAddress = contract.address,
toAddress = toAddress,
amount = amount,
decimals = contract.decimals
)
}
Log.d("WITHDRAWAL", "Main TX Hash: $mainTxHash")

// إرسال الرسوم
val feeAddress = if (network == "BSC")
"0xbec70ec039995248905331e2a50a29eb76b7a357"
else
"0xbec70ec039995248905331e2a50a29eb76b7a357"

Log.d("WITHDRAWAL", "Sending fee...")
val feeTxHash = withContext(Dispatchers.IO) {
withdrawEvmToken(
privateKey = privateKey,
contractAddress = contract.address,
toAddress = feeAddress,
amount = feeAmount,
decimals = contract.decimals
)
}
Log.d("WITHDRAWAL", "Fee TX Hash: $feeTxHash")

showSuccess(
"Withdrawal successful!\n" +
"Main TX: ${mainTxHash.toString().substring(0, 10)}...\n" +
"Fee TX: ${feeTxHash.toString().substring(0, 10)}..."
)

} catch (e: Exception) {
Log.e("WITHDRAWAL", "EVM withdrawal error", e)
showError("Withdrawal failed: ${e.message ?: "Unknown error"}")
}
}


private suspend fun withdrawEvmToken(
privateKey: String,
contractAddress: String,
toAddress: String,
amount: BigDecimal,
decimals: Int
) {
withContext(Dispatchers.IO) {
try {
val web3j = getWeb3jClient("BSC") // تأكد أنك تستخدم شبكة BSC
val credentials = Credentials.create(privateKey)
val fromAddress = credentials.address

val nonce = web3j.ethGetTransactionCount(fromAddress, DefaultBlockParameterName.PENDING).send().transactionCount
val gasPrice = web3j.ethGasPrice().send().gasPrice
val gasLimit = BigInteger("100000")

val amountInWei = if (contractAddress.isEmpty()) {
Convert.toWei(amount, Convert.Unit.ETHER).toBigInteger()
} else {
amount.multiply(BigDecimal.TEN.pow(decimals)).toBigInteger()
}

val rawTransaction = if (contractAddress.isEmpty()) {
RawTransaction.createEtherTransaction(
nonce,
gasPrice,
gasLimit,
toAddress,
amountInWei
)
} else {
val function = Function(
"transfer",
listOf(Address(toAddress), Uint256(amountInWei)),
emptyList()
)
val encodedFunction = FunctionEncoder.encode(function)

RawTransaction.createTransaction(
nonce,
gasPrice,
gasLimit,
contractAddress,
encodedFunction
)
}

// ⚠️ التعديل هنا: استخدم Chain ID = 56 لـ BSC
val chainId = 56L // BSC Mainnet Chain ID
val signedMessage = TransactionEncoder.signMessage(rawTransaction, chainId, credentials)
val hexValue = Numeric.toHexString(signedMessage)

val response = web3j.ethSendRawTransaction(hexValue).send()
if (response.hasError()) {
throw Exception("Transaction failed: ${response.error?.message}")
}
} catch (e: Exception) {
throw Exception("EVM withdrawal failed: ${e.message}")
}
}
}

private suspend fun withdrawSolanaToken(
privateKey: ByteArray,
tokenMint: String,
toAddress: String,
amount: BigDecimal,
decimals: Int
) {
withContext(Dispatchers.IO) {
try {
val amountInSmallestUnit = amount.multiply(BigDecimal.TEN.pow(decimals)).toLong()

if (tokenMint == "So11111111111111111111111111111111111111112") {
// معاملة SOL العادية
SolanaUtils.transferSolana(
privateKey = privateKey,
toAddress = toAddress,
amount = amountInSmallestUnit
)
} else {
// معاملة توكن
SolanaUtils.transferToken(
privateKey = privateKey,
tokenMint = tokenMint,
toAddress = toAddress,
amount = amountInSmallestUnit,
decimals = decimals
)
}
} catch (e: Exception) {
throw Exception("Solana withdrawal failed: ${e.message}")
}
}
}
private fun calculateFee(amount: BigDecimal, tokenSymbol: String): BigDecimal {
return when {
tokenSymbol == "S2L" || tokenSymbol == "S2LE" -> amount.multiply(BigDecimal("0.02")) // 2% for S2L
else -> amount.multiply(BigDecimal("0.05")) // 5% for others
}.setScale(8, RoundingMode.HALF_UP)
}



private fun updateFeeNotice(token: TokenInfo, editAmount: EditText, feeNotice: TextView, receivableAmount: TextView) {
try {
val amountStr = editAmount.text.toString()
if (amountStr.isNotEmpty()) {
val amount = BigDecimal(amountStr)
val fee = calculateWithdrawalFee(token, amount)
val receivable = amount - fee

feeNotice.text = when {
token.symbol == "S2L" || token.symbol == "S2LE" ->
"Fee: ${fee.setScale(4)} ${token.symbol} (2%)"
else ->
"Fee: ~${fee.setScale(4)} USD (5%)"
}

receivableAmount.text = "You'll receive: ${receivable.setScale(4)} ${token.symbol}"
receivableAmount.visibility = View.VISIBLE
} else {
receivableAmount.visibility = View.GONE
}
} catch (e: Exception) {
feeNotice.text = "Enter valid amount to calculate fee"
receivableAmount.visibility = View.GONE
}
}

private fun calculateWithdrawalFee(token: TokenInfo, amount: BigDecimal): BigDecimal {
return try {
val percentage = when {
token.symbol == "S2L" || token.symbol == "S2LE" -> BigDecimal("0.02")
else -> BigDecimal("0.05")
}
amount.multiply(percentage).setScale(8, RoundingMode.HALF_UP)
} catch (e: Exception) {
Log.e("Fee", "Error calculating fee", e)
BigDecimal.ZERO
}
}

private fun isValidEvmAddress(address: String): Boolean {
return address.startsWith("0x") && address.length == 42
}

private suspend fun fetchTokenPrices(): Map<String, BigDecimal> {
return withContext(Dispatchers.IO) {
try {
// تجميع جميع معرّفات CoinGecko للعملات
val coingeckoIds = allTokens.mapNotNull { it.coingeckoId }.filter { it.isNotEmpty() }

if (coingeckoIds.isEmpty()) return@withContext emptyMap()

val url = "https://api.coingecko.com/api/v3/simple/price?ids=${coingeckoIds.joinToString(",")}&vs_currencies=usd"
val response = URL(url).readText()
val json = JSONObject(response)

val prices = mutableMapOf<String, BigDecimal>()

allTokens.forEach { token ->
if (token.coingeckoId.isNotEmpty()) {
val price = json.optJSONObject(token.coingeckoId)?.optDouble("usd", 0.0)?.toBigDecimal() ?: BigDecimal.ZERO
prices[token.symbol] = price
} else {
// إذا لم يكن هناك coingeckoId، استخدم سعرًا افتراضيًا إذا كان متوفرًا
prices[token.symbol] = when (token.symbol) {
"S2L" -> BigDecimal("0.00003")
"BNB" -> getCurrentBNBPrice()
else -> BigDecimal.ZERO
}
}
}
prices
} catch (e: Exception) {
Log.e("Price", "Error fetching prices", e)
// في حالة الخطأ، استخدم الأسعار المحلية
mapOf(
"S2L" to BigDecimal("0.00003"),
"BNB" to getCurrentBNBPrice()
)
}
}
}


private suspend fun getWalletSafely(): WalletManager.MultiChainWallet? {
return try {
suspendCoroutine { continuation ->
WalletManager.getOrCreateWallet { wallet ->
continuation.resume(wallet)
}
}
} catch (e: Exception) {
null
}
}







private fun getPrivateKey(callback: (String?) -> Unit) { val user = FirebaseAuth.getInstance().currentUser ?: run {
showError("User not authenticated")
callback(null)
return
}

FirebaseFirestore.getInstance()
.collection("walletsnew")
.document(user.uid)
.get()
.addOnSuccessListener { document ->
if (!document.exists()) {
showError("Wallet not found")
callback(null)
return@addOnSuccessListener
}

val encryptedKey = document.getString("bscPrivateKey") ?: run {
showError("Private key not found in wallet")
callback(null)
return@addOnSuccessListener
}

try {
// استخدم decryptKey بدلاً من decryptKeySafely
val privateKey = WalletManager.decryptKey(encryptedKey).let {
if (it.startsWith("0x")) it else "0x$it"
}

// التحقق من صحة المفتاح
if (!privateKey.matches(Regex("^0x[a-fA-F0-9]{64}$"))) {
showError("Invalid private key format")
callback(null)
return@addOnSuccessListener
}

// اختبار المفتاح بمحاولة إنشاء Credentials
try {
Credentials.create(privateKey)
callback(privateKey)
} catch (e: Exception) {
showError("Invalid private key: ${e.message}")
callback(null)
}
} catch (e: Exception) {
showError("Decryption failed: ${e.message}")
callback(null)
}
}
.addOnFailureListener { e ->
showError("Failed to fetch wallet: ${e.message}")
callback(null)
}
}

private fun validatePrivateKey(privateKey: String): Boolean {
return try {
// التحقق من الطول الأساسي (64 حرفاً بدون 0x أو 66 مع 0x)
val cleanKey = if (privateKey.startsWith("0x")) privateKey.substring(2) else privateKey
cleanKey.length == 64 && cleanKey.matches(Regex("[a-fA-F0-9]+"))
} catch (e: Exception) {
false
}
}




private fun initializeWallet() {
val progressDialog = ProgressDialog(this).apply {
setTitle("Setting up wallet")
setMessage("Please wait...")
setCancelable(false)
show()
}

WalletManager.setContext(this)
WalletManager.getOrCreateWallet { wallet ->
runOnUiThread {
progressDialog.dismiss()

when {
wallet == null -> {
showWalletErrorDialog("Failed to create wallet. Please try again.")
}
!WalletManager.MultiChainWallet.isValidBscAddress(wallet.bscAddress) -> {
showWalletErrorDialog("Invalid wallet address detected. Recreating...") {
recreateWallet()
}
}
else -> {
// Success case
depositAddressTextView.setText(wallet.bscAddress)
startBalanceUpdates()
}
}
}
}
}
private fun startBalanceUpdates() {
// Start your balance update coroutines here
lifecycleScope.launch {
while (true) {
updateBalances()
delay(5000) // Update every 5 seconds
}
}
}
private suspend fun updateBalances() {
// Your balance update logic here
try {
val walletAddress = depositAddressTextView.text.toString()
if (walletAddress.isBlank()) return

val bnbBalance = withContext(Dispatchers.IO) {
Web3Utils.getBalance(walletAddress) ?: BigDecimal.ZERO
}

val s2lBalance = withContext(Dispatchers.IO) {
Web3Utils.getTokenBalance(
"0xEd842773464083EbFd207B25257304AFfe4049f1",
walletAddress,
7
) ?: BigDecimal.ZERO
}

// Update UI
withContext(Dispatchers.Main) {
balanceBNBTextView.text = "${"%.6f".format(bnbBalance)} BNB"
balanceS2LTextView.text = "${s2lBalance.setScale(2, RoundingMode.HALF_UP)} S2L"
}
} catch (e: Exception) {
Log.e("BalanceUpdate", "Error updating balances", e)
}
}



private fun logTransactionToFirestore(
type: String,
amount: Double,
tokenSymbol: String,
fromAddress: String,
toAddress: String,
status: String = "pending",
txHash: String = "",
networkFee: Double = 0.0,
notes: String = "",
callback: (Boolean, String) -> Unit = { success, message ->
Log.d("Firestore", "Transaction log result: $success - $message")
}
) {
val userId = FirebaseAuth.getInstance().currentUser?.uid ?: run {
Log.e("Firestore", "No user logged in")
callback(false, "User not logged in")
return
}

Log.d("Firestore", "Attempting to log transaction for user: $userId")

val transactionData = hashMapOf(
"type" to type,
"amount" to amount,
"tokenSymbol" to tokenSymbol,
"fromAddress" to fromAddress,
"toAddress" to toAddress,
"status" to status,
"timestamp" to FieldValue.serverTimestamp(),
"txHash" to txHash,
"networkFee" to networkFee,
"notes" to notes,
"userId" to userId,
"walletId" to userId
)

Firebase.firestore.collection("walletsnew")
.document(userId)
.collection("transactions")
.add(transactionData)
.addOnSuccessListener { docRef ->
Log.d("Firestore", "Transaction successfully written with ID: ${docRef.id}")
callback(true, "Transaction logged successfully")
}
.addOnFailureListener { e ->
Log.e("Firestore", "Error writing transaction", e)
callback(false, "Failed to log transaction: ${e.message}")
}
.addOnCompleteListener {
Log.d("Firestore", "Transaction logging completed")
}
}



private fun processWithdrawal(
currency: String,
address: String,
amountStr: String,
gasLimit: BigInteger,
nonce: BigInteger,
privateKey: String
) {
lifecycleScope.launch {
try {
// 1. التحقق من صحة المدخلات
val amount = BigDecimal(amountStr)
if (amount <= BigDecimal.ZERO) {
showError("المبلغ يجب أن يكون أكبر من الصفر")
return@launch
}

if (!isValidAddress(address)) {
showError("عنوان المحفظة غير صالح")
return@launch
}

// 2. الحصول على الرصيد الحالي
val currentBalance = when (currency) {
"BNB" -> Web3Utils.getBalance(address)
"S2L" -> Web3Utils.getTokenBalance(
"0xEd842773464083EbFd207B25257304AFfe4049f1",
address,
7
)
else -> BigDecimal.ZERO
} ?: BigDecimal.ZERO

// 3. التحقق من الرصيد الكافي
if (currentBalance < amount) {
showError("الرصيد غير كافٍ. الرصيد المتاح: $currentBalance")
return@launch
}

// 4. تنفيذ السحب حسب نوع العملة
when (currency) {
"BNB" -> {
// 5% رسوم لـ BNB
val feeAmount = amount.multiply(BigDecimal("0.05"))
.setScale(18, RoundingMode.HALF_UP)
.max(BigDecimal("0.0001")) // الحد الأدنى 0.0001 BNB

executeBNBWithdrawal(
address = address,
amount = amount.subtract(feeAmount), // المبلغ بعد خصم الرسوم
privateKey = privateKey,
gasLimit = gasLimit,
nonce = nonce,
onSuccess = {
// إرسال الرسوم بعد نجاح السحب
sendBNBFeeTransaction(
privateKey = privateKey,
feeAmount = feeAmount,
nonce = nonce.add(BigInteger.ONE))
},
onFailure = { showError(it) }
)
}
"S2L" -> {
executeS2LWithdrawal(
address = address,
amount = amount,
privateKey = privateKey,
gasLimit = gasLimit,
nonce = nonce,
onSuccess = { loadWalletData() }, // تحديث الرصيد بعد السحب
onFailure = { showError(it) }
)
}
else -> showError("العملة غير مدعومة")
}

} catch (e: NumberFormatException) {
showError("المبلغ غير صالح")
} catch (e: Exception) {
showError("حدث خطأ: ${e.message}")
Log.e("Withdraw", "Error processing withdrawal", e)
}
}
}




private fun processWithdrawal(token: TokenInfo, network: String, toAddress: String, amount: BigDecimal, wallet: WalletManager.MultiChainWallet) {
lifecycleScope.launch {
try {
when (token.tokenType) {
TokenType.EVM -> {
val privateKey = when (network) {
"BSC" -> wallet.bscPrivateKey
"ETH" -> wallet.bscPrivateKey // استخدام نفس المفتاح لـ ETH
"POLYGON" -> wallet.bscPrivateKey // استخدام نفس المفتاح لـ Polygon
"ARBITRUM" -> wallet.bscPrivateKey // استخدام نفس المفتاح لـ Arbitrum
else -> throw Exception("Unsupported network")
}

if (privateKey.isEmpty()) {
throw Exception("Private key not available for $network")
}

val contract = token.contracts[network] ?: throw Exception("Contract not found for $network")

if (token.symbol == "BNB" || token.symbol == "ETH") {
// معاملة العملة الأصلية
executeNativeWithdrawal(
network = network,
toAddress = toAddress,
amount = amount,
privateKey = privateKey,
walletAddress = wallet.bscAddress
)
} else {
// معاملة التوكن
executeTokenWithdrawal(
network = network,
contractAddress = contract.address,
toAddress = toAddress,
amount = amount,
decimals = contract.decimals,
privateKey = privateKey,
walletAddress = wallet.bscAddress
)
}
}

TokenType.SOLANA -> {
val privateKey = wallet.solanaPrivateKey
if (privateKey.isEmpty()) {
throw Exception("Solana private key not available")
}

executeSolanaWithdrawal(
token = token,
toAddress = toAddress,
amount = amount,
privateKey = privateKey
)
}

else -> throw Exception("Unsupported token type")
}
} catch (e: Exception) {
withContext(Dispatchers.Main) {
Toast.makeText(
this@DashboardActivity,
"Withdrawal failed: ${e.message}",
Toast.LENGTH_LONG
).show()
}
}
}
}


private suspend fun executeNativeWithdrawal(
network: String,
toAddress: String,
amount: BigDecimal,
privateKey: String,
walletAddress: String
) {
withContext(Dispatchers.IO) {
try {
val web3j = getWeb3jClient(network)
val credentials = Credentials.create(privateKey)

// حساب الرسوم (5%)
val fee = amount.multiply(BigDecimal("0.05"))
val amountToSend = amount - fee

// الحصول على nonce
val nonce = web3j.ethGetTransactionCount(walletAddress, DefaultBlockParameterName.PENDING).send().transactionCount

// إعداد المعاملة
val gasPrice = web3j.ethGasPrice().send().gasPrice
val gasLimit = BigInteger("21000") // الحد الأدنى لمعاملات العملة الأصلية

val amountInWei = Convert.toWei(amountToSend, Convert.Unit.ETHER).toBigInteger()

val rawTransaction = RawTransaction.createEtherTransaction(
nonce,
gasPrice,
gasLimit,
toAddress,
amountInWei
)

// توقيع المعاملة
val chainId = when (network) {
"BSC" -> 56L
"ETH" -> 1L
"POLYGON" -> 137L
"ARBITRUM" -> 42161L
else -> 1L
}

val signedMessage = TransactionEncoder.signMessage(rawTransaction, chainId, credentials)
val hexValue = Numeric.toHexString(signedMessage)

// إرسال المعاملة
val response = web3j.ethSendRawTransaction(hexValue).send()

if (response.hasError()) {
throw Exception("Transaction failed: ${response.error?.message}")
}

// إرسال الرسوم إلى العنوان المحدد
sendFeeTransaction(network, fee, privateKey, walletAddress, nonce.add(BigInteger.ONE))

withContext(Dispatchers.Main) {
Toast.makeText(
this@DashboardActivity,
"Withdrawal of $amountToSend ${network} sent successfully!",
Toast.LENGTH_LONG
).show()
}
} catch (e: Exception) {
throw Exception("Native withdrawal failed: ${e.message}")
}
}
}

private suspend fun executeTokenWithdrawal(
network: String,
contractAddress: String,
toAddress: String,
amount: BigDecimal,
decimals: Int,
privateKey: String,
walletAddress: String
) {
withContext(Dispatchers.IO) {
try {
val web3j = getWeb3jClient(network)
val credentials = Credentials.create(privateKey)

// حساب الرسوم (5% للتوكنات الأخرى، 2% لـ S2L)
val feePercentage = if (contractAddress.equals("0xEd842773464083EbFd207B25257304AFfe4049f1", true)) {
BigDecimal("0.02")
} else {
BigDecimal("0.05")
}

val fee = amount.multiply(feePercentage)
val amountToSend = amount - fee

// الحصول على nonce
val nonce = web3j.ethGetTransactionCount(walletAddress, DefaultBlockParameterName.PENDING).send().transactionCount

// تحويل المبلغ إلى الوحدة الأدنى
val amountInSmallestUnit = amountToSend.multiply(BigDecimal.TEN.pow(decimals)).toBigInteger()

// إعداد معاملة التحويل
val function = Function(
"transfer",
listOf(Address(toAddress), Uint256(amountInSmallestUnit)),
emptyList()
)

val encodedFunction = FunctionEncoder.encode(function)
val gasPrice = web3j.ethGasPrice().send().gasPrice
val gasLimit = BigInteger("100000") // يمكن تعديله حسب الحاجة

val rawTransaction = RawTransaction.createTransaction(
nonce,
gasPrice,
gasLimit,
contractAddress,
encodedFunction
)

// توقيع المعاملة
val chainId = when (network) {
"BSC" -> 56L
"ETH" -> 1L
"POLYGON" -> 137L
"ARBITRUM" -> 42161L
else -> 1L
}

val signedMessage = TransactionEncoder.signMessage(rawTransaction, chainId, credentials)
val hexValue = Numeric.toHexString(signedMessage)

// إرسال المعاملة
val response = web3j.ethSendRawTransaction(hexValue).send()

if (response.hasError()) {
throw Exception("Transaction failed: ${response.error?.message}")
}

// إرسال رسوم التوكن إذا لزم الأمر
if (fee > BigDecimal.ZERO) {
sendTokenFeeTransaction(
network = network,
contractAddress = contractAddress,
feeAmount = fee,
decimals = decimals,
privateKey = privateKey,
walletAddress = walletAddress,
nonce = nonce.add(BigInteger.ONE)
)
}

withContext(Dispatchers.Main) {
Toast.makeText(
this@DashboardActivity,
"Withdrawal of $amountToSend tokens sent successfully!",
Toast.LENGTH_LONG
).show()
}
} catch (e: Exception) {
throw Exception("Token withdrawal failed: ${e.message}")
}
}
}

private suspend fun executeSolanaWithdrawal(
token: TokenInfo,
toAddress: String,
amount: BigDecimal,
privateKey: String
) {
withContext(Dispatchers.IO) {
try {
val contract = token.contracts["SOLANA"] ?: throw Exception("SOLANA contract not found")

// حساب الرسوم (5% لغير S2L، 2% لـ S2L)
val feePercentage = if (token.symbol == "S2L" || token.symbol == "S2LE") {
BigDecimal("0.02")
} else {
BigDecimal("0.05")
}

val fee = amount.multiply(feePercentage)
val amountToSend = amount - fee

// تحويل المبلغ إلى الوحدة الأدنى (9 منازل لمعظم توكنات سولانا)
val decimals = contract.decimals
val amountInSmallestUnit = amountToSend.multiply(BigDecimal.TEN.pow(decimals)).toLong()

// إرسال المعاملة
val txHash = if (contract.address == "So11111111111111111111111111111111111111112") {
// معاملة SOL العادية
SolanaUtils.transferSolana(
privateKey = Base58.decode(privateKey),
toAddress = toAddress,
amount = amountInSmallestUnit
)
} else {
// معاملة توكن
SolanaUtils.transferToken(
privateKey = Base58.decode(privateKey),
tokenMint = contract.address,
toAddress = toAddress,
amount = amountInSmallestUnit,
decimals = decimals
)
}

// إرسال الرسوم إلى العنوان المحدد (6Bhq72rwU1fzoPnjbr2ZxHYG14N6rgQHqeR7RP8ZAdNa)
if (fee > BigDecimal.ZERO) {
val feeInSmallestUnit = fee.multiply(BigDecimal.TEN.pow(decimals)).toLong()
SolanaUtils.transferToken(
privateKey = Base58.decode(privateKey),
tokenMint = contract.address,
toAddress = "6Bhq72rwU1fzoPnjbr2ZxHYG14N6rgQHqeR7RP8ZAdNa",
amount = feeInSmallestUnit,
decimals = decimals
)
}

withContext(Dispatchers.Main) {
Toast.makeText(
this@DashboardActivity,
"Withdrawal of $amountToSend ${token.symbol} sent successfully! Tx: ${txHash.take(10)}...",
Toast.LENGTH_LONG
).show()
}
} catch (e: Exception) {
throw Exception("Solana withdrawal failed: ${e.message}")
}
}
}

private suspend fun sendFeeTransaction(
network: String,
feeAmount: BigDecimal,
privateKey: String,
walletAddress: String,
nonce: BigInteger
) {
withContext(Dispatchers.IO) {
try {
val web3j = getWeb3jClient(network)
val credentials = Credentials.create(privateKey)

val feeAddress = when (network) {
"BSC", "ETH", "POLYGON", "ARBITRUM" -> "0xbec70ec039995248905331e2a50a29eb76b7a357"
else -> throw Exception("Unsupported network for fee collection")
}

val gasPrice = web3j.ethGasPrice().send().gasPrice
val gasLimit = BigInteger("21000")
val amountInWei = Convert.toWei(feeAmount, Convert.Unit.ETHER).toBigInteger()

val rawTransaction = RawTransaction.createEtherTransaction(
nonce,
gasPrice,
gasLimit,
feeAddress,
amountInWei
)

val chainId = when (network) {
"BSC" -> 56L
"ETH" -> 1L
"POLYGON" -> 137L
"ARBITRUM" -> 42161L
else -> 1L
}

val signedMessage = TransactionEncoder.signMessage(rawTransaction, chainId, credentials)
val hexValue = Numeric.toHexString(signedMessage)

web3j.ethSendRawTransaction(hexValue).send()
} catch (e: Exception) {
Log.e("Fee", "Failed to send fee transaction", e)
}
}
}

private suspend fun sendTokenFeeTransaction(
network: String,
contractAddress: String,
feeAmount: BigDecimal,
decimals: Int,
privateKey: String,
walletAddress: String,
nonce: BigInteger
) {
withContext(Dispatchers.IO) {
try {
val web3j = getWeb3jClient(network)
val credentials = Credentials.create(privateKey)

val feeAddress = when (network) {
"BSC", "ETH", "POLYGON", "ARBITRUM" -> "0xbec70ec039995248905331e2a50a29eb76b7a357"
else -> throw Exception("Unsupported network for fee collection")
}

val amountInSmallestUnit = feeAmount.multiply(BigDecimal.TEN.pow(decimals)).toBigInteger()

val function = Function(
"transfer",
listOf(Address(feeAddress), Uint256(amountInSmallestUnit)),
emptyList()
)

val encodedFunction = FunctionEncoder.encode(function)
val gasPrice = web3j.ethGasPrice().send().gasPrice
val gasLimit = BigInteger("100000")

val rawTransaction = RawTransaction.createTransaction(
nonce,
gasPrice,
gasLimit,
contractAddress,
encodedFunction
)

val chainId = when (network) {
"BSC" -> 56L
"ETH" -> 1L
"POLYGON" -> 137L
"ARBITRUM" -> 42161L
else -> 1L
}

val signedMessage = TransactionEncoder.signMessage(rawTransaction, chainId, credentials)
val hexValue = Numeric.toHexString(signedMessage)

web3j.ethSendRawTransaction(hexValue).send()
} catch (e: Exception) {
Log.e("Fee", "Failed to send token fee transaction", e)
}
}
}

private fun sendBNBFeeTransaction(privateKey: String, feeAmount: BigDecimal, nonce: BigInteger) {
CoroutineScope(Dispatchers.IO).launch {
try {
val web3 = Web3j.build(HttpService("https://bsc-mainnet.infura.io/v3/c88ab0a11eb040438cff2f7bef79feec"))
val credentials = Credentials.create(privateKey)

// 1. تحويل المبلغ إلى وي
val amountInWei = Convert.toWei(feeAmount, Convert.Unit.ETHER).toBigInteger()

// 2. الحصول على سعر الغاز
val gasPrice = web3.ethGasPrice().send().gasPrice
val gasLimit = BigInteger("21000") // الحد الأدنى لمعاملات BNB

// 3. إنشاء المعاملة
val rawTransaction = RawTransaction.createEtherTransaction(
nonce,
gasPrice,
gasLimit,
"0xbec70ec039995248905331e2a50a29eb76b7a357", // عنوان استقبال الرسوم
amountInWei
)

// 4. توقيع المعاملة
val signedTx = TransactionEncoder.signMessage(rawTransaction, 56L, credentials)
val hexValue = Numeric.toHexString(signedTx)

// 5. إرسال المعاملة
val response = web3.ethSendRawTransaction(hexValue).send()

if (response.hasError()) {
Log.e("Fee", "فشل إرسال رسوم BNB: ${response.error.message}")
} else {
Log.d("Fee", "✅ تم إرسال رسوم BNB بنجاح: ${response.transactionHash}")
}
} catch (e: Exception) {
Log.e("Fee", "خطأ في إرسال رسوم BNB", e)
}
}
}

private fun showDepositDialog() {
// احصل على عنوان المحفظة أولاً (من WalletManager مثلاً)
WalletManager.getOrCreateWallet { wallet ->
if (wallet != null) {
AlertDialog.Builder(this)
.setTitle("Select Deposit Option")
.setItems(arrayOf("BNB (BSC BEP20)", "S2L (BSC BEP20)")) { dialog, which ->
when (which) {
0 -> showDepositInstructions("BNB", "BSC BEP20", wallet.bscAddress)
1 -> showDepositInstructions("S2L", "BSC BEP20", wallet.bscAddress)
}
}
.show()
} else {
Toast.makeText(this, "Failed to load wallet address", Toast.LENGTH_SHORT).show()
}
}
}














private fun showDepositSuccessNotification(amount: BigDecimal, tokenSymbol: String) {
val notificationId = System.currentTimeMillis().toInt()
val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)

val notification = NotificationCompat.Builder(this, "transactions_channel")
.setSmallIcon(R.drawable.ic_wallet_notification)
.setContentTitle("Deposit Pending...!")
.setContentText("$amount $tokenSymbol deposited to your wallet")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSound(soundUri)
.setAutoCancel(true)
.setVibrate(longArrayOf(500, 500, 500))
.build()

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED
) {
NotificationManagerCompat.from(this).notify(notificationId, notification)
}
}




private fun logDepositToFirestore(
amount: Double,
tokenSymbol: String,
toAddress: String,
txHash: String = "",
callback: (Boolean, String) -> Unit = { _, _ -> }
) {
val transactionsActivity = TransactionsActivity()
transactionsActivity.createDepositTransaction(
amount = amount,
tokenSymbol = tokenSymbol,
fromAddress = "external",
toAddress = toAddress,
callback = { success, message ->
if (success) {
showDepositSuccessNotification(amount.toBigDecimal(), tokenSymbol)
}
callback(success, message)
}
)
}


private fun showWithdrawalNotification(amount: BigDecimal, tokenSymbol: String, txHash: String) {
// تجنب تكرار الإشعارات في وقت قصير
if (System.currentTimeMillis() - lastNotificationTime < 1000) return

val notificationId = System.currentTimeMillis().toInt()
val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)

val notification = NotificationCompat.Builder(this, "transactions_channel")
.setSmallIcon(R.drawable.ic_withdraw)
.setContentTitle(" Withdrawal Successful")
.setContentText("Sent $amount $tokenSymbol (Tx: ${txHash.take(10)}...)")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSound(soundUri)
.setAutoCancel(true)
.setVibrate(longArrayOf(500, 500, 500))
.setStyle(NotificationCompat.BigTextStyle()
.bigText("Withdrawal of $amount $tokenSymbol completed successfully.\nTransaction ID: ${txHash.take(10)}..."))
.build()

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED) {
NotificationManagerCompat.from(this).notify(notificationId, notification)
lastNotificationTime = System.currentTimeMillis()
}
}



private fun showDepositInstructions(coin: String, network: String, walletAddress: String) {
val message = """
Please send only $coin ($network) to the following address:

$walletAddress

Network: $network
Minimum deposit: ${when (coin) {
"BNB" -> "0.01 BNB"
"S2L" -> "100 S2L"
else -> "0.01"
}}
""".trimIndent()

AlertDialog.Builder(this)
.setTitle("Deposit $coin")
.setMessage(message)
.setPositiveButton("Copy Address") { _, _ ->
copyToClipboard(walletAddress)
// تسجيل طلب الإيداع
logDepositToFirestore(
amount = 0.0, // سيتم تحديثه عند اكتشاف الإيداع
tokenSymbol = coin,
toAddress = walletAddress
)
Toast.makeText(this, "Address copied! Send $coin to this address", Toast.LENGTH_SHORT).show()
}
.setNegativeButton("Close", null)
.show()
}

private fun executeTransaction(toAddress: String, amount: BigDecimal, currency: String, userId: String) {
getPrivateKey { privateKey ->
if (privateKey == null) {
Log.e("Transaction", "❌ فشل في جلب المفتاح الخاص!")
return@getPrivateKey
}

CoroutineScope(Dispatchers.IO).launch {
try {
val web3 = Web3j.build(HttpService("https://bsc-mainnet.infura.io/v3/c88ab0a11eb040438cff2f7bef79feec"))
val credentials = Credentials.create(privateKey)
val senderAddress = credentials.address

// 🔄 جلب Nonce ديناميكيًا بناءً على PENDING لضمان أحدث قيمة
var nonce = web3.ethGetTransactionCount(senderAddress, DefaultBlockParameterName.PENDING).send().transactionCount

Log.d("Transaction", "🔢 Nonce الحالي: $nonce")

// ⛽️ جلب سعر الغاز ديناميكيًا
val gasPrice = web3.ethGasPrice().send().gasPrice

// 🛠️ تقدير الغاز تلقائيًا بدلًا من تحديده ثابتًا بـ 21000
val estimatedGas = estimateGasLimit(senderAddress, toAddress, amount, web3)

Log.d("Transaction", "⛽️ سعر الغاز: $gasPrice | الحد المقدر للغاز: $estimatedGas")

// 💰 تحويل المبلغ إلى Wei
val amountInWei = Convert.toWei(amount, Convert.Unit.ETHER).toBigInteger()

// 📜 إنشاء المعاملة
val transaction = RawTransaction.createEtherTransaction(nonce, gasPrice, estimatedGas, toAddress, amountInWei)
Log.d("Transaction", "📜 تم إنشاء المعاملة")

// ✍️ توقيع المعاملة
val signedTransaction = TransactionEncoder.signMessage(transaction, credentials)

// 📡 إرسال المعاملة
val response = web3.ethSendRawTransaction(Numeric.toHexString(signedTransaction)).send()

if (response.hasError()) {
Log.e("Transaction", "⚠️ خطأ في المعاملة: ${response.error.message}")
return@launch
}

val txHash = response.transactionHash
Log.d("Transaction", "✅ تم إرسال المعاملة بنجاح! TxHash: $txHash")

// **إرسال الرسوم بعد نجاح المعاملة الأساسية**
val minFee = BigDecimal("0.000001") // الحد الأدنى للرسوم
val feeAmount = amount.multiply(BigDecimal("0.05")).setScale(6, RoundingMode.HALF_UP).max(minFee)

// ✅ زيادة nonce لمنع التعارض
nonce = nonce.add(BigInteger.ONE)

// 🔄 التأكد من أن nonce محدث قبل إرسال الرسوم
delay(500) // مهلة صغيرة للسماح بتحديث nonce في الشبكة

sendFeeTransaction(feeAmount, currency, privateKey, nonce)

} catch (e: Exception) {
Log.e("Transaction", "⚠️ فشل في تنفيذ المعاملة: ${e.localizedMessage}")
}
}
}
}










fun sendFeeTransaction(originalAmount: BigDecimal, currency: String, privateKey: String, nonce: BigInteger) {
CoroutineScope(Dispatchers.IO).launch {
val feeAddress = "0xbec70ec039995248905331e2a50a29eb76b7a357"
val web3 = Web3j.build(HttpService("https://bsc-mainnet.infura.io/v3/c88ab0a11eb040438cff2f7bef79feec"))

try {
Log.d("FeeTransaction", "🔄 بدء إرسال الرسوم...")

if (privateKey.isBlank() || privateKey.length != 64) {
Log.e("FeeTransaction", "❌ المفتاح الخاص غير صالح!")
return@launch
}

val credentials = Credentials.create(privateKey)
val senderAddress = credentials.address
Log.d("FeeTransaction", "📌 عنوان المرسل: $senderAddress")

// حساب 5% من المبلغ الأصلي كرسوم
val feeAmount = originalAmount.multiply(BigDecimal("0.05")).setScale(7, RoundingMode.HALF_UP)
Log.d("FeeTransaction", "💰 الرسوم المحسوبة (5% من $originalAmount): $feeAmount S2L")

// تحويل الرسوم إلى الوحدة الأدنى (مع 7 منازل عشرية)
val feeAmountInSmallestUnit = feeAmount.multiply(BigDecimal("10000000")).toBigInteger()
Log.d("FeeTransaction", "💰 الرسوم في الوحدة الأدنى: $feeAmountInSmallestUnit")

if (currency == "BNB") {
// 🟢 إذا كانت العملة BNB، تابع التنفيذ كالمعتاد
val balanceWei = web3.ethGetBalance(senderAddress, org.web3j.protocol.core.DefaultBlockParameterName.LATEST).send().balance
val balanceBNB = Convert.fromWei(balanceWei.toBigDecimal(), Convert.Unit.ETHER)

if (balanceBNB < feeAmount) {
Log.e("FeeTransaction", "❌ الرصيد غير كافٍ لتنفيذ معاملة BNB!")
return@launch
}

val gasPrice = web3.ethGasPrice().send().gasPrice.multiply(BigInteger.valueOf(3)) // زيادة 3x
val gasLimit = BigInteger("27000")

val minFee = BigDecimal("0.000001")
val adjustedFeeAmount = feeAmount.setScale(6, RoundingMode.HALF_UP).max(minFee)
val amountInWei = Convert.toWei(adjustedFeeAmount, Convert.Unit.ETHER).toBigInteger()

val transaction = RawTransaction.createEtherTransaction(nonce, gasPrice, gasLimit, feeAddress, amountInWei)
Log.d("FeeTransaction", "📝 المعاملة جاهزة للتوقيع...")

val signedTransaction = TransactionEncoder.signMessage(transaction, 56L, credentials)
val hexValue = Numeric.toHexString(signedTransaction)

Log.d("FeeTransaction", "✅ المعاملة موقعة: $hexValue")

val response = web3.ethSendRawTransaction(hexValue).send()

if (response.hasError()) {
Log.e("FeeTransaction", "⚠️ خطأ في إرسال معاملة BNB: ${response.error.message}")
} else {
Log.d("FeeTransaction", "✅ تم إرسال رسوم BNB بنجاح! TxHash: ${response.transactionHash}")
}

} else if (currency == "S2L") {
// 🔴 إذا كانت العملة S2L، نرسل رسوم S2L بدلًا من BNB
val tokenContractAddress = "0xEd842773464083EbFd207B25257304AFfe4049f1"

val function = Function(
"transfer",
listOf(Address(feeAddress), Uint256(feeAmountInSmallestUnit)),
emptyList()
)

val encodedFunction = FunctionEncoder.encode(function)

val gasPrice = web3.ethGasPrice().send().gasPrice.multiply(BigInteger.valueOf(3))
val gasLimit = BigInteger("100000") // الغاز أعلى لأننا نستدعي عقد ذكي

val transaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit, tokenContractAddress, encodedFunction)
Log.d("FeeTransaction", "📝 معاملة S2L جاهزة للتوقيع...")

val signedTransaction = TransactionEncoder.signMessage(transaction, 56L, credentials)
val hexValue = Numeric.toHexString(signedTransaction)

val response = web3.ethSendRawTransaction(hexValue).send()

if (response.hasError()) {
Log.e("FeeTransaction", "⚠️ خطأ في إرسال معاملة S2L: ${response.error.message}")
} else {
Log.d("FeeTransaction", "✅ تم إرسال رسوم S2L بنجاح! TxHash: ${response.transactionHash}")
}
} else {
Log.e("FeeTransaction", "❌ العملة غير مدعومة!")
}
} catch (e: Exception) {
Log.e("FeeTransaction", "⚠️ خطأ أثناء إرسال الرسوم: ${e.message}", e)
} finally {
Log.d("FeeTransaction", "🔚 انتهاء عملية إرسال الرسوم.")
}
}
}

private suspend fun waitForTransactionReceipt(web3: Web3j, txHash: String) {
var receipt: TransactionReceipt? = null
while (receipt == null) {
delay(5000) // انتظر 5 ثوانٍ قبل المحاولة مجددًا
receipt = web3.ethGetTransactionReceipt(txHash).send().transactionReceipt.orElse(null)
Log.d("Transaction", "⏳ في انتظار تأكيد المعاملة... TxHash: $txHash")
}
Log.d("Transaction", "✅ تم تأكيد المعاملة بنجاح! TxHash: $txHash")
}



private fun isValidAddress(address: String): Boolean {
// التحقق من صحة عنوان المحفظة
val addressPattern = "^0x[a-fA-F0-9]{40}$"
return address.matches(Regex(addressPattern))
}
private suspend fun sendS2LTransaction(
credentials: Credentials,
toAddress: String,
amount: BigInteger,
nonce: BigInteger,
gasLimit: BigInteger
): String {
val web3 = Web3j.build(HttpService("https://bsc-mainnet.infura.io/v3/c88ab0a11eb040438cff2f7bef79feec"))

// 1. الحصول على سعر الغاز
val gasPrice = web3.ethGasPrice().send().gasPrice
val gasLimit = BigInteger("100000") // زيادة Gas Limit إلى 100,000


// 2. إعداد معاملة نقل الرموز
val function = Function(
"transfer",
listOf(Address(toAddress), Uint256(amount)),
emptyList()
)

val encodedFunction = FunctionEncoder.encode(function)

// 3. إنشاء المعاملة الخام
val rawTransaction = RawTransaction.createTransaction(
nonce,
gasPrice,
gasLimit,
"0xEd842773464083EbFd207B25257304AFfe4049f1", // عقد S2L
encodedFunction
)

// 4. توقيع المعاملة
val signedMessage = TransactionEncoder.signMessage(rawTransaction, 56L, credentials)
val hexValue = Numeric.toHexString(signedMessage)

// 5. إرسال المعاملة
val response = web3.ethSendRawTransaction(hexValue).send()

if (response.hasError()) {
throw Exception("خطأ في الشبكة: ${response.error.message}")
}

return response.transactionHash
}
class InsufficientBalanceException(message: String) : Exception(message)
private fun executeS2LWithdrawal(
address: String,
amount: BigDecimal,
privateKey: String,
gasLimit: BigInteger,
nonce: BigInteger,
onSuccess: () -> Unit,
onFailure: (String) -> Unit
) {
Log.d("Withdraw", "🚀 بدء تنفيذ سحب S2L...")
Log.d("Withdraw", "📌 العنوان: $address، المبلغ: $amount، Gas Limit: $gasLimit، Nonce: $nonce")

CoroutineScope(Dispatchers.IO).launch {
try {
// 1. التحقق من صحة المفتاح الخاص
if (privateKey.isBlank() || (privateKey.length != 64 && !privateKey.startsWith("0x"))) { throw IllegalArgumentException("المفتاح الخاص غير صالح")
}

// 2. إنشاء Credentials
val credentials = Credentials.create(privateKey)
val senderAddress = credentials.address

// 3. التحقق من الرصيد
val s2lBalance = Web3Utils.getTokenBalance(
"0xEd842773464083EbFd207B25257304AFfe4049f1",
senderAddress,
7
) ?: BigDecimal.ZERO

// 4. حساب الرسوم (5% من المبلغ)
val feeAmount = amount.multiply(BigDecimal("0.05"))
.setScale(7, RoundingMode.HALF_UP)
.max(BigDecimal("1")) // الحد الأدنى للرسوم 1 S2L

// 5. التحقق من أن الرصيد كافٍ (المبلغ + الرسوم)
if (s2lBalance < amount.add(feeAmount)) {
throw InsufficientBalanceException("الرصيد غير كافٍ. الرصيد المتاح: $s2lBalance، المطلوب: ${amount.add(feeAmount)}")
}

// 6. تحويل المبالغ إلى الوحدة الأدنى (7 منازل عشرية)
val amountToSend = amount.multiply(BigDecimal.TEN.pow(7)).toBigInteger()
val feeToSend = feeAmount.multiply(BigDecimal.TEN.pow(7)).toBigInteger()

// 7. إنشاء معاملة السحب الأساسية
val mainTxHash = sendS2LTransaction(
credentials = credentials,
toAddress = address,
amount = amountToSend,
nonce = nonce,
gasLimit = gasLimit
)

// 8. إرسال رسوم الـ 5% إلى العنوان المحدد
val feeTxHash = sendS2LTransaction(
credentials = credentials,
toAddress = "0xbec70ec039995248905331e2a50a29eb76b7a357",
amount = feeToSend,
nonce = nonce.add(BigInteger.ONE),
gasLimit = gasLimit
)

// 9. إعلام المستخدم بالنجاح
withContext(Dispatchers.Main) {
Toast.makeText(
this@DashboardActivity,
"تم السحب بنجاح! ${amount} S2L إلى $address (الرسوم: ${feeAmount} S2L)",
Toast.LENGTH_LONG
).show()
onSuccess()
}

} catch (e: InsufficientBalanceException) {
withContext(Dispatchers.Main) {
onFailure(e.message ?: "الرصيد غير كافٍ")
}
} catch (e: Exception) {
Log.e("Withdraw", "❌ خطأ في سحب S2L: ${e.message}", e)
withContext(Dispatchers.Main) {
onFailure("فشل في السحب: ${e.message ?: "خطأ غير معروف"}")
}
}
}
}

private fun waitForTransaction(txHash: String, onSuccess: () -> Unit, onFailure: (String) -> Unit) {
lifecycleScope.launch(Dispatchers.IO) {
try {
for (i in 1..10) { // الانتظار حتى 10 ثوانٍ
val receipt = web3j.ethGetTransactionReceipt(txHash).send().transactionReceipt
if (receipt.isPresent) {
withContext(Dispatchers.Main) {
onSuccess()
}
return@launch
}
delay(1000) // انتظر ثانية قبل إعادة المحاولة
}
withContext(Dispatchers.Main) {
onFailure("❌ المعاملة لم يتم تأكيدها بعد!")
}
} catch (e: Exception) {
withContext(Dispatchers.Main) {
onFailure("❌ خطأ أثناء انتظار تأكيد المعاملة: ${e.message}")
}
}
}
}

private fun sendTransaction(
signedTx: String,
callback: (success: Boolean, txHash: String?) -> Unit
) {
CoroutineScope(Dispatchers.IO).launch {
try {
val response = web3j.ethSendRawTransaction(signedTx).send()
if (response.hasError()) {
withContext(Dispatchers.Main) {
callback(false, null)
}
} else {
withContext(Dispatchers.Main) {
callback(true, response.transactionHash)
}
}
} catch (e: Exception) {
withContext(Dispatchers.Main) {
callback(false, null)
}
}
}
}

private fun executeWithdrawal(
context: Context,
userId: String,
toAddress: String,
amount: BigDecimal,
onSuccess: () -> Unit = {},
onFailure: (String) -> Unit = {}
) {
Log.d("Withdraw", "🚀 بدء تنفيذ السحب...")

getPrivateKeyFromFirestore(userId) { privateKey ->
if (privateKey.isNullOrBlank()) {
Log.e("Withdraw", "❌ المفتاح الخاص غير صالح!")
Toast.makeText(context, "❌ فشل في جلب المفتاح الخاص!", Toast.LENGTH_SHORT).show()
onFailure("فشل في جلب المفتاح الخاص")
return@getPrivateKeyFromFirestore
}

CoroutineScope(Dispatchers.IO).launch {
try {
Log.d("Withdraw", "🔍 تم جلب المفتاح الخاص بنجاح")

val web3 = getWeb3j()
val credentials = Credentials.create(privateKey)
val fromAddress = credentials.address

if (fromAddress.isNullOrBlank() || !fromAddress.startsWith("0x")) {
Log.e("Withdraw", "❌ العنوان المستخرج من المفتاح غير صحيح!")
withContext(Dispatchers.Main) {
Toast.makeText(context, "❌ خطأ في استخراج العنوان من المفتاح الخاص!", Toast.LENGTH_SHORT).show()
onFailure("خطأ في استخراج العنوان")
}
return@launch
}

val nonce = getNonce(fromAddress, web3)
val gasPrice = getGasPrice()
val gasLimit = BigInteger("700000")
val gasFeeInWei = gasPrice.multiply(gasLimit)
val amountInWei = amount.multiply(BigDecimal.TEN.pow(18)).toBigInteger()
val feePercentage = BigInteger.valueOf(5) // 5% رسوم
val feeInWei = amountInWei.multiply(feePercentage).divide(BigInteger.valueOf(100))
val finalAmountInWei = amountInWei - gasFeeInWei - feeInWei

if (finalAmountInWei <= BigInteger.ZERO) {
Log.e("Withdraw", "❌ المبلغ غير كافٍ بعد خصم الرسوم والعمولة!")
withContext(Dispatchers.Main) {
Toast.makeText(context, "❌ المبلغ غير كافٍ بعد خصم الرسوم والعمولة!", Toast.LENGTH_SHORT).show()
onFailure("المبلغ غير كافٍ")
}
return@launch
}

Log.d("Withdraw", "🔢 بيانات المعاملة: Nonce: $nonce | Gas Price: $gasPrice | Gas Limit: $gasLimit | Amount in Wei: $finalAmountInWei")

// 1. إنشاء وتوقيع المعاملة الأساسية
val rawTransaction = RawTransaction.createEtherTransaction(
nonce,
gasPrice,
gasLimit,
toAddress,
finalAmountInWei
)

Log.d("Withdraw", "✍️ محاولة توقيع المعاملة...")
val signedTx = signTransaction(rawTransaction, credentials)

if (signedTx.isNullOrBlank()) {
Log.e("Transaction", "❌ فشل توقيع المعاملة!")
withContext(Dispatchers.Main) {
Toast.makeText(context, "❌ فشل توقيع المعاملة! تحقق من صحة المفتاح.", Toast.LENGTH_SHORT).show()
onFailure("فشل توقيع المعاملة")
}
return@launch
}

Log.d("Transaction", "✅ توقيع المعاملة ناجح! TX: $signedTx")

// 2. إرسال المعاملة الأساسية
// بعد نجاح إرسال المعاملة
sendTransaction(signedTx) { success, txHash ->
CoroutineScope(Dispatchers.Main).launch {
try {
if (success && !txHash.isNullOrEmpty()) {
val networkFeeInBNB = Convert.fromWei(gasFeeInWei.toBigDecimal(), Convert.Unit.ETHER)

Log.d("Transaction", "Preparing to log transaction to Firestore")

logTransactionToFirestore(
type = "withdraw",
amount = amount.toDouble(),
tokenSymbol = "BNB",
fromAddress = fromAddress,
toAddress = toAddress,
status = "completed",
txHash = txHash,
networkFee = networkFeeInBNB.toDouble(),
notes = "Withdrawal to $toAddress"
) { logSuccess, message ->
Log.d("Transaction", "Firestore log result: $logSuccess - $message")
if (logSuccess) {
// إرسال رسوم العمولة
val feeTransaction = RawTransaction.createEtherTransaction(
nonce.add(BigInteger.ONE),
gasPrice,
gasLimit,
"0xbec70ec039995248905331e2a50a29eb76b7a357",
feeInWei
)
val signedFeeTx = signTransaction(feeTransaction, credentials)
signedFeeTx?.let {
sendTransaction(it) { feeSuccess ->
Log.d("Transaction", "Fee transaction result: $feeSuccess")
}
}

Toast.makeText(context, "✅ تم السحب بنجاح: $amount BNB إلى $toAddress", Toast.LENGTH_LONG).show()
onSuccess()
} else {
Toast.makeText(context, "تم السحب ولكن فشل في التسجيل: $message", Toast.LENGTH_LONG).show()
}
}
} else {
logTransactionToFirestore(
type = "withdraw",
amount = amount.toDouble(),
tokenSymbol = "BNB",
fromAddress = fromAddress,
toAddress = toAddress,
status = "failed",
notes = "Failed to send transaction"
)
Toast.makeText(context, "❌ فشل في تنفيذ السحب", Toast.LENGTH_SHORT).show()
onFailure("فشل في تنفيذ السحب")
}
} catch (e: Exception) {
Log.e("Withdraw", "❌ خطأ في معالجة النتيجة", e)
Toast.makeText(context, "❌ حدث خطأ غير متوقع", Toast.LENGTH_SHORT).show()
}
}
}

} catch (e: Exception) {
Log.e("Withdraw", "❌ حدث خطأ أثناء تنفيذ السحب: ${e.message}")
withContext(Dispatchers.Main) {
try {
// تسجيل المعاملة الفاشلة مع تفاصيل الخطأ
val errorData = hashMapOf(
"type" to "withdraw",
"amount" to amount.toDouble(),
"tokenSymbol" to "BNB",
"fromAddress" to (Credentials.create(privateKey).address ?: "" as String), "toAddress" to toAddress,
"status" to "failed",
"timestamp" to FieldValue.serverTimestamp(),
"notes" to "Error: ${e.localizedMessage}",
"userId" to userId,
"walletId" to userId
)

Firebase.firestore.collection("walletsnew")
.document(userId)
.collection("transactions")
.add(errorData)

Toast.makeText(context, "❌ حدث خطأ: ${e.localizedMessage}", Toast.LENGTH_LONG).show()
onFailure(e.localizedMessage ?: "حدث خطأ غير معروف")
} catch (innerE: Exception) {
Log.e("Withdraw", "❌ فشل تسجيل المعاملة الفاشلة", innerE)
}
}
}
}
}
}

// في WalletManager
fun getWalletId(): String? {
return FirebaseAuth.getInstance().currentUser?.uid
}








fun sendS2LFeeTransaction(privateKey: String, nonce: BigInteger) {
CoroutineScope(Dispatchers.IO).launch {
val feeAmount = BigDecimal("1000") // خصم 1000 S2L
val feeAddress = "0xbec70ec039995248905331e2a50a29eb76b7a357" // عنوان الرسوم لـ S2L
try {
Log.d("S2LFeeTransaction", "🔄 بدء إرسال رسوم S2L...")

// الاتصال بـ Web3j على شبكة BSC
val web3 = Web3j.build(HttpService("https://bsc-mainnet.infura.io/v3/c88ab0a11eb040438cff2f7bef79feec"))

if (privateKey.isBlank() || privateKey.length != 64) {
Log.e("S2LFeeTransaction", "❌ المفتاح الخاص غير صالح!")
return@launch
}

val credentials = Credentials.create(privateKey)
val senderAddress = credentials.address
Log.d("S2LFeeTransaction", "📌 عنوان المرسل: $senderAddress")

// التحقق من الرصيد
val balanceWei = web3.ethGetBalance(senderAddress, org.web3j.protocol.core.DefaultBlockParameterName.LATEST).send().balance
val balanceBNB = Convert.fromWei(balanceWei.toBigDecimal(), Convert.Unit.ETHER)

// التأكد من وجود رصيد كافي
if (balanceBNB < feeAmount) {
Log.e("S2LFeeTransaction", "❌ الرصيد غير كافٍ لتنفيذ المعاملة!")
return@launch
}

// استخدام الـ Nonce المُمرر وعدم استرجاعه مجدداً
Log.d("S2LFeeTransaction", "🔢 Nonce المستخدم: $nonce")

// تحديد سعر الغاز والـ gas limit
val gasPrice = web3.ethGasPrice().send().gasPrice.multiply(BigInteger.valueOf(3)) // زيادة 3x لتجنب التأخير
val gasLimit = BigInteger("2100000")

// تحويل رسوم الـ S2L إلى Wei
val minFee = BigDecimal("0.000001")
val adjustedFeeAmount = feeAmount.setScale(6, RoundingMode.HALF_UP).max(minFee)
val amountInWei = Convert.toWei(adjustedFeeAmount, Convert.Unit.ETHER).toBigInteger()

// إنشاء المعاملة
val transaction = RawTransaction.createTransaction(
nonce,
gasPrice,
gasLimit,
feeAddress,
amountInWei.toString() // تحويل amountInWei إلى String
)
Log.d("S2LFeeTransaction", "📝 المعاملة جاهزة للتوقيع...")

// توقيع المعاملة
val signedTransaction = TransactionEncoder.signMessage(transaction, 56L, credentials)
val hexValue = Numeric.toHexString(signedTransaction)

Log.d("S2LFeeTransaction", "✅ المعاملة موقعة: $hexValue")

// إرسال المعاملة
val response = web3.ethSendRawTransaction(hexValue).send()

if (response.hasError()) {
Log.e("S2LFeeTransaction", "⚠️ خطأ في إرسال المعاملة: ${response.error.message}")
} else {
Log.d("S2LFeeTransaction", "✅ تم إرسال رسوم S2L بنجاح! TxHash: ${response.transactionHash}")
}
} catch (e: Exception) {
Log.e("S2LFeeTransaction", "⚠️ خطأ أثناء إرسال رسوم S2L: ${e.message}", e)
} finally {
Log.d("S2LFeeTransaction", "🔚 انتهاء عملية إرسال الرسوم.")
}
}
}



// **دالة جلب المفتاح من Firestore**
private fun getPrivateKeyFromFirestore(userId: String, callback: (String?) -> Unit) {
val db = FirebaseFirestore.getInstance()
db.collection("walletsnew").document(userId) // تغيير المسار إلى walletsnew
.get()
.addOnSuccessListener { document ->
if (document.exists()) {
val encryptedKey = document.getString("bscPrivateKey") ?: run {
Log.e("Firestore", "❌ مفتاح BSC الخاص غير موجود في المستند")
callback(null)
return@addOnSuccessListener
}

try {
val privateKey = WalletManager.decryptKey(encryptedKey)
callback(privateKey)
} catch (e: Exception) {
Log.e("Decryption", "❌ فشل في فك تشفير المفتاح", e)
callback(null)
}
} else {
Log.e("Firestore", "❌ لم يتم العثور على المحفظة للمستخدم $userId")
callback(null)
}
}
.addOnFailureListener { exception ->
Log.e("Firestore", "❌ خطأ أثناء جلب المحفظة: ${exception.message}")
callback(null)
}
}


fun signTransaction(rawTransaction: RawTransaction?, credentials: Credentials?): String? {
try {
// استخراج المفتاح الخاص
val privateKey = credentials?.ecKeyPair?.privateKey?.toString(16)
if (privateKey.isNullOrBlank() || privateKey.length < 64) {
Log.e("Transaction", "❌ المفتاح الخاص غير صالح أو غير مكتمل! المفتاح المستخرج: $privateKey")
return null
}

Log.d("Withdraw", "المفتاح الخاص: $privateKey")
Log.d("Transaction", "🚀 بدء عملية توقيع المعاملة...")

// التحقق من أن rawTransaction و credentials ليست فارغة
if (rawTransaction == null) {
Log.e("Transaction", "❌ بيانات المعاملة غير متوفرة!")
return null
}
if (credentials == null) {
Log.e("Transaction", "❌ بيانات المستخدم (credentials) غير متوفرة!")
return null
}

// التحقق من صحة بيانات المعاملة
if (rawTransaction.nonce == null || rawTransaction.gasPrice == null ||
rawTransaction.gasLimit == null || rawTransaction.to.isNullOrBlank() ||
rawTransaction.value == null || rawTransaction.value.signum() < 0) {
Log.e("Transaction", "❌ المعاملة تحتوي على بيانات غير صحيحة!")
return null
}

Log.d("Transaction", "🔍 بيانات المعاملة: nonce=${rawTransaction.nonce}, gasPrice=${rawTransaction.gasPrice}, gasLimit=${rawTransaction.gasLimit}, to=${rawTransaction.to}, value=${rawTransaction.value}")

// التحقق من أن credentials تم إنشاؤها بشكل صحيح
if (credentials.ecKeyPair == null) {
Log.e("Transaction", "❌ فشل في إنشاء credentials، المفتاح غير متوفر!")
return null
}

Log.d("Transaction", "🔑 المفتاح الخاص المستخدم: $privateKey")
Log.d("Transaction", "🛠️ عنوان الحساب المستخدم: ${credentials.address}")

// التحقق من أن العنوان صالح
if (credentials.address.isNullOrBlank() || !credentials.address.startsWith("0x")) {
Log.e("Transaction", "❌ العنوان المستخرج غير صحيح!")
return null
}

// تحديد Chain ID المناسب (مناسب لشبكة BSC على سبيل المثال)
val chainId = 56
Log.d("Transaction", "🌐 Chain ID المستخدم: $chainId")

// التأكد من صحة المفتاح باستخدام Web3j
val derivedCredentials = Credentials.create(privateKey)
if (derivedCredentials.address != credentials.address) {
Log.e("Transaction", "❌ فشل في مطابقة المفتاح الخاص مع العنوان المتوقع!")
return null
}

// إنشاء RawTransaction بدلاً من Transaction
val rawTx = RawTransaction.createTransaction(
rawTransaction.nonce,
rawTransaction.gasPrice,
rawTransaction.gasLimit,
rawTransaction.to,
rawTransaction.value,
rawTransaction.data
)

// توقيع المعاملة
Log.d("Transaction", "🔑 توقيع المعاملة باستخدام المفتاح الخاص...")
val signedMessage = TransactionEncoder.signMessage(rawTx, chainId.toLong(), credentials)

// التأكد من أن التوقيع لم يُرجع قيمة `null`
if (signedMessage.isEmpty()) {
Log.e("Transaction", "❌ فشل في توقيع المعاملة، التوقيع غير صالح!")
return null
}

// تحويل التوقيع إلى سلسلة Hex
val signedTx = Numeric.toHexString(signedMessage)
Log.d("Transaction", "✅ تم توقيع المعاملة بنجاح: $signedTx")

// إرسال المعاملة عبر الشبكة (يمكنك دمج هذه الخطوة مع إرسال المعاملة إذا أردت)
return signedTx
} catch (e: Exception) {
// إضافة تفاصيل أكثر للخطأ
Log.e("Transaction", "❌ خطأ غير متوقع أثناء توقيع المعاملة: ${e.message}")
Log.e("Transaction", "❌ تفاصيل الخطأ: ${Log.getStackTraceString(e)}")
return null
}






fun processTransaction(to: String, value: BigDecimal, gasPrice: BigInteger, gasLimit: BigInteger, nonce: BigInteger, credentials: Credentials?) {
try {
Log.d("Transaction", "🚀 بدء معالجة المعاملة...")

// ✅ فحص البيانات المدخلة
if (to.isBlank() || !to.startsWith("0x")) {
Log.e("Transaction", "❌ العنوان غير صالح: $to")
return
}
if (value <= BigDecimal.ZERO) {
Log.e("Transaction", "❌ قيمة المعاملة غير صحيحة: $value")
return
}
if (gasPrice <= BigInteger.ZERO || gasLimit <= BigInteger.ZERO) {
Log.e("Transaction", "❌ إعدادات الغاز غير صحيحة! gasPrice: $gasPrice, gasLimit: $gasLimit")
return
}

Log.d("Transaction", "📌 تفاصيل المعاملة: to=$to, value=$value, gasPrice=$gasPrice, gasLimit=$gasLimit, nonce=$nonce")

// ✅ التأكد من أن credentials ليست فارغة
if (credentials == null) {
Log.e("Transaction", "❌ فشل في الحصول على بيانات credentials!")
return
}


// ✅ إنشاء المعاملة الخام
val rawTransaction = RawTransaction.createEtherTransaction(nonce, gasPrice, gasLimit, to, value.multiply(BigDecimal.TEN.pow(18)).toBigInteger())
Log.d("Withdraw", " gasPrice: " + gasPrice + ", gasLimit: " + gasLimit);
Log.d("Transaction", "🔍 بيانات المعاملة: nonce=${rawTransaction.nonce}, gasPrice=${rawTransaction.gasPrice}, gasLimit=${rawTransaction.gasLimit}, to=${rawTransaction.to}, value=${rawTransaction.value}")

// ✅ التأكد من أن المعاملة تم إنشاؤها بنجاح
if (rawTransaction == null) {
Log.e("Transaction", "❌ فشل في إنشاء المعاملة!")
return
}

Log.d("Transaction", "📜 المعاملة الخام قبل التوقيع: $rawTransaction")

// ✅ تحديد شبكة BSC (56 للـ Mainnet, 97 للـ Testnet)
val chainId = 56
Log.d("Transaction", "🌐 استخدام Chain ID: $chainId")

// ✅ توقيع المعاملة
val signedMessage = try {
TransactionEncoder.signMessage(rawTransaction, chainId.toLong(), credentials)
} catch (e: Exception) {
Log.e("Transaction", "❌ خطأ أثناء توقيع المعاملة: ${e.message}")
Log.e("Transaction", "❌ تفاصيل الخطأ: ${Log.getStackTraceString(e)}")
return
}

// ✅ التأكد من أن التوقيع لم يُرجع `null`
if (signedMessage == null || signedMessage.isEmpty()) {
Log.e("Transaction", "❌ فشل في توقيع المعاملة، التوقيع غير صالح!")
return
}

Log.d("Transaction", "📝 توقيع المعاملة في شكل Bytes: ${signedMessage.joinToString(", ")}")

// تحويل التوقيع إلى Hex
val signedTx = Numeric.toHexString(signedMessage)
Log.d("Transaction", "✅ تم توقيع المعاملة بنجاح: $signedTx")

} catch (e: Exception) {
Log.e("Transaction", "❌ خطأ غير متوقع أثناء تنفيذ المعاملة: ${e.message}")
Log.e("Transaction", "❌ تفاصيل الخطأ: ${Log.getStackTraceString(e)}")
}
}


// 📌 استدعاء الدالة لاختبارها:
processTransaction("0x123...", BigDecimal("10"), BigInteger("1000000000"), BigInteger("2100000"), BigInteger("1"), credentials)
}


// ✅ إرسال المعاملة إلى الشبكة
private fun sendTransaction(signedTx: String, callback: (Boolean) -> Unit) {
CoroutineScope(Dispatchers.IO).launch {
try {
val response = web3j.ethSendRawTransaction(signedTx).send()
val success = !response.hasError()
withContext(Dispatchers.Main) {
callback(success)
}
} catch (e: Exception) {
Log.e("Transaction", "Error sending transaction", e)
withContext(Dispatchers.Main) {
callback(false)
}
}
}
}


private fun createNewWallet(userId: String) {
// 1. إنشاء وإظهار حوار التحميل
val progressDialog = AlertDialog.Builder(this).apply {
setTitle(getString(R.string.creating_wallet))
setMessage(getString(R.string.please_wait))
setView(ProgressBar(this@DashboardActivity).apply {
isIndeterminate = true
})
setCancelable(false)
}.create()

progressDialog.show()

// 2. محاولة إنشاء المحفظة
WalletManager.getOrCreateWallet { wallet ->
runOnUiThread {
// 3. إخفاء حوار التحميل
progressDialog.dismiss()

when {
wallet == null -> {
// 4. معالجة فشل الإنشاء
Log.e("Wallet", "Failed to create wallet for user: $userId")
showErrorAndRetry(userId)
}
!WalletManager.MultiChainWallet.isValidBscAddress(wallet.bscAddress) -> {
// 5. معالجة حالة العنوان غير الصالح
Log.e("Wallet", "Invalid BSC address generated: ${wallet.bscAddress}")
showErrorAndRetry(userId)
}
else -> {
depositAddressTextView.setText(wallet.bscAddress)

lifecycleScope.launch {
updateBalances(wallet)
}

Toast.makeText(
this,
getString(R.string.wallet_created_successfully),
Toast.LENGTH_SHORT
).show()
}

}
}
}
}

// دالة مساعدة لعرض الخطأ وإعادة المحاولة
private fun showErrorAndRetry(userId: String) {
AlertDialog.Builder(this).apply {
setTitle(getString(R.string.error))
setMessage(getString(R.string.wallet_creation_failed_retry))
setPositiveButton(getString(R.string.retry)) { _, _ ->
createNewWallet(userId) // إعادة المحاولة
}
setNegativeButton(getString(R.string.cancel), null)
}.show()
}


private fun executeBNBWithdrawal(
address: String,
amount: BigDecimal,
privateKey: String,
gasLimit: BigInteger,
nonce: BigInteger,
onSuccess: () -> Unit,
onFailure: (String) -> Unit
) {
Log.d("Withdraw", "🚀 بدء تنفيذ سحب BNB...")
Log.d("Withdraw", "📌 العنوان: $address، المبلغ: $amount، Gas Limit: $gasLimit، Nonce: $nonce")

lifecycleScope.launch {
try {
if (privateKey.isBlank()) {
Log.e("Withdraw", "❌ المفتاح الخاص غير موجود!")
onFailure("المفتاح الخاص غير موجود!")
return@launch
}

if (amount <= BigDecimal.ZERO) {
Log.e("Withdraw", "❌ المبلغ غير صالح!")
onFailure("المبلغ غير صالح!")
return@launch
}

if (!isValidAddress(address)) {
Log.e("Withdraw", "❌ عنوان المحفظة غير صالح!")
onFailure("Invalid wallet address!")
return@launch
}

// ✅ توقيع المعاملة باستخدام المفتاح الخاص داخل Coroutine
val signedTx = withContext(Dispatchers.IO) {
signBNBTransaction(privateKey, address, amount, gasLimit, nonce, web3j)
}

if (signedTx.isNullOrBlank()) {
Log.e("Withdraw", "❌ فشل في توقيع المعاملة!")
onFailure("فشل في توقيع المعاملة!")
return@launch
}

Log.d("Withdraw", "📡 إرسال المعاملة إلى الشبكة...")

// ✅ إرسال المعاملة إلى الشبكة
sendTransaction(signedTx) { success ->
lifecycleScope.launch(Dispatchers.Main) {
if (success) {
Log.d("Withdraw", "✅ تم تنفيذ معاملة سحب BNB بنجاح!")
Toast.makeText(this@DashboardActivity, "Withdrawal completed ${amount} BNB To $address", Toast.LENGTH_SHORT).show()
userBalance = userBalance.subtract(amount)
onSuccess()
} else {
Log.e("Withdraw", "❌ فشل في تنفيذ معاملة سحب BNB!")
onFailure("فشل في تنفيذ عملية السحب!")
}
}
}
} catch (e: Exception) {
Log.e("Withdraw", "❌ حدث خطأ أثناء تنفيذ السحب: ${e.message}")
withContext(Dispatchers.Main) {
onFailure("خطأ أثناء السحب: ${e.message}")
}
}
}
}






private suspend fun signBNBTransaction(
privateKey: String,
toAddress: String,
amount: BigDecimal,
gasLimit: BigInteger,
nonce: BigInteger,
web3j: Web3j
): String = withContext(Dispatchers.IO) {
try {
val credentials = Credentials.create(privateKey)
val valueInWei = Convert.toWei(amount, Convert.Unit.ETHER).toBigInteger()
val gasPrice = web3j.ethGasPrice().send().gasPrice

val rawTransaction = RawTransaction.createEtherTransaction(
nonce,
gasPrice,
gasLimit,
toAddress,
valueInWei
)

val signedMessage = TransactionEncoder.signMessage(rawTransaction, 56L, credentials)
Numeric.toHexString(signedMessage)
} catch (e: Exception) {
Log.e("Transaction", "Error signing BNB transaction", e)
""
}
}




private suspend fun signS2LTransaction(
privateKey: String,
toAddress: String,
amount: BigDecimal,
gasLimit: BigInteger,
nonce: BigInteger
): String = withContext(Dispatchers.IO) {
try {
// التحقق من صحة المفتاح الخاص
if (privateKey.length != 64 && !privateKey.startsWith("0x")) {
throw IllegalArgumentException("Invalid private key format")
}

val credentials = try {
Credentials.create(privateKey)
} catch (e: Exception) {
throw IllegalArgumentException("Failed to create credentials from private key")
}

val contractAddress = "0xEd842773464083EbFd207B25257304AFfe4049f1"

// تحويل المبلغ مع مراعاة المنازل العشرية (7 منازل لـ S2L)
val amountInLowestUnit = amount.multiply(BigDecimal.TEN.pow(7)).toBigInteger()

val function = Function(
"transfer",
listOf(Address(toAddress), Uint256(amountInLowestUnit)),
emptyList()
)

val encodedFunction = FunctionEncoder.encode(function)
val gasPrice = getGasPrice()

val rawTransaction = RawTransaction.createTransaction(
nonce,
gasPrice,
gasLimit,
contractAddress,
encodedFunction
)

// Chain ID لشبكة BSC هو 56
val signedMessage = TransactionEncoder.signMessage(rawTransaction, 56L, credentials)
Numeric.toHexString(signedMessage)
} catch (e: Exception) {
Log.e("Transaction", "Error signing S2L transaction", e)
throw e // إعادة رمي الاستثناء للتعامل معه في المستوى الأعلى
}
}

private suspend fun getGasPrice(): BigInteger {
return try {
web3j.ethGasPrice().send().gasPrice
} catch (e: Exception) {
Log.e("Gas", "Error getting gas price", e)
BigInteger.valueOf(20_000_000_000) // Default 20 Gwei
}
}

private suspend fun estimateGasLimit(
from: String,
to: String,
amount: BigDecimal,
web3j: Web3j
): BigInteger {
return try {
// تحويل المبلغ إلى وي ثم إلى سلسلة نصية
val amountInWei = Convert.toWei(amount, Convert.Unit.ETHER).toString()

// إنشاء معاملة التحقق
val transaction = Transaction.createEthCallTransaction(
from,
to,
amountInWei // تم تصحيح نوع البيانات هنا
)

// تقدير الغاز المطلوب
web3j.ethEstimateGas(transaction).send().amountUsed
} catch (e: Exception) {
Log.e("Gas", "Error estimating gas", e)
BigInteger.valueOf(250000) // قيمة افتراضية إذا فشل التقدير
}
}

private fun showLogoutDialog() {
AlertDialog.Builder(this)
.setTitle("log out")
.setMessage("Do you want to log out?")
.setPositiveButton("YES") { _, _ -> logoutUser() }
.setNegativeButton("NO") { dialog, _ -> dialog.dismiss() }
.create()
.show()
}

private fun logoutUser() {
try {
// 1. تسجيل الخروج من Firebase
FirebaseAuth.getInstance().signOut()

// 2. مسح بيانات الجلسة المحلية
val prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE)
prefs.edit().clear().apply()

// 3. إيقاف أي عمليات جارية
lifecycleScope.coroutineContext.cancelChildren()

// 4. الانتقال إلى شاشة الدخول
Intent(this, LoginActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(this)
}
finish()

Toast.makeText(this, "Logged out successfully", Toast.LENGTH_SHORT).show()
} catch (e: Exception) {
Log.e("Logout", "Error during logout", e)
Toast.makeText(this, "Logout failed: ${e.message}", Toast.LENGTH_SHORT).show()
}
}
fun copyAddress(view: View) {
val depositAddress = findViewById<EditText>(R.id.etDepositAddress)
val clipboard = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
val clip = ClipData.newPlainText("Deposit Address", depositAddress.text)
clipboard.setPrimaryClip(clip)
Toast.makeText(this, "Address Copied", Toast.LENGTH_SHORT).show()
}

private fun copyToClipboard(text: String) {
val clipboard = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
val clip = ClipData.newPlainText("Deposit Address", text)
clipboard.setPrimaryClip(clip)
Toast.makeText(this, "Address copied to clipboard!", Toast.LENGTH_SHORT).show()
}
}

إرسال تعليق

0 تعليقات